@k2b/ui 0.49.0 → 0.51.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 (461) hide show
  1. package/dist/base.css +70 -1
  2. package/dist/browser/actions/Button.js.map +1 -1
  3. package/dist/browser/actions/CommandList.js +861 -0
  4. package/dist/browser/actions/CommandList.js.map +1 -0
  5. package/dist/browser/actions/CommandMenu.js +237 -0
  6. package/dist/browser/actions/CommandMenu.js.map +1 -0
  7. package/dist/browser/actions/ContextMenu.js +3 -0
  8. package/dist/browser/actions/ContextMenu.js.map +1 -1
  9. package/dist/browser/actions/Dropdown.js +43 -10
  10. package/dist/browser/actions/Dropdown.js.map +1 -1
  11. package/dist/browser/actions/command-dock.js +47 -0
  12. package/dist/browser/actions/command-dock.js.map +1 -0
  13. package/dist/browser/actions/command-items.js +84 -0
  14. package/dist/browser/actions/command-items.js.map +1 -0
  15. package/dist/browser/actions/command-messages.js +42 -0
  16. package/dist/browser/actions/command-messages.js.map +1 -0
  17. package/dist/browser/actions/index.js +1 -0
  18. package/dist/browser/actions/index.js.map +1 -1
  19. package/dist/browser/charts/core/area.js +188 -0
  20. package/dist/browser/charts/core/area.js.map +1 -0
  21. package/dist/browser/charts/core/calendar.js +186 -0
  22. package/dist/browser/charts/core/calendar.js.map +1 -0
  23. package/dist/browser/charts/core/chart-map-data.js +9 -0
  24. package/dist/browser/charts/core/chart-map-data.js.map +1 -0
  25. package/dist/browser/charts/core/chart-messages.js +17 -0
  26. package/dist/browser/charts/core/chart-messages.js.map +1 -0
  27. package/dist/browser/charts/core/hbar-layout.js +118 -0
  28. package/dist/browser/charts/core/hbar-layout.js.map +1 -0
  29. package/dist/browser/charts/core/hbar.js +39 -0
  30. package/dist/browser/charts/core/hbar.js.map +1 -0
  31. package/dist/browser/charts/core/index.js +17 -0
  32. package/dist/browser/charts/core/index.js.map +1 -0
  33. package/dist/browser/charts/core/inspection.js +9 -0
  34. package/dist/browser/charts/core/inspection.js.map +1 -0
  35. package/dist/browser/charts/core/map.js +116 -0
  36. package/dist/browser/charts/core/map.js.map +1 -0
  37. package/dist/browser/charts/core/registry.js +35 -0
  38. package/dist/browser/charts/core/registry.js.map +1 -0
  39. package/dist/browser/charts/core/render-size.js +13 -0
  40. package/dist/browser/charts/core/render-size.js.map +1 -0
  41. package/dist/browser/charts/core/render.js +113 -0
  42. package/dist/browser/charts/core/render.js.map +1 -0
  43. package/dist/browser/charts/core/snapshot.js +65 -0
  44. package/dist/browser/charts/core/snapshot.js.map +1 -0
  45. package/dist/browser/charts/core/svg-renderers.js +2406 -0
  46. package/dist/browser/charts/core/svg-renderers.js.map +1 -0
  47. package/dist/browser/charts/core/svg.js +21 -0
  48. package/dist/browser/charts/core/svg.js.map +1 -0
  49. package/dist/browser/charts/core/termination.test-fixture.js +162 -0
  50. package/dist/browser/charts/core/termination.test-fixture.js.map +1 -0
  51. package/dist/browser/charts/core/text.js +13 -0
  52. package/dist/browser/charts/core/text.js.map +1 -0
  53. package/dist/browser/charts/core/types.js +6 -0
  54. package/dist/browser/charts/core/types.js.map +1 -0
  55. package/dist/browser/charts/core/waterfall.js +162 -0
  56. package/dist/browser/charts/core/waterfall.js.map +1 -0
  57. package/dist/browser/charts/description.js +2 -0
  58. package/dist/browser/charts/description.js.map +1 -0
  59. package/dist/browser/charts.js +4 -2
  60. package/dist/browser/charts.js.map +1 -1
  61. package/dist/browser/content/BalanceSummary.js +106 -0
  62. package/dist/browser/content/BalanceSummary.js.map +1 -0
  63. package/dist/browser/content/Chart.js +21 -616
  64. package/dist/browser/content/Chart.js.map +1 -1
  65. package/dist/browser/content/ChartExplorer.js +366 -122
  66. package/dist/browser/content/ChartExplorer.js.map +1 -1
  67. package/dist/browser/content/ChartRoot.js +632 -0
  68. package/dist/browser/content/ChartRoot.js.map +1 -0
  69. package/dist/browser/content/ChartSnapshotView.js +16 -9
  70. package/dist/browser/content/ChartSnapshotView.js.map +1 -1
  71. package/dist/browser/content/ChartSparkline.js +24 -0
  72. package/dist/browser/content/ChartSparkline.js.map +1 -0
  73. package/dist/browser/content/DataTable.js +676 -293
  74. package/dist/browser/content/DataTable.js.map +1 -1
  75. package/dist/browser/content/DataTableTools.js +119 -0
  76. package/dist/browser/content/DataTableTools.js.map +1 -0
  77. package/dist/browser/content/FileView.js +111 -61
  78. package/dist/browser/content/FileView.js.map +1 -1
  79. package/dist/browser/content/FlowAmount.js +82 -0
  80. package/dist/browser/content/FlowAmount.js.map +1 -0
  81. package/dist/browser/content/Lightbox.js +8 -8
  82. package/dist/browser/content/Lightbox.js.map +1 -1
  83. package/dist/browser/content/MapView.js +30 -28
  84. package/dist/browser/content/MapView.js.map +1 -1
  85. package/dist/browser/content/PdfPreview.js +84 -52
  86. package/dist/browser/content/PdfPreview.js.map +1 -1
  87. package/dist/browser/content/PdfViewer.js +588 -0
  88. package/dist/browser/content/PdfViewer.js.map +1 -0
  89. package/dist/browser/content/balance-summary-messages.js +26 -0
  90. package/dist/browser/content/balance-summary-messages.js.map +1 -0
  91. package/dist/browser/content/chart-bar.js +251 -21
  92. package/dist/browser/content/chart-bar.js.map +1 -1
  93. package/dist/browser/content/chart-calendar.js +43 -0
  94. package/dist/browser/content/chart-calendar.js.map +1 -0
  95. package/dist/browser/content/chart-inspection-core.js +178 -50
  96. package/dist/browser/content/chart-inspection-core.js.map +1 -1
  97. package/dist/browser/content/chart-inspection.js.map +1 -1
  98. package/dist/browser/content/chart-line-gaps.js +2 -2
  99. package/dist/browser/content/chart-line-gaps.js.map +1 -1
  100. package/dist/browser/content/chart-map-viewport.js.map +1 -1
  101. package/dist/browser/content/chart-message-catalog.js +174 -0
  102. package/dist/browser/content/chart-message-catalog.js.map +1 -0
  103. package/dist/browser/content/chart-messages.js +2 -138
  104. package/dist/browser/content/chart-messages.js.map +1 -1
  105. package/dist/browser/content/chart-snapshot.js +1 -62
  106. package/dist/browser/content/chart-snapshot.js.map +1 -1
  107. package/dist/browser/content/chart-state-timeline.js +1 -1
  108. package/dist/browser/content/chart-state-timeline.js.map +1 -1
  109. package/dist/browser/content/chart-svg.js +4 -2
  110. package/dist/browser/content/chart-svg.js.map +1 -1
  111. package/dist/browser/content/chart-time-axis.js +139 -0
  112. package/dist/browser/content/chart-time-axis.js.map +1 -0
  113. package/dist/browser/content/data-table-columns.js +160 -0
  114. package/dist/browser/content/data-table-columns.js.map +1 -0
  115. package/dist/browser/content/data-table-messages.js +38 -2
  116. package/dist/browser/content/data-table-messages.js.map +1 -1
  117. package/dist/browser/content/flow-amount-messages.js +26 -0
  118. package/dist/browser/content/flow-amount-messages.js.map +1 -0
  119. package/dist/browser/content/index.js +5 -0
  120. package/dist/browser/content/index.js.map +1 -1
  121. package/dist/browser/content/pdf-document.js +29 -0
  122. package/dist/browser/content/pdf-document.js.map +1 -0
  123. package/dist/browser/content/pdf-limits.js +31 -0
  124. package/dist/browser/content/pdf-limits.js.map +1 -0
  125. package/dist/browser/content/pdf-messages.js +34 -2
  126. package/dist/browser/content/pdf-messages.js.map +1 -1
  127. package/dist/browser/content/pdf-viewer-engine.js +57 -0
  128. package/dist/browser/content/pdf-viewer-worker.js +28 -0
  129. package/dist/browser/inputs/ChoiceInputs.js +94 -51
  130. package/dist/browser/inputs/ChoiceInputs.js.map +1 -1
  131. package/dist/browser/inputs/ChoiceSlider.js +75 -58
  132. package/dist/browser/inputs/ChoiceSlider.js.map +1 -1
  133. package/dist/browser/inputs/DatePicker.js +118 -102
  134. package/dist/browser/inputs/DatePicker.js.map +1 -1
  135. package/dist/browser/inputs/PeriodPicker.js +874 -0
  136. package/dist/browser/inputs/PeriodPicker.js.map +1 -0
  137. package/dist/browser/inputs/SelectChip.js +50 -17
  138. package/dist/browser/inputs/SelectChip.js.map +1 -1
  139. package/dist/browser/inputs/date-picker.js +13 -0
  140. package/dist/browser/inputs/date-picker.js.map +1 -1
  141. package/dist/browser/inputs/index.js +4 -1
  142. package/dist/browser/inputs/index.js.map +1 -1
  143. package/dist/browser/inputs/input-messages.js +8 -2
  144. package/dist/browser/inputs/input-messages.js.map +1 -1
  145. package/dist/browser/inputs/markdown/MarkdownEditor.js +14 -10
  146. package/dist/browser/inputs/markdown/MarkdownEditor.js.map +1 -1
  147. package/dist/browser/inputs/markdown/SlashCommands.js +402 -0
  148. package/dist/browser/inputs/markdown/SlashCommands.js.map +1 -0
  149. package/dist/browser/inputs/period-picker-messages.js +71 -0
  150. package/dist/browser/inputs/period-picker-messages.js.map +1 -0
  151. package/dist/browser/inputs/period.js +263 -0
  152. package/dist/browser/inputs/period.js.map +1 -0
  153. package/dist/browser/intl/Format.js +31 -8
  154. package/dist/browser/intl/Format.js.map +1 -1
  155. package/dist/browser/layout/AppWorkspace.js +7 -1
  156. package/dist/browser/layout/AppWorkspace.js.map +1 -1
  157. package/dist/browser/layout/DetailPanel.js +147 -120
  158. package/dist/browser/layout/DetailPanel.js.map +1 -1
  159. package/dist/browser/layout/Discussion.js +101 -108
  160. package/dist/browser/layout/Discussion.js.map +1 -1
  161. package/dist/browser/layout/index.js.map +1 -1
  162. package/dist/browser/surfaces/BudgetList.js +281 -0
  163. package/dist/browser/surfaces/BudgetList.js.map +1 -0
  164. package/dist/browser/surfaces/DescriptionList.js +5 -2
  165. package/dist/browser/surfaces/DescriptionList.js.map +1 -1
  166. package/dist/browser/surfaces/ProgressBar.js +134 -21
  167. package/dist/browser/surfaces/ProgressBar.js.map +1 -1
  168. package/dist/browser/surfaces/StatCell.js +327 -146
  169. package/dist/browser/surfaces/StatCell.js.map +1 -1
  170. package/dist/browser/surfaces/StatGrid.js +75 -57
  171. package/dist/browser/surfaces/StatGrid.js.map +1 -1
  172. package/dist/browser/surfaces/budget-messages.js +64 -0
  173. package/dist/browser/surfaces/budget-messages.js.map +1 -0
  174. package/dist/browser/surfaces/delta-badge.js +79 -0
  175. package/dist/browser/surfaces/delta-badge.js.map +1 -0
  176. package/dist/browser/surfaces/index.js +2 -1
  177. package/dist/browser/surfaces/index.js.map +1 -1
  178. package/dist/browser/surfaces/person-color.js +2 -2
  179. package/dist/browser/surfaces/person-color.js.map +1 -1
  180. package/dist/browser/surfaces/stat-cell-messages.js +41 -0
  181. package/dist/browser/surfaces/stat-cell-messages.js.map +1 -0
  182. package/dist/browser/widgets/Dashboard.js +137 -0
  183. package/dist/browser/widgets/Dashboard.js.map +1 -0
  184. package/dist/browser/widgets/DashboardFrame.js +310 -0
  185. package/dist/browser/widgets/DashboardFrame.js.map +1 -0
  186. package/dist/browser/widgets/index.js +2 -0
  187. package/dist/browser/widgets/index.js.map +1 -1
  188. package/dist/licenses/pdfjs-dist.txt +177 -0
  189. package/dist/ssr/actions/Button.js.map +1 -1
  190. package/dist/ssr/actions/CommandList.js +638 -0
  191. package/dist/ssr/actions/CommandList.js.map +1 -0
  192. package/dist/ssr/actions/CommandMenu.js +197 -0
  193. package/dist/ssr/actions/CommandMenu.js.map +1 -0
  194. package/dist/ssr/actions/ContextMenu.js +3 -0
  195. package/dist/ssr/actions/ContextMenu.js.map +1 -1
  196. package/dist/ssr/actions/Dropdown.js +43 -10
  197. package/dist/ssr/actions/Dropdown.js.map +1 -1
  198. package/dist/ssr/actions/command-dock.js +47 -0
  199. package/dist/ssr/actions/command-dock.js.map +1 -0
  200. package/dist/ssr/actions/command-items.js +84 -0
  201. package/dist/ssr/actions/command-items.js.map +1 -0
  202. package/dist/ssr/actions/command-messages.js +42 -0
  203. package/dist/ssr/actions/command-messages.js.map +1 -0
  204. package/dist/ssr/actions/index.js +1 -0
  205. package/dist/ssr/actions/index.js.map +1 -1
  206. package/dist/ssr/charts/core/area.js +188 -0
  207. package/dist/ssr/charts/core/area.js.map +1 -0
  208. package/dist/ssr/charts/core/calendar.js +186 -0
  209. package/dist/ssr/charts/core/calendar.js.map +1 -0
  210. package/dist/ssr/charts/core/chart-map-data.js +9 -0
  211. package/dist/ssr/charts/core/chart-map-data.js.map +1 -0
  212. package/dist/ssr/charts/core/chart-messages.js +17 -0
  213. package/dist/ssr/charts/core/chart-messages.js.map +1 -0
  214. package/dist/ssr/charts/core/hbar-layout.js +118 -0
  215. package/dist/ssr/charts/core/hbar-layout.js.map +1 -0
  216. package/dist/ssr/charts/core/hbar.js +39 -0
  217. package/dist/ssr/charts/core/hbar.js.map +1 -0
  218. package/dist/ssr/charts/core/index.js +17 -0
  219. package/dist/ssr/charts/core/index.js.map +1 -0
  220. package/dist/ssr/charts/core/inspection.js +9 -0
  221. package/dist/ssr/charts/core/inspection.js.map +1 -0
  222. package/dist/ssr/charts/core/map.js +116 -0
  223. package/dist/ssr/charts/core/map.js.map +1 -0
  224. package/dist/ssr/charts/core/registry.js +35 -0
  225. package/dist/ssr/charts/core/registry.js.map +1 -0
  226. package/dist/ssr/charts/core/render-size.js +13 -0
  227. package/dist/ssr/charts/core/render-size.js.map +1 -0
  228. package/dist/ssr/charts/core/render.js +113 -0
  229. package/dist/ssr/charts/core/render.js.map +1 -0
  230. package/dist/ssr/charts/core/snapshot.js +65 -0
  231. package/dist/ssr/charts/core/snapshot.js.map +1 -0
  232. package/dist/ssr/charts/core/svg-renderers.js +2406 -0
  233. package/dist/ssr/charts/core/svg-renderers.js.map +1 -0
  234. package/dist/ssr/charts/core/svg.js +21 -0
  235. package/dist/ssr/charts/core/svg.js.map +1 -0
  236. package/dist/ssr/charts/core/termination.test-fixture.js +162 -0
  237. package/dist/ssr/charts/core/termination.test-fixture.js.map +1 -0
  238. package/dist/ssr/charts/core/text.js +13 -0
  239. package/dist/ssr/charts/core/text.js.map +1 -0
  240. package/dist/ssr/charts/core/types.js +6 -0
  241. package/dist/ssr/charts/core/types.js.map +1 -0
  242. package/dist/ssr/charts/core/waterfall.js +162 -0
  243. package/dist/ssr/charts/core/waterfall.js.map +1 -0
  244. package/dist/ssr/charts/description.js +2 -0
  245. package/dist/ssr/charts/description.js.map +1 -0
  246. package/dist/ssr/charts.js +4 -2
  247. package/dist/ssr/charts.js.map +1 -1
  248. package/dist/ssr/content/BalanceSummary.js +75 -0
  249. package/dist/ssr/content/BalanceSummary.js.map +1 -0
  250. package/dist/ssr/content/Chart.js +21 -483
  251. package/dist/ssr/content/Chart.js.map +1 -1
  252. package/dist/ssr/content/ChartExplorer.js +190 -46
  253. package/dist/ssr/content/ChartExplorer.js.map +1 -1
  254. package/dist/ssr/content/ChartRoot.js +475 -0
  255. package/dist/ssr/content/ChartRoot.js.map +1 -0
  256. package/dist/ssr/content/ChartSnapshotView.js +5 -1
  257. package/dist/ssr/content/ChartSnapshotView.js.map +1 -1
  258. package/dist/ssr/content/ChartSparkline.js +24 -0
  259. package/dist/ssr/content/ChartSparkline.js.map +1 -0
  260. package/dist/ssr/content/DataTable.js +287 -78
  261. package/dist/ssr/content/DataTable.js.map +1 -1
  262. package/dist/ssr/content/DataTableTools.js +106 -0
  263. package/dist/ssr/content/DataTableTools.js.map +1 -0
  264. package/dist/ssr/content/FileView.js +56 -7
  265. package/dist/ssr/content/FileView.js.map +1 -1
  266. package/dist/ssr/content/FlowAmount.js +58 -0
  267. package/dist/ssr/content/FlowAmount.js.map +1 -0
  268. package/dist/ssr/content/Lightbox.js +8 -8
  269. package/dist/ssr/content/Lightbox.js.map +1 -1
  270. package/dist/ssr/content/MapView.js +9 -9
  271. package/dist/ssr/content/MapView.js.map +1 -1
  272. package/dist/ssr/content/PdfPreview.js +49 -20
  273. package/dist/ssr/content/PdfPreview.js.map +1 -1
  274. package/dist/ssr/content/PdfViewer.js +484 -0
  275. package/dist/ssr/content/PdfViewer.js.map +1 -0
  276. package/dist/ssr/content/balance-summary-messages.js +26 -0
  277. package/dist/ssr/content/balance-summary-messages.js.map +1 -0
  278. package/dist/ssr/content/chart-bar.js +251 -21
  279. package/dist/ssr/content/chart-bar.js.map +1 -1
  280. package/dist/ssr/content/chart-calendar.js +43 -0
  281. package/dist/ssr/content/chart-calendar.js.map +1 -0
  282. package/dist/ssr/content/chart-inspection-core.js +178 -50
  283. package/dist/ssr/content/chart-inspection-core.js.map +1 -1
  284. package/dist/ssr/content/chart-inspection.js.map +1 -1
  285. package/dist/ssr/content/chart-line-gaps.js +2 -2
  286. package/dist/ssr/content/chart-line-gaps.js.map +1 -1
  287. package/dist/ssr/content/chart-map-viewport.js.map +1 -1
  288. package/dist/ssr/content/chart-message-catalog.js +174 -0
  289. package/dist/ssr/content/chart-message-catalog.js.map +1 -0
  290. package/dist/ssr/content/chart-messages.js +2 -138
  291. package/dist/ssr/content/chart-messages.js.map +1 -1
  292. package/dist/ssr/content/chart-snapshot.js +1 -62
  293. package/dist/ssr/content/chart-snapshot.js.map +1 -1
  294. package/dist/ssr/content/chart-state-timeline.js +1 -1
  295. package/dist/ssr/content/chart-state-timeline.js.map +1 -1
  296. package/dist/ssr/content/chart-svg.js +4 -2
  297. package/dist/ssr/content/chart-svg.js.map +1 -1
  298. package/dist/ssr/content/chart-time-axis.js +139 -0
  299. package/dist/ssr/content/chart-time-axis.js.map +1 -0
  300. package/dist/ssr/content/data-table-columns.js +160 -0
  301. package/dist/ssr/content/data-table-columns.js.map +1 -0
  302. package/dist/ssr/content/data-table-messages.js +38 -2
  303. package/dist/ssr/content/data-table-messages.js.map +1 -1
  304. package/dist/ssr/content/flow-amount-messages.js +26 -0
  305. package/dist/ssr/content/flow-amount-messages.js.map +1 -0
  306. package/dist/ssr/content/index.js +5 -0
  307. package/dist/ssr/content/index.js.map +1 -1
  308. package/dist/ssr/content/pdf-document.js +29 -0
  309. package/dist/ssr/content/pdf-document.js.map +1 -0
  310. package/dist/ssr/content/pdf-limits.js +31 -0
  311. package/dist/ssr/content/pdf-limits.js.map +1 -0
  312. package/dist/ssr/content/pdf-messages.js +34 -2
  313. package/dist/ssr/content/pdf-messages.js.map +1 -1
  314. package/dist/ssr/inputs/ChoiceInputs.js +49 -12
  315. package/dist/ssr/inputs/ChoiceInputs.js.map +1 -1
  316. package/dist/ssr/inputs/ChoiceSlider.js +17 -12
  317. package/dist/ssr/inputs/ChoiceSlider.js.map +1 -1
  318. package/dist/ssr/inputs/DatePicker.js +19 -13
  319. package/dist/ssr/inputs/DatePicker.js.map +1 -1
  320. package/dist/ssr/inputs/PeriodPicker.js +598 -0
  321. package/dist/ssr/inputs/PeriodPicker.js.map +1 -0
  322. package/dist/ssr/inputs/SelectChip.js +26 -9
  323. package/dist/ssr/inputs/SelectChip.js.map +1 -1
  324. package/dist/ssr/inputs/date-picker.js +13 -0
  325. package/dist/ssr/inputs/date-picker.js.map +1 -1
  326. package/dist/ssr/inputs/index.js +4 -1
  327. package/dist/ssr/inputs/index.js.map +1 -1
  328. package/dist/ssr/inputs/input-messages.js +8 -2
  329. package/dist/ssr/inputs/input-messages.js.map +1 -1
  330. package/dist/ssr/inputs/markdown/MarkdownEditor.js +3 -2
  331. package/dist/ssr/inputs/markdown/MarkdownEditor.js.map +1 -1
  332. package/dist/ssr/inputs/markdown/SlashCommands.js +339 -0
  333. package/dist/ssr/inputs/markdown/SlashCommands.js.map +1 -0
  334. package/dist/ssr/inputs/period-picker-messages.js +71 -0
  335. package/dist/ssr/inputs/period-picker-messages.js.map +1 -0
  336. package/dist/ssr/inputs/period.js +263 -0
  337. package/dist/ssr/inputs/period.js.map +1 -0
  338. package/dist/ssr/intl/Format.js +22 -2
  339. package/dist/ssr/intl/Format.js.map +1 -1
  340. package/dist/ssr/layout/AppWorkspace.js +7 -1
  341. package/dist/ssr/layout/AppWorkspace.js.map +1 -1
  342. package/dist/ssr/layout/DetailPanel.js +27 -4
  343. package/dist/ssr/layout/DetailPanel.js.map +1 -1
  344. package/dist/ssr/layout/Discussion.js +16 -2
  345. package/dist/ssr/layout/Discussion.js.map +1 -1
  346. package/dist/ssr/layout/index.js.map +1 -1
  347. package/dist/ssr/surfaces/BudgetList.js +170 -0
  348. package/dist/ssr/surfaces/BudgetList.js.map +1 -0
  349. package/dist/ssr/surfaces/DescriptionList.js +1 -1
  350. package/dist/ssr/surfaces/DescriptionList.js.map +1 -1
  351. package/dist/ssr/surfaces/ProgressBar.js +96 -5
  352. package/dist/ssr/surfaces/ProgressBar.js.map +1 -1
  353. package/dist/ssr/surfaces/StatCell.js +157 -52
  354. package/dist/ssr/surfaces/StatCell.js.map +1 -1
  355. package/dist/ssr/surfaces/StatGrid.js +24 -35
  356. package/dist/ssr/surfaces/StatGrid.js.map +1 -1
  357. package/dist/ssr/surfaces/budget-messages.js +64 -0
  358. package/dist/ssr/surfaces/budget-messages.js.map +1 -0
  359. package/dist/ssr/surfaces/delta-badge.js +55 -0
  360. package/dist/ssr/surfaces/delta-badge.js.map +1 -0
  361. package/dist/ssr/surfaces/index.js +2 -1
  362. package/dist/ssr/surfaces/index.js.map +1 -1
  363. package/dist/ssr/surfaces/person-color.js +2 -2
  364. package/dist/ssr/surfaces/person-color.js.map +1 -1
  365. package/dist/ssr/surfaces/stat-cell-messages.js +41 -0
  366. package/dist/ssr/surfaces/stat-cell-messages.js.map +1 -0
  367. package/dist/ssr/widgets/Dashboard.js +84 -0
  368. package/dist/ssr/widgets/Dashboard.js.map +1 -0
  369. package/dist/ssr/widgets/DashboardFrame.js +200 -0
  370. package/dist/ssr/widgets/DashboardFrame.js.map +1 -0
  371. package/dist/ssr/widgets/index.js +2 -0
  372. package/dist/ssr/widgets/index.js.map +1 -1
  373. package/dist/styles.css +1 -1
  374. package/dist/types/actions/Button.d.ts +1 -1
  375. package/dist/types/actions/CommandList.d.ts +120 -0
  376. package/dist/types/actions/CommandMenu.d.ts +39 -0
  377. package/dist/types/actions/Dropdown.d.ts +17 -0
  378. package/dist/types/actions/command-dock.d.ts +8 -0
  379. package/dist/types/actions/command-items.d.ts +134 -0
  380. package/dist/types/actions/command-messages.d.ts +19 -0
  381. package/dist/types/actions/index.d.ts +3 -0
  382. package/dist/types/charts/core/area.d.ts +62 -0
  383. package/dist/types/charts/core/calendar.d.ts +57 -0
  384. package/dist/types/charts/core/chart-map-data.d.ts +3 -0
  385. package/dist/types/charts/core/chart-messages.d.ts +5 -0
  386. package/dist/types/charts/core/hbar-layout.d.ts +74 -0
  387. package/dist/types/charts/core/hbar.d.ts +13 -0
  388. package/dist/types/charts/core/index.d.ts +16 -0
  389. package/dist/types/charts/core/inspection.d.ts +16 -0
  390. package/dist/types/charts/core/map.d.ts +3 -0
  391. package/dist/types/charts/core/registry.d.ts +33 -0
  392. package/dist/types/charts/core/render-size.d.ts +7 -0
  393. package/dist/types/charts/core/render.d.ts +37 -0
  394. package/dist/types/charts/core/snapshot.d.ts +27 -0
  395. package/dist/types/charts/core/svg-renderers.d.ts +722 -0
  396. package/dist/types/charts/core/svg.d.ts +20 -0
  397. package/dist/types/charts/core/termination.test-fixture.d.ts +1 -0
  398. package/dist/types/charts/core/text.d.ts +5 -0
  399. package/dist/types/charts/core/types.d.ts +20 -0
  400. package/dist/types/charts/core/waterfall.d.ts +68 -0
  401. package/dist/types/charts/description.d.ts +226 -0
  402. package/dist/types/charts.d.ts +5 -2
  403. package/dist/types/content/BalanceSummary.d.ts +29 -0
  404. package/dist/types/content/Chart.d.ts +19 -117
  405. package/dist/types/content/ChartExplorer.d.ts +43 -2
  406. package/dist/types/content/ChartRoot.d.ts +92 -0
  407. package/dist/types/content/ChartSnapshotView.d.ts +1 -0
  408. package/dist/types/content/ChartSparkline.d.ts +5 -0
  409. package/dist/types/content/DataTable.d.ts +28 -0
  410. package/dist/types/content/DataTableTools.d.ts +44 -0
  411. package/dist/types/content/FlowAmount.d.ts +28 -0
  412. package/dist/types/content/PdfViewer.d.ts +32 -0
  413. package/dist/types/content/balance-summary-messages.d.ts +11 -0
  414. package/dist/types/content/chart-bar.d.ts +95 -2
  415. package/dist/types/content/chart-calendar.d.ts +4 -0
  416. package/dist/types/content/chart-inspection-core.d.ts +21 -16
  417. package/dist/types/content/chart-inspection.d.ts +5 -1
  418. package/dist/types/content/chart-map-viewport.d.ts +1 -1
  419. package/dist/types/content/chart-message-catalog.d.ts +84 -0
  420. package/dist/types/content/chart-messages.d.ts +2 -33
  421. package/dist/types/content/chart-snapshot.d.ts +1 -26
  422. package/dist/types/content/chart-svg.d.ts +1 -1
  423. package/dist/types/content/chart-time-axis.d.ts +26 -0
  424. package/dist/types/content/data-table-columns.d.ts +72 -0
  425. package/dist/types/content/data-table-messages.d.ts +18 -0
  426. package/dist/types/content/flow-amount-messages.d.ts +11 -0
  427. package/dist/types/content/index.d.ts +12 -2
  428. package/dist/types/content/pdf-document.d.ts +5 -0
  429. package/dist/types/content/pdf-engine.d.ts +9 -0
  430. package/dist/types/content/pdf-limits.d.ts +43 -0
  431. package/dist/types/content/pdf-messages.d.ts +16 -0
  432. package/dist/types/inputs/ChoiceInputs.d.ts +4 -0
  433. package/dist/types/inputs/ChoiceSlider.d.ts +12 -0
  434. package/dist/types/inputs/DatePicker.d.ts +22 -0
  435. package/dist/types/inputs/PeriodPicker.d.ts +24 -0
  436. package/dist/types/inputs/SelectChip.d.ts +2 -0
  437. package/dist/types/inputs/date-picker.d.ts +6 -0
  438. package/dist/types/inputs/index.d.ts +8 -2
  439. package/dist/types/inputs/input-messages.d.ts +3 -0
  440. package/dist/types/inputs/markdown/MarkdownEditor.d.ts +5 -0
  441. package/dist/types/inputs/markdown/SlashCommands.d.ts +20 -0
  442. package/dist/types/inputs/period-picker-messages.d.ts +34 -0
  443. package/dist/types/inputs/period.d.ts +134 -0
  444. package/dist/types/intl/Format.d.ts +5 -0
  445. package/dist/types/layout/AppWorkspace.d.ts +5 -0
  446. package/dist/types/layout/DetailPanel.d.ts +12 -0
  447. package/dist/types/layout/index.d.ts +1 -1
  448. package/dist/types/surfaces/BudgetList.d.ts +42 -0
  449. package/dist/types/surfaces/DescriptionList.d.ts +5 -0
  450. package/dist/types/surfaces/ProgressBar.d.ts +38 -2
  451. package/dist/types/surfaces/StatCell.d.ts +40 -2
  452. package/dist/types/surfaces/StatGrid.d.ts +3 -1
  453. package/dist/types/surfaces/budget-messages.d.ts +30 -0
  454. package/dist/types/surfaces/delta-badge.d.ts +10 -0
  455. package/dist/types/surfaces/index.d.ts +4 -3
  456. package/dist/types/surfaces/person-color.d.ts +2 -2
  457. package/dist/types/surfaces/stat-cell-messages.d.ts +19 -0
  458. package/dist/types/widgets/Dashboard.d.ts +42 -0
  459. package/dist/types/widgets/DashboardFrame.d.ts +58 -0
  460. package/dist/types/widgets/index.d.ts +2 -0
  461. package/package.json +8 -1
@@ -0,0 +1,2406 @@
1
+ // Ported from @k2b/stdlib 0.30.0 (ISC); retain SVG and numeric algorithms until parity proves changes.
2
+ // ==========================
3
+ // SVG Chart Generation
4
+ // ==========================
5
+ //
6
+ // Pure-native SVG generation for the four basic chart types: scatter, line,
7
+ // bar, and pie/donut. Returns SVG strings — inject directly into the DOM,
8
+ // write to disk, or send over the wire. No peer dependencies.
9
+ //
10
+ // Charts ship with embedded default CSS using semantic class names and CSS
11
+ // custom properties for colors. Consumers override styles via class selectors
12
+ // (their CSS wins on specificity) or CSS variables (`--stdlib-chart-c1` ...
13
+ // `--stdlib-chart-c8`). Axes and labels use `currentColor` so parent `color`
14
+ // drives theming (dark mode "just works").
15
+
16
+ // ==========================
17
+ // PUBLIC TYPES
18
+ // ==========================
19
+
20
+ /** Marker shapes for `scatter` data points. Auto-cycles per series when
21
+ * `autoVariant` is enabled on the chart. */
22
+
23
+ /** Line dash patterns for `line` series. Auto-cycles per series when
24
+ * `autoVariant` is enabled. */
25
+
26
+ const itemColorIndex = (item, fallback) => {
27
+ const index = item.colorIndex ?? fallback;
28
+ if (!Number.isInteger(index) || index < 0) throw new RangeError("Chart colorIndex must be a nonnegative integer");
29
+ return index % 8;
30
+ };
31
+ /** One selectable datum in an inspected SVG. Indices refer to the source arrays.
32
+ * `anchor` uses the containing SVG coordinate system, including nested map SVGs.
33
+ * Values are raw data; `formatted` contains the renderer's axis/value formatting.
34
+ */
35
+
36
+ /** Wrap renderer-owned geometry with escaped, inert inspection metadata. */
37
+ export const chartDatumSvg = (svg, datum, inspect, titleText) => {
38
+ if (!inspect || !datum.anchor.every(Number.isFinite)) return svg;
39
+ const title = titleText ?? [datum.label, ...datum.values.map(field => `${field.key}: ${field.formatted ?? field.value}`)].filter(Boolean).join(" · ");
40
+ return `<g data-chart-role="${escapeXml(datum.role)}" data-chart-datum="${escapeXml(JSON.stringify(datum))}"><title>${escapeXml(title)}</title>${svg}</g>`;
41
+ };
42
+ const inspectionPoint = (datum, inspect) => inspect ? chartDatumSvg(`<circle class="stdlib-chart-inspection-point" cx="${fmt(datum.anchor[0])}" cy="${fmt(datum.anchor[1])}" r="3" fill="transparent" stroke="none"/>`, datum, true) : "";
43
+ const pointValues = (p, xAxis, yAxis) => [{
44
+ key: "x",
45
+ value: p.x,
46
+ formatted: xAxis?.format?.(p.x)
47
+ }, {
48
+ key: "y",
49
+ value: p.y,
50
+ formatted: yAxis?.format?.(p.y)
51
+ }, ...Object.entries(p).filter(([key, value]) => key !== "x" && key !== "y" && typeof value === "number" && Number.isFinite(value)).map(([key, value]) => ({
52
+ key,
53
+ value
54
+ }))];
55
+
56
+ /**
57
+ * A horizontal or vertical reference line drawn on a cartesian chart, e.g.
58
+ * for thresholds, targets, or averages.
59
+ */
60
+
61
+ /** Internal shared attributes for raw cartesian charts and UI bar layouts. */
62
+ export const referenceLineAttributes = (ref, label = false) => {
63
+ const declarations = [];
64
+ if (!label && ref.style !== undefined) {
65
+ const styles = {
66
+ solid: "none",
67
+ dashed: "4 4",
68
+ dotted: "1 3"
69
+ };
70
+ const dash = styles[ref.style];
71
+ if (typeof dash !== "string") throw new RangeError("Invalid reference line style");
72
+ declarations.push(`stroke-dasharray:${dash}`);
73
+ if (ref.style === "dotted") declarations.push("stroke-linecap:round");
74
+ }
75
+ if (ref.tone !== undefined) {
76
+ const tones = {
77
+ neutral: "currentColor",
78
+ info: "var(--k2b-info-text,#1d4ed8)",
79
+ success: "var(--k2b-success-text,#047857)",
80
+ warning: "var(--k2b-warning-text,#92400e)",
81
+ danger: "var(--k2b-danger-text,#b91c1c)"
82
+ };
83
+ const color = tones[ref.tone];
84
+ if (typeof color !== "string") throw new RangeError("Invalid reference line tone");
85
+ declarations.push(`color:${color}`);
86
+ }
87
+ return declarations.length ? ` style="${declarations.join(";")}"` : "";
88
+ };
89
+
90
+ // ==========================
91
+ // CONSTANTS
92
+ // ==========================
93
+
94
+ const DEFAULT_WIDTH = 400;
95
+ const DEFAULT_HEIGHT = 240;
96
+ const DEFAULT_PADDING = {
97
+ top: 16,
98
+ right: 16,
99
+ bottom: 32,
100
+ left: 40
101
+ };
102
+ const DEFAULT_TICKS = 5;
103
+ const DEFAULT_MARKERS = ["circle", "square", "triangle", "diamond", "plus", "cross"];
104
+ const DEFAULT_LINE_STYLES = ["solid", "dashed", "dotted", "dashdot"];
105
+
106
+ /** SVG `stroke-dasharray` values per line style. Empty string = no dasharray. */
107
+ const LINE_DASH_PATTERNS = {
108
+ solid: "",
109
+ dashed: "6 4",
110
+ dotted: "2 3",
111
+ dashdot: "6 3 2 3"
112
+ };
113
+
114
+ // CSS rule order is significant. Series-N rules emit first so shape-specific
115
+ // rules below can override (e.g. line's `fill: none` beats series fill, and
116
+ // slice/point's `stroke: white` beats series stroke).
117
+ const DEFAULT_STYLES = `
118
+ /* font-family is intentionally not set here so the chart inherits the app's
119
+ font from its surrounding HTML context. For standalone SVG usage, set
120
+ font-family on a wrapping element or override .stdlib-chart in your CSS. */
121
+ .stdlib-chart {
122
+ color: #1f2937;
123
+ --stdlib-chart-c1: #3b82f6; --stdlib-chart-c2: #10b981;
124
+ --stdlib-chart-c3: #f59e0b; --stdlib-chart-c4: #ef4444;
125
+ --stdlib-chart-c5: #8b5cf6; --stdlib-chart-c6: #ec4899;
126
+ --stdlib-chart-c7: #14b8a6; --stdlib-chart-c8: #f97316;
127
+ }
128
+ .stdlib-chart-series-0 { fill: var(--stdlib-chart-c1); stroke: var(--stdlib-chart-c1); }
129
+ .stdlib-chart-series-1 { fill: var(--stdlib-chart-c2); stroke: var(--stdlib-chart-c2); }
130
+ .stdlib-chart-series-2 { fill: var(--stdlib-chart-c3); stroke: var(--stdlib-chart-c3); }
131
+ .stdlib-chart-series-3 { fill: var(--stdlib-chart-c4); stroke: var(--stdlib-chart-c4); }
132
+ .stdlib-chart-series-4 { fill: var(--stdlib-chart-c5); stroke: var(--stdlib-chart-c5); }
133
+ .stdlib-chart-series-5 { fill: var(--stdlib-chart-c6); stroke: var(--stdlib-chart-c6); }
134
+ .stdlib-chart-series-6 { fill: var(--stdlib-chart-c7); stroke: var(--stdlib-chart-c7); }
135
+ .stdlib-chart-series-7 { fill: var(--stdlib-chart-c8); stroke: var(--stdlib-chart-c8); }
136
+ .stdlib-chart-axis { stroke: currentColor; opacity: 0.4; fill: none; }
137
+ .stdlib-chart-tick-label { font-size: 10px; fill: currentColor; opacity: 0.6; }
138
+ .stdlib-chart-axis-label { font-size: 11px; fill: currentColor; opacity: 0.85; }
139
+ .stdlib-chart-grid { stroke: currentColor; opacity: 0.08; stroke-dasharray: 2 2; fill: none; }
140
+ .stdlib-chart-title { font-size: 14px; font-weight: 600; fill: currentColor; }
141
+ .stdlib-chart-subtitle { font-size: 11px; fill: currentColor; opacity: 0.7; }
142
+ .stdlib-chart-reference { stroke: currentColor; opacity: 0.5; stroke-dasharray: 4 4; fill: none; }
143
+ .stdlib-chart-reference-label { font-size: 10px; fill: currentColor; opacity: 0.7; }
144
+ .stdlib-chart-line { fill: none; stroke-width: 2; }
145
+ .stdlib-chart-area { fill-opacity: 0.18; stroke: none; }
146
+ .stdlib-chart-sparkline { fill: none; stroke-width: 1.5; stroke: currentColor; }
147
+ .stdlib-chart-sparkline-area { stroke: none; }
148
+ .stdlib-chart-sparkline-last { fill: currentColor; stroke: none; }
149
+ .stdlib-chart-sparkline-max { fill: #10b981; stroke: none; }
150
+ .stdlib-chart-sparkline-min { fill: #ef4444; stroke: none; }
151
+ .stdlib-chart-point { stroke: white; stroke-width: 1.5; }
152
+ .stdlib-chart-slice { stroke: white; stroke-width: 2; stroke-linejoin: round; }
153
+ .stdlib-chart-label { font-size: 11px; fill: currentColor; }
154
+ .stdlib-chart-bar-value { font-size: 10px; fill: currentColor; opacity: 0.8; }
155
+ .stdlib-chart-errorbar { stroke: currentColor; opacity: 0.55; fill: none; stroke-width: 1; }
156
+ .stdlib-chart-error-band { fill-opacity: 0.15; stroke: none; }
157
+ .stdlib-chart-trendline { stroke: currentColor; opacity: 0.55; stroke-width: 1.5; fill: none; stroke-dasharray: 5 4; }
158
+ .stdlib-chart-minor-tick { stroke: currentColor; opacity: 0.25; }
159
+ .stdlib-chart-box { fill-opacity: 0.4; stroke-width: 1; }
160
+ .stdlib-chart-box-median { stroke: currentColor; stroke-width: 1.5; fill: none; }
161
+ .stdlib-chart-box-whisker { stroke: currentColor; opacity: 0.6; fill: none; }
162
+ .stdlib-chart-box-cap { stroke: currentColor; opacity: 0.6; fill: none; }
163
+ .stdlib-chart-box-outlier { fill: currentColor; opacity: 0.5; stroke: white; stroke-width: 1; }
164
+ .stdlib-chart-legend-swatch { stroke: none; }
165
+ .stdlib-chart-legend-label { font-size: 11px; font-weight: 400; fill: currentColor; stroke: none; }
166
+ .stdlib-chart-empty-text { font-size: 11px; fill: currentColor; opacity: 0.5; }
167
+ .stdlib-chart-gauge-track { stroke: currentColor; stroke-width: 10; opacity: 0.12; fill: none; stroke-linecap: round; }
168
+ .stdlib-chart-gauge-fill { stroke-width: 10; fill: none; stroke-linecap: round; }
169
+ .stdlib-chart-gauge-gradient-segment { stroke-width: 10; fill: none; stroke-linecap: butt; }
170
+ .stdlib-chart-gauge-gradient-scale { opacity: 0.22; }
171
+ .stdlib-chart-gauge-needle { stroke-width: 2; fill: none; stroke-linecap: round; }
172
+ .stdlib-chart-gauge-hub { fill: currentColor; stroke: none; }
173
+ .stdlib-chart-gauge-value { font-size: 28px; font-weight: 700; fill: currentColor; }
174
+ .stdlib-chart-gauge-label { font-size: 12px; fill: currentColor; opacity: 0.72; }
175
+ .stdlib-chart-gauge-unit { font-size: 11px; fill: currentColor; opacity: 0.6; }
176
+ .stdlib-chart-bar-gauge-track { fill: currentColor; opacity: 0.1; }
177
+ .stdlib-chart-bar-gauge-fill { stroke: none; }
178
+ .stdlib-chart-bar-gauge-label { font-size: 11px; fill: currentColor; opacity: 0.75; }
179
+ .stdlib-chart-bar-gauge-value { font-size: 11px; font-weight: 600; fill: currentColor; }
180
+ .stdlib-chart-stat-label { font-size: 12px; fill: currentColor; opacity: 0.72; }
181
+ .stdlib-chart-stat-value { font-size: 30px; font-weight: 700; fill: currentColor; }
182
+ .stdlib-chart-stat-unit { font-size: 14px; font-weight: 600; fill: currentColor; opacity: 0.72; }
183
+ .stdlib-chart-stat-delta { font-size: 12px; font-weight: 600; fill: currentColor; opacity: 0.72; }
184
+ .stdlib-chart-stat-delta-up { fill: #10b981; opacity: 1; }
185
+ .stdlib-chart-stat-delta-down { fill: #ef4444; opacity: 1; }
186
+ .stdlib-chart-stat-sparkline { fill: none; stroke: currentColor; stroke-width: 1.6; opacity: 0.86; }
187
+ .stdlib-chart-stat-sparkline-area { stroke: none; opacity: 0.18; }
188
+ .stdlib-chart-heatmap-cell { stroke: white; stroke-width: 1; }
189
+ .stdlib-chart-heatmap-label { font-size: 10px; fill: currentColor; opacity: 0.68; }
190
+ .stdlib-chart-map-land { fill: currentColor; opacity: var(--stdlib-chart-map-land-opacity, 0.12); stroke: currentColor; stroke-width: 0.5; stroke-linejoin: round; }
191
+ .stdlib-chart-map-point { stroke: var(--stdlib-chart-map-point-stroke, white); stroke-width: 1.5; }
192
+ .stdlib-chart-map-empty { font-size: 11px; fill: currentColor; opacity: 0.55; }
193
+ .stdlib-chart-state-region { stroke: white; stroke-width: 1; }
194
+ .stdlib-chart-state-label { font-size: 11px; fill: currentColor; opacity: 0.75; }
195
+ `.trim();
196
+
197
+ // ==========================
198
+ // HELPERS (pure)
199
+ // ==========================
200
+
201
+ /** XML-escape a string for safe inclusion in attribute values or text content. */
202
+ export const escapeXml = s => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
203
+
204
+ /** Normalize a `Padding` input (number or partial object) to a full `Padding`. */
205
+ export const normalizePadding = p => {
206
+ if (p === undefined) return {
207
+ ...DEFAULT_PADDING
208
+ };
209
+ if (typeof p === "number") return {
210
+ top: p,
211
+ right: p,
212
+ bottom: p,
213
+ left: p
214
+ };
215
+ return {
216
+ top: p.top ?? DEFAULT_PADDING.top,
217
+ right: p.right ?? DEFAULT_PADDING.right,
218
+ bottom: p.bottom ?? DEFAULT_PADDING.bottom,
219
+ left: p.left ?? DEFAULT_PADDING.left
220
+ };
221
+ };
222
+
223
+ /**
224
+ * Compute `[min, max]` from a list of numeric values, ignoring non-finite
225
+ * entries. Returns `[0, 1]` for an empty/all-non-finite list and pads ±1
226
+ * around a single finite value.
227
+ */
228
+ export const computeDomain = values => {
229
+ let min = Number.POSITIVE_INFINITY;
230
+ let max = Number.NEGATIVE_INFINITY;
231
+ for (const v of values) {
232
+ if (!Number.isFinite(v)) continue;
233
+ if (v < min) min = v;
234
+ if (v > max) max = v;
235
+ }
236
+ if (!Number.isFinite(min) || !Number.isFinite(max)) return [0, 1];
237
+ if (min === max) return [min - 1, max + 1];
238
+ return [min, max];
239
+ };
240
+
241
+ /**
242
+ * Pick a "nice" axis step (1, 2, 5, 10, 20, 50, ...) that splits `range`
243
+ * into roughly `target` intervals. Avoids ugly tick labels like 0.473.
244
+ */
245
+ export const niceStep = (range, target) => {
246
+ if (range <= 0 || target <= 0) return 1;
247
+ const rough = range / target;
248
+ const mag = Math.pow(10, Math.floor(Math.log10(rough)));
249
+ const norm = rough / mag;
250
+ const nice = norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10;
251
+ return nice * mag;
252
+ };
253
+
254
+ /** The most ticks one linear axis counts, the same budget as a time axis; more never fit a readable axis. */
255
+ export const MAX_AXIS_TICKS = 1_000;
256
+
257
+ /**
258
+ * Round `min` down and `max` up to the nearest multiples of `step`, so the
259
+ * domain edges fall on tick boundaries. Returns the extended domain plus the
260
+ * tick values within it (inclusive of both ends).
261
+ */
262
+ export const extendDomainToNice = (min, max, step) => {
263
+ const lo = Math.floor(min / step) * step;
264
+ const hi = Math.ceil(max / step) * step;
265
+ const ticks = [];
266
+ // Use rounding to avoid floating-point drift at tick positions.
267
+ const decimals = Math.max(0, -Math.floor(Math.log10(step)));
268
+ const round = v => Number(v.toFixed(Math.min(decimals + 2, 12)));
269
+ // A step below the float spacing of large values never advances, and a tiny step counts without end: keep the ends.
270
+ const ends = {
271
+ domain: [lo, hi],
272
+ ticks: [...new Set([round(lo), round(hi)])]
273
+ };
274
+ if ((hi - lo) / step > MAX_AXIS_TICKS) return ends;
275
+ for (let v = lo; v <= hi + step / 2;) {
276
+ ticks.push(round(v));
277
+ const next = v + step;
278
+ if (next <= v) return ends;
279
+ v = next;
280
+ }
281
+ return {
282
+ domain: [lo, hi],
283
+ ticks
284
+ };
285
+ };
286
+
287
+ /** Linear map of `value` from input domain `[d0, d1]` to output range `[r0, r1]`. */
288
+ export const mapRange = (value, [d0, d1], [r0, r1]) => {
289
+ if (d1 === d0) return (r0 + r1) / 2;
290
+ return r0 + (value - d0) / (d1 - d0) * (r1 - r0);
291
+ };
292
+
293
+ /**
294
+ * Logarithmic (base-10) map of `value` from input domain `[d0, d1]` to
295
+ * output range `[r0, r1]`. Both domain endpoints must be strictly positive.
296
+ * Non-positive values are clamped to a small epsilon to avoid `-Infinity`.
297
+ */
298
+ export const mapLog = (value, [d0, d1], [r0, r1]) => {
299
+ if (d0 <= 0 || d1 <= 0) return (r0 + r1) / 2;
300
+ const v = Math.max(value, 1e-300);
301
+ const logD0 = Math.log10(d0);
302
+ const logD1 = Math.log10(d1);
303
+ if (logD0 === logD1) return (r0 + r1) / 2;
304
+ return r0 + (Math.log10(v) - logD0) / (logD1 - logD0) * (r1 - r0);
305
+ };
306
+
307
+ /**
308
+ * Compute logarithmic ticks (powers of 10) within `[min, max]`. The
309
+ * returned array always includes both decade boundaries enclosing the
310
+ * domain so the axis line spans the data.
311
+ */
312
+ export const niceLogTicks = (min, max) => {
313
+ const safeMin = Math.max(min, 1e-300);
314
+ const safeMax = Math.max(max, safeMin);
315
+ // Clamp the log-tick range to a finite, SVG-safe span so callers passing
316
+ // Number.MAX_VALUE (or non-finite extremes) don't trigger an infinite loop.
317
+ // 1e-30 .. 1e30 covers every real-world scientific magnitude.
318
+ const MIN_EXP = -30;
319
+ const MAX_EXP = 30;
320
+ const loExp = Math.max(MIN_EXP, Math.floor(Math.log10(safeMin)));
321
+ const hiExp = Math.min(MAX_EXP, Math.ceil(Math.log10(safeMax)));
322
+ const lo = Math.pow(10, loExp);
323
+ const hi = Math.pow(10, Math.max(loExp, hiExp));
324
+ const ticks = [];
325
+ // Iterate by exponent to avoid floating-point drift at extreme ranges.
326
+ for (let e = loExp; e <= Math.max(loExp, hiExp); e++) {
327
+ ticks.push(Math.pow(10, e));
328
+ }
329
+ return {
330
+ domain: [lo, hi],
331
+ ticks
332
+ };
333
+ };
334
+
335
+ /**
336
+ * Least-squares linear regression. Returns slope, intercept, and r² for the
337
+ * regression line `y = slope * x + intercept`. Returns null for fewer than
338
+ * two finite points or all-x-equal input.
339
+ */
340
+ export const linearRegression = points => {
341
+ const finite = points.filter(p => Number.isFinite(p.x) && Number.isFinite(p.y));
342
+ const n = finite.length;
343
+ if (n < 2) return null;
344
+ let sumX = 0;
345
+ let sumY = 0;
346
+ for (const p of finite) {
347
+ sumX += p.x;
348
+ sumY += p.y;
349
+ }
350
+ const meanX = sumX / n;
351
+ const meanY = sumY / n;
352
+ let num = 0;
353
+ let denom = 0;
354
+ let totalSS = 0;
355
+ for (const p of finite) {
356
+ const dx = p.x - meanX;
357
+ const dy = p.y - meanY;
358
+ num += dx * dy;
359
+ denom += dx * dx;
360
+ totalSS += dy * dy;
361
+ }
362
+ if (denom === 0) return null;
363
+ const slope = num / denom;
364
+ const intercept = meanY - slope * meanX;
365
+ // r² via 1 - SSres / SStot
366
+ let resSS = 0;
367
+ for (const p of finite) {
368
+ const predicted = slope * p.x + intercept;
369
+ const resid = p.y - predicted;
370
+ resSS += resid * resid;
371
+ }
372
+ const r2 = totalSS === 0 ? 1 : 1 - resSS / totalSS;
373
+ return {
374
+ slope,
375
+ intercept,
376
+ r2
377
+ };
378
+ };
379
+
380
+ /**
381
+ * Compute box-plot statistics for a set of observations:
382
+ * min/max, quartiles (q1/q2/q3 via R-7 linear interpolation), Tukey whiskers
383
+ * (1.5×IQR rule clamped to data extents), and outliers beyond the whiskers.
384
+ *
385
+ * Returns null for an empty/all-non-finite input.
386
+ */
387
+ export const computeBoxStats = values => {
388
+ const finite = values.filter(v => Number.isFinite(v));
389
+ if (finite.length === 0) return null;
390
+ const sorted = [...finite].sort((a, b) => a - b);
391
+ const quantile = q => {
392
+ // R-7 (linear interpolation between consecutive order statistics).
393
+ const pos = q * (sorted.length - 1);
394
+ const lo = Math.floor(pos);
395
+ const hi = Math.ceil(pos);
396
+ if (lo === hi) return sorted[lo];
397
+ return sorted[lo] + (pos - lo) * (sorted[hi] - sorted[lo]);
398
+ };
399
+ const q1 = quantile(0.25);
400
+ const q2 = quantile(0.5);
401
+ const q3 = quantile(0.75);
402
+ const iqr = q3 - q1;
403
+ const fenceLow = q1 - 1.5 * iqr;
404
+ const fenceHigh = q3 + 1.5 * iqr;
405
+ // Whiskers extend to the most-extreme data point still inside the fences.
406
+ let whiskerLow = q1;
407
+ let whiskerHigh = q3;
408
+ for (const v of sorted) {
409
+ if (v >= fenceLow && v < whiskerLow) whiskerLow = v;
410
+ if (v <= fenceHigh && v > whiskerHigh) whiskerHigh = v;
411
+ }
412
+ const outliers = sorted.filter(v => v < fenceLow || v > fenceHigh);
413
+ return {
414
+ min: sorted[0],
415
+ max: sorted[sorted.length - 1],
416
+ q1,
417
+ q2,
418
+ q3,
419
+ whiskerLow,
420
+ whiskerHigh,
421
+ outliers
422
+ };
423
+ };
424
+
425
+ /**
426
+ * Bin a numeric dataset into a histogram. `bins` may be:
427
+ * - undefined → Sturges' formula `ceil(log2(n)) + 1`
428
+ * - a number → that many equal-width bins
429
+ * - an array of edges (length k+1 → k bins)
430
+ *
431
+ * Non-finite input values are filtered. Returns bin edges and per-bin counts.
432
+ */
433
+ export const autoBin = (values, bins) => {
434
+ const finite = values.filter(v => Number.isFinite(v));
435
+ if (finite.length === 0) return {
436
+ edges: [0, 1],
437
+ counts: [0]
438
+ };
439
+
440
+ // Cap bin count so a malicious / mistyped `bins: 1e9` doesn't allocate
441
+ // gigabytes. 1024 is generous: 30 is Sturges' for 1e9 samples.
442
+ const MAX_BINS = 1024;
443
+ let edges;
444
+ if (Array.isArray(bins)) {
445
+ const sorted = [...bins].filter(e => Number.isFinite(e)).sort((a, b) => a - b);
446
+ if (sorted.length >= 2) {
447
+ edges = sorted;
448
+ } else {
449
+ // Empty or single-edge input → fall back to a single auto-bin span over
450
+ // the data so we never emit `[undefined, NaN]` edges.
451
+ const dmin = Math.min(...finite);
452
+ const dmax = Math.max(...finite);
453
+ edges = dmin === dmax ? [dmin - 0.5, dmin + 0.5] : [dmin, dmax];
454
+ }
455
+ } else {
456
+ // Single-loop min/max — `Math.min(...arr)` fails with RangeError on huge
457
+ // arrays (call-stack overflow) and is also O(n) anyway.
458
+ let min = Infinity;
459
+ let max = -Infinity;
460
+ for (const v of finite) {
461
+ if (v < min) min = v;
462
+ if (v > max) max = v;
463
+ }
464
+ const range = max - min;
465
+ let k;
466
+ if (typeof bins === "number" && bins > 0) {
467
+ k = Math.min(MAX_BINS, Math.floor(bins));
468
+ } else {
469
+ k = Math.max(1, Math.min(MAX_BINS, Math.ceil(Math.log2(finite.length)) + 1));
470
+ }
471
+ if (range === 0) {
472
+ edges = [min - 0.5, min + 0.5];
473
+ } else {
474
+ const step = range / k;
475
+ edges = Array.from({
476
+ length: k + 1
477
+ }, (_, i) => min + i * step);
478
+ }
479
+ }
480
+ const counts = new Array(edges.length - 1).fill(0);
481
+ for (const v of finite) {
482
+ // Right-open intervals [e_i, e_{i+1}); last bin closed-closed.
483
+ let bin = -1;
484
+ for (let i = 0; i < counts.length; i++) {
485
+ const isLast = i === counts.length - 1;
486
+ if (v >= edges[i] && (isLast ? v <= edges[i + 1] : v < edges[i + 1])) {
487
+ bin = i;
488
+ break;
489
+ }
490
+ }
491
+ if (bin >= 0) counts[bin] += 1;
492
+ }
493
+ return {
494
+ edges,
495
+ counts
496
+ };
497
+ };
498
+
499
+ // ==========================
500
+ // SVG SKELETON
501
+ // ==========================
502
+
503
+ export const computePlotArea = (width, height, padding, hasXAxisLabel, hasYAxisLabel, headerHeight = 0, legendHeight = 0) => {
504
+ // Reserve extra space when axis labels are present.
505
+ const extraBottom = hasXAxisLabel ? 14 : 0;
506
+ const extraLeft = hasYAxisLabel ? 14 : 0;
507
+ return {
508
+ x0: padding.left + extraLeft,
509
+ y0: padding.top + headerHeight,
510
+ x1: width - padding.right,
511
+ y1: height - padding.bottom - extraBottom - legendHeight
512
+ };
513
+ };
514
+
515
+ /**
516
+ * Render an optional centered header (title + subtitle) at the top of an
517
+ * SVG. Returns the SVG fragment plus the pixel height it consumed so the
518
+ * caller can shift the plot area down accordingly.
519
+ */
520
+ export const renderHeader = (width, title, subtitle) => {
521
+ if (!title && !subtitle) return {
522
+ svg: "",
523
+ height: 0
524
+ };
525
+ const cx = width / 2;
526
+ const parts = [];
527
+ let y = 16;
528
+ if (title) {
529
+ parts.push(`<text class="stdlib-chart-title" x="${fmt(cx)}" y="${fmt(y)}" text-anchor="middle">${escapeXml(title)}</text>`);
530
+ y += 14;
531
+ }
532
+ if (subtitle) {
533
+ parts.push(`<text class="stdlib-chart-subtitle" x="${fmt(cx)}" y="${fmt(y)}" text-anchor="middle">${escapeXml(subtitle)}</text>`);
534
+ y += 6;
535
+ }
536
+ return {
537
+ svg: parts.join(""),
538
+ height: y
539
+ };
540
+ };
541
+
542
+ /**
543
+ * Render reference lines (horizontal or vertical thresholds) within the plot
544
+ * area. Out-of-domain values are silently skipped. Honors per-axis scale
545
+ * (linear or log).
546
+ */
547
+ const renderReferenceLines = (refs, xAxis, yAxis, area) => {
548
+ const xMap = pickMapper(xAxis.scale);
549
+ const yMap = pickMapper(yAxis.scale);
550
+ const parts = [];
551
+ for (const ref of refs) {
552
+ if (!Number.isFinite(ref.value)) continue;
553
+ const axis = ref.axis ?? "y";
554
+ if (axis === "y") {
555
+ if (ref.value < yAxis.domain[0] || ref.value > yAxis.domain[1]) continue;
556
+ const y = yMap(ref.value, yAxis.domain, [area.y1, area.y0]);
557
+ parts.push(`<line class="stdlib-chart-reference"${referenceLineAttributes(ref)} x1="${fmt(area.x0)}" y1="${fmt(y)}" x2="${fmt(area.x1)}" y2="${fmt(y)}"/>`);
558
+ if (ref.label) {
559
+ parts.push(`<text class="stdlib-chart-reference-label"${referenceLineAttributes(ref, true)} x="${fmt(area.x1 - 4)}" y="${fmt(y - 4)}" text-anchor="end">${escapeXml(ref.label)}</text>`);
560
+ }
561
+ } else {
562
+ if (ref.value < xAxis.domain[0] || ref.value > xAxis.domain[1]) continue;
563
+ const x = xMap(ref.value, xAxis.domain, [area.x0, area.x1]);
564
+ parts.push(`<line class="stdlib-chart-reference"${referenceLineAttributes(ref)} x1="${fmt(x)}" y1="${fmt(area.y0)}" x2="${fmt(x)}" y2="${fmt(area.y1)}"/>`);
565
+ if (ref.label) {
566
+ parts.push(`<text class="stdlib-chart-reference-label"${referenceLineAttributes(ref, true)} x="${fmt(x + 4)}" y="${fmt(area.y0 + 12)}">${escapeXml(ref.label)}</text>`);
567
+ }
568
+ }
569
+ }
570
+ return parts.join("");
571
+ };
572
+
573
+ /**
574
+ * Resolve a point's effective error extents into `[low, high]` magnitudes
575
+ * (relative deltas, both ≥ 0). Asymmetric `errYHigh`/`errYLow` take precedence
576
+ * over symmetric `errY`. Returns null when no error info is set.
577
+ */
578
+ const resolveErrorY = p => {
579
+ const high = p.errYHigh ?? p.errY;
580
+ const low = p.errYLow ?? p.errY;
581
+ if (high === undefined && low === undefined) return null;
582
+ return [Number.isFinite(low) ? Math.abs(low) : 0, Number.isFinite(high) ? Math.abs(high) : 0];
583
+ };
584
+ const resolveErrorX = p => {
585
+ const high = p.errXHigh ?? p.errX;
586
+ const low = p.errXLow ?? p.errX;
587
+ if (high === undefined && low === undefined) return null;
588
+ return [Number.isFinite(low) ? Math.abs(low) : 0, Number.isFinite(high) ? Math.abs(high) : 0];
589
+ };
590
+
591
+ /** Build the SVG fragment for the per-point error bars across all series. */
592
+ const renderErrorBars = (series, xAxis, yAxis, area) => {
593
+ const xMap = pickMapper(xAxis.scale);
594
+ const yMap = pickMapper(yAxis.scale);
595
+ const CAP = 4; // half-width of error bar caps in pixels
596
+ const parts = [];
597
+ for (const s of series) {
598
+ for (const p of s.data) {
599
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) continue;
600
+ const cx = xMap(p.x, xAxis.domain, [area.x0, area.x1]);
601
+ const cy = yMap(p.y, yAxis.domain, [area.y1, area.y0]);
602
+ const yErr = resolveErrorY(p);
603
+ if (yErr) {
604
+ const [low, high] = yErr;
605
+ const yHi = yMap(p.y + high, yAxis.domain, [area.y1, area.y0]);
606
+ const yLo = yMap(p.y - low, yAxis.domain, [area.y1, area.y0]);
607
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx)}" y1="${fmt(yHi)}" x2="${fmt(cx)}" y2="${fmt(yLo)}"/>`);
608
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx - CAP)}" y1="${fmt(yHi)}" x2="${fmt(cx + CAP)}" y2="${fmt(yHi)}"/>`);
609
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx - CAP)}" y1="${fmt(yLo)}" x2="${fmt(cx + CAP)}" y2="${fmt(yLo)}"/>`);
610
+ // Mark we need cy to match data point — ensure we use it (silences unused warnings if any).
611
+ void cy;
612
+ }
613
+ const xErr = resolveErrorX(p);
614
+ if (xErr) {
615
+ const [low, high] = xErr;
616
+ const xHi = xMap(p.x + high, xAxis.domain, [area.x0, area.x1]);
617
+ const xLo = xMap(p.x - low, xAxis.domain, [area.x0, area.x1]);
618
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xLo)}" y1="${fmt(cy)}" x2="${fmt(xHi)}" y2="${fmt(cy)}"/>`);
619
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xLo)}" y1="${fmt(cy - CAP)}" x2="${fmt(xLo)}" y2="${fmt(cy + CAP)}"/>`);
620
+ parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xHi)}" y1="${fmt(cy - CAP)}" x2="${fmt(xHi)}" y2="${fmt(cy + CAP)}"/>`);
621
+ }
622
+ }
623
+ }
624
+ return parts.join("");
625
+ };
626
+
627
+ /** Collect all values relevant for axis-domain computation, including error
628
+ * extents so error bars don't get clipped. */
629
+ const collectAxisValues = (series, axis) => {
630
+ const out = [];
631
+ for (const s of series) {
632
+ for (const p of s.data) {
633
+ const v = axis === "x" ? p.x : p.y;
634
+ if (!Number.isFinite(v)) continue;
635
+ out.push(v);
636
+ const err = axis === "x" ? resolveErrorX(p) : resolveErrorY(p);
637
+ if (err) {
638
+ out.push(v - err[0]);
639
+ out.push(v + err[1]);
640
+ }
641
+ }
642
+ }
643
+ return out;
644
+ };
645
+
646
+ /**
647
+ * Render a single-row centered legend at the bottom of the SVG. Returns the
648
+ * SVG fragment plus the height it consumed so callers can shift the plot
649
+ * area up accordingly. Empty input yields height 0.
650
+ */
651
+ export const renderLegend = (items, width, yTop) => {
652
+ if (items.length === 0) return {
653
+ svg: "",
654
+ height: 0
655
+ };
656
+ const ROW_HEIGHT = 20;
657
+ const ITEM_GAP = 16;
658
+ const SWATCH = 8;
659
+ const SWATCH_GAP = 4;
660
+ const SIDE_PADDING = 4;
661
+ // Approximate text width per character at 11px — good enough for centering.
662
+ const charWidth = 6.5;
663
+ const itemWidths = items.map(it => SWATCH + SWATCH_GAP + Math.max(it.label.length, 1) * charWidth);
664
+
665
+ // Greedy line-break: pack items into rows so each row fits inside the
666
+ // available width. Single-row legends (≤ a few short labels) still render
667
+ // on one line — no visual change for the line/scatter/bar callers that
668
+ // typically have only 2-4 series. Pie/donut with long "Label (XX%)" entries
669
+ // and 5+ slices wrap to multiple rows instead of overflowing the viewBox.
670
+ const availableWidth = Math.max(40, width - 2 * SIDE_PADDING);
671
+ const rows = [];
672
+ let cur = [];
673
+ let curW = 0;
674
+ items.forEach((item, i) => {
675
+ const w = itemWidths[i];
676
+ const projected = cur.length === 0 ? w : curW + ITEM_GAP + w;
677
+ if (cur.length > 0 && projected > availableWidth) {
678
+ rows.push({
679
+ items: cur,
680
+ widths: cur.map((_, j) => itemWidths[i - cur.length + j]),
681
+ totalWidth: curW
682
+ });
683
+ cur = [item];
684
+ curW = w;
685
+ } else {
686
+ cur = [...cur, item];
687
+ curW = projected;
688
+ }
689
+ });
690
+ if (cur.length > 0) {
691
+ rows.push({
692
+ items: cur,
693
+ widths: cur.map((_, j) => itemWidths[items.length - cur.length + j]),
694
+ totalWidth: curW
695
+ });
696
+ }
697
+ const parts = [`<g class="stdlib-chart-legend">`];
698
+ rows.forEach((row, rowIdx) => {
699
+ let cursor = Math.max(SIDE_PADDING, (width - row.totalWidth) / 2);
700
+ const baseY = yTop + ROW_HEIGHT / 2 + rowIdx * ROW_HEIGHT;
701
+ row.items.forEach((item, i) => {
702
+ parts.push(`<g class="stdlib-chart-legend-item stdlib-chart-series-${item.seriesIndex % 8}">`);
703
+ parts.push(`<rect class="stdlib-chart-legend-swatch" x="${fmt(cursor)}" y="${fmt(baseY - SWATCH / 2)}" width="${SWATCH}" height="${SWATCH}" rx="1"/>`);
704
+ parts.push(`<text class="stdlib-chart-legend-label" x="${fmt(cursor + SWATCH + SWATCH_GAP)}" y="${fmt(baseY)}" dominant-baseline="middle">${escapeXml(item.label)}</text>`);
705
+ parts.push(`</g>`);
706
+ cursor += row.widths[i] + ITEM_GAP;
707
+ });
708
+ });
709
+ parts.push(`</g>`);
710
+ return {
711
+ svg: parts.join(""),
712
+ height: rows.length * ROW_HEIGHT
713
+ };
714
+ };
715
+
716
+ /** Measure the total height a legend with `items` will consume in `width`,
717
+ * without actually rendering. Used by chart functions to reserve vertical
718
+ * space before computing the plot area. */
719
+ export const measureLegendHeight = (items, width) => {
720
+ if (items.length === 0) return 0;
721
+ const ROW_HEIGHT = 20;
722
+ const ITEM_GAP = 16;
723
+ const SWATCH = 8;
724
+ const SWATCH_GAP = 4;
725
+ const charWidth = 6.5;
726
+ const availableWidth = Math.max(40, width - 8);
727
+ let curW = 0;
728
+ let rows = 1;
729
+ items.forEach((it, i) => {
730
+ const w = SWATCH + SWATCH_GAP + Math.max(it.label.length, 1) * charWidth;
731
+ const projected = i === 0 ? w : curW + ITEM_GAP + w;
732
+ if (i > 0 && projected > availableWidth) {
733
+ rows++;
734
+ curW = w;
735
+ } else {
736
+ curW = projected;
737
+ }
738
+ });
739
+ return rows * ROW_HEIGHT;
740
+ };
741
+
742
+ /** Wrap chart body in a root `<svg>` with embedded default styles. */
743
+ export const svgRoot = (opts, body) => {
744
+ const cls = opts.className ? `stdlib-chart ${escapeXml(opts.className)}` : "stdlib-chart";
745
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${opts.width} ${opts.height}" class="${cls}"><style>${DEFAULT_STYLES}</style>${body}</svg>`;
746
+ };
747
+
748
+ // ==========================
749
+ // GEOMETRY HELPERS
750
+ // ==========================
751
+
752
+ /** Format an SVG path `d` attribute for a polyline through `points`. */
753
+ export const linePathD = points => {
754
+ if (points.length === 0) return "";
755
+ let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
756
+ for (let i = 1; i < points.length; i++) {
757
+ d += ` L ${fmt(points[i].x)} ${fmt(points[i].y)}`;
758
+ }
759
+ return d;
760
+ };
761
+
762
+ /**
763
+ * Format an SVG path `d` for a smooth curve through `points` using cubic
764
+ * Bezier segments with Catmull-Rom-derived vertical control points.
765
+ *
766
+ * Vertical control points use neighboring `points[i-1]` and `points[i+2]`
767
+ * (reflecting the end points at boundaries) with the standard Catmull-Rom
768
+ * tension factor of 1/6. Horizontal control points stay at the segment's
769
+ * thirds, so x progresses linearly and never doubles back when point spacing
770
+ * is uneven.
771
+ */
772
+ export const smoothPathD = points => {
773
+ const n = points.length;
774
+ if (n === 0) return "";
775
+ if (n === 1) return `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
776
+ if (n === 2) return linePathD(points);
777
+ let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
778
+ for (let i = 0; i < n - 1; i++) {
779
+ const p0 = i > 0 ? points[i - 1] : points[i];
780
+ const p1 = points[i];
781
+ const p2 = points[i + 1];
782
+ const p3 = i + 2 < n ? points[i + 2] : points[i + 1];
783
+ const dx = p2.x - p1.x;
784
+ const cp1x = p1.x + dx / 3;
785
+ const cp1y = p1.y + (p2.y - p0.y) / 6;
786
+ const cp2x = p2.x - dx / 3;
787
+ const cp2y = p2.y - (p3.y - p1.y) / 6;
788
+ d += ` C ${fmt(cp1x)} ${fmt(cp1y)} ${fmt(cp2x)} ${fmt(cp2y)} ${fmt(p2.x)} ${fmt(p2.y)}`;
789
+ }
790
+ return d;
791
+ };
792
+
793
+ /**
794
+ * Build an SVG path `d` attribute for a pie slice (or donut sector).
795
+ *
796
+ * Angles are in radians, measured from the +X axis. Slices grow clockwise,
797
+ * which in SVG's y-down coordinate space means `a1 > a0` produces a clockwise
798
+ * arc when drawn with the large-arc and sweep flags set appropriately.
799
+ *
800
+ * Full-circle (a1 - a0 ≈ 2π) is split into two 180° arcs because a single
801
+ * `A` command can't draw a complete circle unambiguously.
802
+ */
803
+ export const arcPathD = (cx, cy, r, a0, a1, innerR = 0) => {
804
+ const sweep = a1 - a0;
805
+ // Full circle: split into two halves to avoid degenerate `A` command.
806
+ if (sweep >= Math.PI * 2 - 1e-9) {
807
+ const aMid = a0 + Math.PI;
808
+ if (innerR <= 0) {
809
+ const ox0 = cx + r * Math.cos(a0),
810
+ oy0 = cy + r * Math.sin(a0);
811
+ const oxM = cx + r * Math.cos(aMid),
812
+ oyM = cy + r * Math.sin(aMid);
813
+ return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(oxM)} ${fmt(oyM)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(ox0)} ${fmt(oy0)} Z`;
814
+ }
815
+ const ox0 = cx + r * Math.cos(a0),
816
+ oy0 = cy + r * Math.sin(a0);
817
+ const oxM = cx + r * Math.cos(aMid),
818
+ oyM = cy + r * Math.sin(aMid);
819
+ const ix0 = cx + innerR * Math.cos(a0),
820
+ iy0 = cy + innerR * Math.sin(a0);
821
+ const ixM = cx + innerR * Math.cos(aMid),
822
+ iyM = cy + innerR * Math.sin(aMid);
823
+ // Outer ring CW, inner ring CCW (using even-odd fill rule via SVG default).
824
+ return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(oxM)} ${fmt(oyM)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(ox0)} ${fmt(oy0)} Z` + ` M ${fmt(ix0)} ${fmt(iy0)} A ${fmt(innerR)} ${fmt(innerR)} 0 0 0 ${fmt(ixM)} ${fmt(iyM)} A ${fmt(innerR)} ${fmt(innerR)} 0 0 0 ${fmt(ix0)} ${fmt(iy0)} Z`;
825
+ }
826
+ const large = sweep > Math.PI ? 1 : 0;
827
+ const ox0 = cx + r * Math.cos(a0),
828
+ oy0 = cy + r * Math.sin(a0);
829
+ const ox1 = cx + r * Math.cos(a1),
830
+ oy1 = cy + r * Math.sin(a1);
831
+ if (innerR <= 0) {
832
+ return `M ${fmt(cx)} ${fmt(cy)} L ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 ${large} 1 ${fmt(ox1)} ${fmt(oy1)} Z`;
833
+ }
834
+ const ix0 = cx + innerR * Math.cos(a0),
835
+ iy0 = cy + innerR * Math.sin(a0);
836
+ const ix1 = cx + innerR * Math.cos(a1),
837
+ iy1 = cy + innerR * Math.sin(a1);
838
+ return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 ${large} 1 ${fmt(ox1)} ${fmt(oy1)} L ${fmt(ix1)} ${fmt(iy1)} A ${fmt(innerR)} ${fmt(innerR)} 0 ${large} 0 ${fmt(ix0)} ${fmt(iy0)} Z`;
839
+ };
840
+
841
+ /**
842
+ * SVG path `d` for a marker shape centered at `(cx, cy)` with circumradius `r`.
843
+ *
844
+ * The shapes are sized so a typical visual radius matches `r`:
845
+ * - circle: full radius
846
+ * - square: side = sqrt(2)·r so the diagonal equals 2·r (visually balanced
847
+ * next to a circle of the same r)
848
+ * - triangle: equilateral pointing up, circumradius r
849
+ * - diamond: square rotated 45°, half-diagonal = r
850
+ * - plus: cross-shape at thickness r·0.5
851
+ * - cross: X-shape at thickness r·0.4
852
+ */
853
+ export const markerPath = (shape, cx, cy, r) => {
854
+ switch (shape) {
855
+ case "circle":
856
+ // Single arc command pair to draw a closed circle.
857
+ return `M ${fmt(cx - r)} ${fmt(cy)} A ${fmt(r)} ${fmt(r)} 0 1 0 ${fmt(cx + r)} ${fmt(cy)} A ${fmt(r)} ${fmt(r)} 0 1 0 ${fmt(cx - r)} ${fmt(cy)} Z`;
858
+ case "square":
859
+ {
860
+ const s = r * Math.SQRT2 / 2; // half-side
861
+ return `M ${fmt(cx - s)} ${fmt(cy - s)} L ${fmt(cx + s)} ${fmt(cy - s)} L ${fmt(cx + s)} ${fmt(cy + s)} L ${fmt(cx - s)} ${fmt(cy + s)} Z`;
862
+ }
863
+ case "triangle":
864
+ {
865
+ // Equilateral pointing up. Circumradius r.
866
+ const h = r * Math.sin(Math.PI / 3) * 1.5; // altitude from base to apex
867
+ return `M ${fmt(cx)} ${fmt(cy - r)} L ${fmt(cx + h * Math.cos(Math.PI / 6))} ${fmt(cy + r * 0.5)} L ${fmt(cx - h * Math.cos(Math.PI / 6))} ${fmt(cy + r * 0.5)} Z`;
868
+ }
869
+ case "diamond":
870
+ return `M ${fmt(cx)} ${fmt(cy - r)} L ${fmt(cx + r)} ${fmt(cy)} L ${fmt(cx)} ${fmt(cy + r)} L ${fmt(cx - r)} ${fmt(cy)} Z`;
871
+ case "plus":
872
+ {
873
+ const t = r * 0.32; // half-thickness
874
+ return `M ${fmt(cx - r)} ${fmt(cy - t)} L ${fmt(cx - t)} ${fmt(cy - t)} L ${fmt(cx - t)} ${fmt(cy - r)} L ${fmt(cx + t)} ${fmt(cy - r)} L ${fmt(cx + t)} ${fmt(cy - t)} L ${fmt(cx + r)} ${fmt(cy - t)} L ${fmt(cx + r)} ${fmt(cy + t)} L ${fmt(cx + t)} ${fmt(cy + t)} L ${fmt(cx + t)} ${fmt(cy + r)} L ${fmt(cx - t)} ${fmt(cy + r)} L ${fmt(cx - t)} ${fmt(cy + t)} L ${fmt(cx - r)} ${fmt(cy + t)} Z`;
875
+ }
876
+ case "cross":
877
+ {
878
+ // X shape — same as plus rotated 45°. Build by composing two oriented bars.
879
+ const a = r * 0.7;
880
+ const t = r * 0.28;
881
+ return `M ${fmt(cx - a + t)} ${fmt(cy - a - t)} L ${fmt(cx - a - t)} ${fmt(cy - a + t)} L ${fmt(cx + a - t)} ${fmt(cy + a + t)} L ${fmt(cx + a + t)} ${fmt(cy + a - t)} Z` + ` M ${fmt(cx + a - t)} ${fmt(cy - a - t)} L ${fmt(cx + a + t)} ${fmt(cy - a + t)} L ${fmt(cx - a + t)} ${fmt(cy + a + t)} L ${fmt(cx - a - t)} ${fmt(cy + a - t)} Z`;
882
+ }
883
+ }
884
+ };
885
+
886
+ /**
887
+ * SVG path `d` for a step (stair) line. `mode` controls where the vertical
888
+ * step happens relative to the data points:
889
+ * - `before` — vertical step at the new x BEFORE the value updates (state
890
+ * machine "Mealy" style: change at input)
891
+ * - `after` — value updates at the data point's x and persists until next x
892
+ * - `middle` — vertical step at the midpoint between consecutive x-values
893
+ */
894
+ export const stepPathD = (points, mode) => {
895
+ if (points.length === 0) return "";
896
+ if (points.length === 1) return `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
897
+ let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
898
+ for (let i = 1; i < points.length; i++) {
899
+ const p = points[i];
900
+ const prev = points[i - 1];
901
+ if (mode === "before") {
902
+ // step at next-x: extend horizontally to new x at OLD y, then jump to new y.
903
+ d += ` L ${fmt(p.x)} ${fmt(prev.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
904
+ } else if (mode === "after") {
905
+ // step at current-x: jump to new y immediately, persist until next x.
906
+ d += ` L ${fmt(prev.x)} ${fmt(p.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
907
+ } else {
908
+ // middle: step at midpoint of x.
909
+ const mx = (prev.x + p.x) / 2;
910
+ d += ` L ${fmt(mx)} ${fmt(prev.y)} L ${fmt(mx)} ${fmt(p.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
911
+ }
912
+ }
913
+ return d;
914
+ };
915
+
916
+ /** Format a number for SVG attributes — short, no scientific notation. */
917
+ export const fmt = n => {
918
+ if (!Number.isFinite(n)) return "0";
919
+ // 2 decimals is enough for sub-pixel precision at typical sizes.
920
+ const rounded = Math.round(n * 100) / 100;
921
+ return Number.isInteger(rounded) ? `${rounded}` : `${rounded}`;
922
+ };
923
+ export const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
924
+ const normalizeMinMax = (min, max) => {
925
+ const lo = Number.isFinite(min) ? min : 0;
926
+ const hi = Number.isFinite(max) ? max : 100;
927
+ return lo === hi ? [lo, lo + 1] : lo < hi ? [lo, hi] : [hi, lo];
928
+ };
929
+ const formatNumberValue = (value, format, unit = "") => {
930
+ if (!Number.isFinite(value)) return "";
931
+ return `${format ? format(value) : fmt(value)}${unit}`;
932
+ };
933
+ const thresholdFillAttr = color => color ? ` fill="${escapeXml(color)}"` : "";
934
+ const thresholdStrokeAttr = color => color ? ` stroke="${escapeXml(color)}"` : "";
935
+ const polarPoint = (cx, cy, r, angleRad) => ({
936
+ x: cx + r * Math.cos(angleRad),
937
+ y: cy + r * Math.sin(angleRad)
938
+ });
939
+ const arcLinePathD = (cx, cy, r, a0, a1) => {
940
+ const start = polarPoint(cx, cy, r, a0);
941
+ const end = polarPoint(cx, cy, r, a1);
942
+ const large = Math.abs(a1 - a0) > Math.PI ? 1 : 0;
943
+ const sweep = a1 >= a0 ? 1 : 0;
944
+ return `M ${fmt(start.x)} ${fmt(start.y)} A ${fmt(r)} ${fmt(r)} 0 ${large} ${sweep} ${fmt(end.x)} ${fmt(end.y)}`;
945
+ };
946
+ const parseHexColor = color => {
947
+ const short = /^#([0-9a-f]{3})$/i.exec(color);
948
+ if (short) {
949
+ const [r, g, b] = short[1].split("").map(c => Number.parseInt(c + c, 16));
950
+ return {
951
+ r: r,
952
+ g: g,
953
+ b: b
954
+ };
955
+ }
956
+ const long = /^#([0-9a-f]{6})$/i.exec(color);
957
+ if (!long) return null;
958
+ const value = long[1];
959
+ return {
960
+ r: Number.parseInt(value.slice(0, 2), 16),
961
+ g: Number.parseInt(value.slice(2, 4), 16),
962
+ b: Number.parseInt(value.slice(4, 6), 16)
963
+ };
964
+ };
965
+ const hexColor = color => `#${[color.r, color.g, color.b].map(value => clamp(Math.round(value), 0, 255).toString(16).padStart(2, "0")).join("")}`;
966
+ const interpolateColor = (from, to, t) => {
967
+ const a = parseHexColor(from);
968
+ const b = parseHexColor(to);
969
+ if (!a || !b) return t < 0.5 ? from : to;
970
+ return hexColor({
971
+ r: a.r + (b.r - a.r) * t,
972
+ g: a.g + (b.g - a.g) * t,
973
+ b: a.b + (b.b - a.b) * t
974
+ });
975
+ };
976
+ const gaugeThresholdStops = (thresholds, min, max) => {
977
+ if (!thresholds || thresholds.length === 0) return [];
978
+ const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
979
+ if (sorted.length === 0) return [];
980
+ const colorFor = (threshold, index) => threshold.color ?? `var(--stdlib-chart-c${index % 8 + 1})`;
981
+ return [{
982
+ value: min,
983
+ color: colorFor(sorted[0], 0)
984
+ }, ...sorted.map((threshold, index) => ({
985
+ value: clamp(threshold.value, min, max),
986
+ color: colorFor(threshold, index)
987
+ }))];
988
+ };
989
+ const gaugeColorAt = (stops, value) => {
990
+ if (stops.length === 0) return "currentColor";
991
+ for (let i = 1; i < stops.length; i++) {
992
+ const prev = stops[i - 1];
993
+ const next = stops[i];
994
+ if (value <= next.value) {
995
+ const t = next.value === prev.value ? 1 : clamp((value - prev.value) / (next.value - prev.value), 0, 1);
996
+ return interpolateColor(prev.color, next.color, t);
997
+ }
998
+ }
999
+ return stops[stops.length - 1].color;
1000
+ };
1001
+ const renderGaugeGradientSegments = opts => {
1002
+ if (opts.stops.length === 0) return "";
1003
+ const segments = 72;
1004
+ const maxProgress = opts.progress ?? 100;
1005
+ const parts = [];
1006
+ for (let i = 0; i < segments; i++) {
1007
+ const p0 = i / segments * 100;
1008
+ const p1 = Math.min((i + 1) / segments * 100, maxProgress);
1009
+ if (p0 >= maxProgress || p1 <= p0) break;
1010
+ const v0 = mapRange(p0, [0, 100], [opts.min, opts.max]);
1011
+ const v1 = mapRange(p1, [0, 100], [opts.min, opts.max]);
1012
+ const color = gaugeColorAt(opts.stops, (v0 + v1) / 2);
1013
+ const a0 = mapRange(p0, [0, 100], [opts.startAngle, opts.endAngle]);
1014
+ const a1 = mapRange(p1, [0, 100], [opts.startAngle, opts.endAngle]);
1015
+ parts.push(`<path class="${opts.className}" stroke="${escapeXml(color)}" d="${arcLinePathD(opts.cx, opts.cy, opts.radius, a0, a1)}"/>`);
1016
+ }
1017
+ return parts.join("");
1018
+ };
1019
+
1020
+ // ==========================
1021
+ // AXIS RENDERERS
1022
+ // ==========================
1023
+
1024
+ const pickMapper = scale => scale === "log" ? mapLog : mapRange;
1025
+
1026
+ /**
1027
+ * Whether a value is renderable on the given axis. Log axes reject zero and
1028
+ * negative values (since `log(<=0)` is undefined). Used to filter data
1029
+ * points before rendering so we don't emit huge off-plot SVG coordinates.
1030
+ */
1031
+ const isOnAxis = (axis, v) => Number.isFinite(v) && (axis.scale !== "log" || v > 0);
1032
+
1033
+ /**
1034
+ * Compute the domain, major ticks, and (optional) minor ticks for an axis,
1035
+ * choosing linear or log scale per `axisOpts`. Filters non-positive values
1036
+ * out under log scale and falls back to `[1, 10]` if none remain.
1037
+ */
1038
+ const computeAxisScale = (values, axisOpts, fallbackTicks = DEFAULT_TICKS) => {
1039
+ const scale = axisOpts?.scale === "log" ? "log" : "linear";
1040
+ if (axisOpts?.domain) {
1041
+ const [lo, hi] = axisOpts.domain;
1042
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo >= hi || !Number.isFinite(hi - lo) || scale === "log" && lo <= 0) {
1043
+ throw new RangeError("Chart axis domain must have finite increasing bounds (positive for log scales)");
1044
+ }
1045
+ if (values.some(v => Number.isFinite(v) && (scale !== "log" || v > 0) && (v < lo || v > hi))) {
1046
+ throw new RangeError("Chart axis domain must contain all plotted values and bounds");
1047
+ }
1048
+ const ticks = [];
1049
+ if (scale === "log") {
1050
+ for (let exponent = Math.floor(Math.log10(lo)); exponent <= Math.ceil(Math.log10(hi)); exponent++) {
1051
+ const value = 10 ** exponent;
1052
+ if (value > lo && value < hi) ticks.push(value);
1053
+ }
1054
+ } else {
1055
+ const step = niceStep(hi - lo, axisOpts.ticks ?? fallbackTicks);
1056
+ // At extreme magnitudes the step may be smaller than one representable
1057
+ // increment. Keep endpoint ticks instead of entering a non-advancing loop.
1058
+ if (step > 0 && Number.isFinite(step) && (hi - lo) / step <= MAX_AXIS_TICKS) {
1059
+ for (let value = Math.ceil(lo / step) * step; value < hi;) {
1060
+ if (value > lo && (!axisOpts.insetEndpointLabels || value - lo >= step && hi - value >= step)) ticks.push(value);
1061
+ const next = value + step;
1062
+ if (next <= value) break;
1063
+ value = next;
1064
+ }
1065
+ }
1066
+ }
1067
+ return {
1068
+ domain: [lo, hi],
1069
+ ticks: [...new Set([lo, ...ticks.filter(v => v > lo && v < hi), hi])],
1070
+ minorTicks: [],
1071
+ scale
1072
+ };
1073
+ }
1074
+ if (scale === "log") {
1075
+ const positive = values.filter(v => Number.isFinite(v) && v > 0);
1076
+ if (positive.length === 0) {
1077
+ return {
1078
+ domain: [1, 10],
1079
+ ticks: [1, 10],
1080
+ minorTicks: [],
1081
+ scale
1082
+ };
1083
+ }
1084
+ const min = Math.min(...positive);
1085
+ const max = Math.max(...positive);
1086
+ const r = niceLogTicks(min, max);
1087
+ const minorTicks = [];
1088
+ if (axisOpts?.minorTicks) {
1089
+ for (let i = 0; i < r.ticks.length - 1; i++) {
1090
+ const decade = r.ticks[i];
1091
+ for (let m = 2; m <= 9; m++) minorTicks.push(decade * m);
1092
+ }
1093
+ }
1094
+ return {
1095
+ domain: r.domain,
1096
+ ticks: r.ticks,
1097
+ minorTicks,
1098
+ scale
1099
+ };
1100
+ }
1101
+ const [minRaw, maxRaw] = computeDomain(values);
1102
+ const step = niceStep(maxRaw - minRaw, axisOpts?.ticks ?? fallbackTicks);
1103
+ const r = extendDomainToNice(minRaw, maxRaw, step);
1104
+ const minorTicks = [];
1105
+ if (axisOpts?.minorTicks && r.ticks.length > 1) {
1106
+ const SUBDIVISIONS = 5;
1107
+ for (let i = 0; i < r.ticks.length - 1; i++) {
1108
+ const a = r.ticks[i];
1109
+ const b = r.ticks[i + 1];
1110
+ const sub = (b - a) / SUBDIVISIONS;
1111
+ for (let m = 1; m < SUBDIVISIONS; m++) minorTicks.push(a + sub * m);
1112
+ }
1113
+ }
1114
+ return {
1115
+ domain: r.domain,
1116
+ ticks: r.ticks,
1117
+ minorTicks,
1118
+ scale
1119
+ };
1120
+ };
1121
+ const renderYAxis = (axis, area, opts) => {
1122
+ const format = opts?.format ?? (v => String(v));
1123
+ const map = pickMapper(axis.scale);
1124
+ const parts = [];
1125
+ for (const t of axis.ticks) {
1126
+ const y = map(t, axis.domain, [area.y1, area.y0]);
1127
+ parts.push(`<line class="stdlib-chart-grid" x1="${fmt(area.x0)}" y1="${fmt(y)}" x2="${fmt(area.x1)}" y2="${fmt(y)}"/>`);
1128
+ parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(area.x0 - 6)}" y="${fmt(y + 3)}" text-anchor="end">${escapeXml(format(t))}</text>`);
1129
+ }
1130
+ for (const mt of axis.minorTicks) {
1131
+ const y = map(mt, axis.domain, [area.y1, area.y0]);
1132
+ parts.push(`<line class="stdlib-chart-minor-tick" x1="${fmt(area.x0 - 3)}" y1="${fmt(y)}" x2="${fmt(area.x0)}" y2="${fmt(y)}"/>`);
1133
+ }
1134
+ parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y0)}" x2="${fmt(area.x0)}" y2="${fmt(area.y1)}"/>`);
1135
+ if (opts?.label) {
1136
+ const cx = 12;
1137
+ const cy = (area.y0 + area.y1) / 2;
1138
+ parts.push(`<text class="stdlib-chart-axis-label" x="${fmt(cx)}" y="${fmt(cy)}" text-anchor="middle" transform="rotate(-90 ${fmt(cx)} ${fmt(cy)})">${escapeXml(opts.label)}</text>`);
1139
+ }
1140
+ return parts.join("");
1141
+ };
1142
+ const renderXAxisNumeric = (axis, area, height, opts) => {
1143
+ const format = opts?.format ?? (v => String(v));
1144
+ const map = pickMapper(axis.scale);
1145
+ const parts = [];
1146
+ for (const t of axis.ticks) {
1147
+ const x = map(t, axis.domain, [area.x0, area.x1]);
1148
+ const anchor = opts?.domain && opts.insetEndpointLabels ? t === axis.domain[0] ? "start" : t === axis.domain[1] ? "end" : "middle" : "middle";
1149
+ parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(x)}" y="${fmt(area.y1 + 14)}" text-anchor="${anchor}">${escapeXml(format(t))}</text>`);
1150
+ }
1151
+ for (const mt of axis.minorTicks) {
1152
+ const x = map(mt, axis.domain, [area.x0, area.x1]);
1153
+ parts.push(`<line class="stdlib-chart-minor-tick" x1="${fmt(x)}" y1="${fmt(area.y1)}" x2="${fmt(x)}" y2="${fmt(area.y1 + 3)}"/>`);
1154
+ }
1155
+ parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y1)}" x2="${fmt(area.x1)}" y2="${fmt(area.y1)}"/>`);
1156
+ if (opts?.label) {
1157
+ parts.push(`<text class="stdlib-chart-axis-label" x="${fmt((area.x0 + area.x1) / 2)}" y="${fmt(height - 4)}" text-anchor="middle">${escapeXml(opts.label)}</text>`);
1158
+ }
1159
+ return parts.join("");
1160
+ };
1161
+ const renderXAxisCategorical = (labels, area, height, axisLabel) => {
1162
+ const parts = [];
1163
+ if (labels.length > 0) {
1164
+ const step = (area.x1 - area.x0) / labels.length;
1165
+ for (let i = 0; i < labels.length; i++) {
1166
+ const cx = area.x0 + step * (i + 0.5);
1167
+ parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(cx)}" y="${fmt(area.y1 + 14)}" text-anchor="middle">${escapeXml(labels[i])}</text>`);
1168
+ }
1169
+ }
1170
+ parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y1)}" x2="${fmt(area.x1)}" y2="${fmt(area.y1)}"/>`);
1171
+ if (axisLabel) {
1172
+ parts.push(`<text class="stdlib-chart-axis-label" x="${fmt((area.x0 + area.x1) / 2)}" y="${fmt(height - 4)}" text-anchor="middle">${escapeXml(axisLabel)}</text>`);
1173
+ }
1174
+ return parts.join("");
1175
+ };
1176
+ const emptyChart = (width, height, className, message = "no data") => svgRoot({
1177
+ width,
1178
+ height,
1179
+ className
1180
+ }, `<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle" dominant-baseline="middle">${escapeXml(message)}</text>`);
1181
+
1182
+ // ==========================
1183
+ // CHART FUNCTIONS
1184
+ // ==========================
1185
+
1186
+ /**
1187
+ * Render a scatter plot. Each series produces a group of circles, one per
1188
+ * data point, classed `stdlib-chart-series-N` so series colors stay
1189
+ * consistent across charts.
1190
+ *
1191
+ * Non-finite x or y values are filtered out. An empty `series` (or one with
1192
+ * no finite points) renders an empty-state SVG with a "no data" label.
1193
+ *
1194
+ * @example
1195
+ * charts.scatter({ series: [{ data: [{x:1,y:2},{x:2,y:5},{x:3,y:3}] }] });
1196
+ *
1197
+ * @example
1198
+ * charts.scatter({
1199
+ * series: [
1200
+ * { label: "Group A", data: [...] },
1201
+ * { label: "Group B", data: [...] },
1202
+ * ],
1203
+ * xAxis: { label: "Time (s)" },
1204
+ * yAxis: { label: "Value", format: v => `${v}k` },
1205
+ * });
1206
+ */
1207
+ export const scatter = opts => {
1208
+ const width = opts.width ?? DEFAULT_WIDTH;
1209
+ const height = opts.height ?? DEFAULT_HEIGHT;
1210
+ const padding = normalizePadding(opts.padding);
1211
+ const header = renderHeader(width, opts.title, opts.subtitle);
1212
+ const legendItems = collectSeriesLegend(opts);
1213
+ const legendHeight = legendItems.length > 0 ? 20 : 0;
1214
+ const finitePoints = opts.series.flatMap(s => s.data).filter(p => Number.isFinite(p.x) && Number.isFinite(p.y));
1215
+ if (finitePoints.length === 0) return emptyChart(width, height, opts.className);
1216
+ const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, !!opts.yAxis?.label, header.height, legendHeight);
1217
+ const xAxis = computeAxisScale(collectAxisValues(opts.series, "x"), opts.xAxis);
1218
+ const yAxis = computeAxisScale(collectAxisValues(opts.series, "y"), opts.yAxis);
1219
+ const xMap = pickMapper(xAxis.scale);
1220
+ const yMap = pickMapper(yAxis.scale);
1221
+
1222
+ // Size dimension: if any point has a finite `size`, normalize across all
1223
+ // points to the configured pixel range; points without size fall back to
1224
+ // the midpoint so they remain visible.
1225
+ const sizes = finitePoints.map(p => p.size).filter(s => typeof s === "number" && Number.isFinite(s));
1226
+ const sizeRange = opts.sizeRange ?? [3, 12];
1227
+ const useSizes = sizes.length > 0;
1228
+ const sizeDomain = useSizes ? computeDomain(sizes) : [0, 1];
1229
+ const fallbackR = (sizeRange[0] + sizeRange[1]) / 2;
1230
+ const body = [];
1231
+ body.push(renderYAxis(yAxis, area, opts.yAxis));
1232
+ body.push(renderXAxisNumeric(xAxis, area, height - legendHeight, opts.xAxis));
1233
+
1234
+ // Error bars render under the points so the points sit on top of the bar
1235
+ // intersections — easier to read.
1236
+ body.push(renderErrorBars(opts.series, xAxis, yAxis, area));
1237
+ opts.series.forEach((s, i) => {
1238
+ const cls = `stdlib-chart-series-${i % 8}`;
1239
+ const shape = s.marker ?? (opts.autoVariant ? DEFAULT_MARKERS[i % DEFAULT_MARKERS.length] : "circle");
1240
+ const elements = s.data.map((p, index) => ({
1241
+ p,
1242
+ index
1243
+ })).filter(({
1244
+ p
1245
+ }) => isOnAxis(xAxis, p.x) && isOnAxis(yAxis, p.y)).map(({
1246
+ p,
1247
+ index
1248
+ }) => {
1249
+ const cx = xMap(p.x, xAxis.domain, [area.x0, area.x1]);
1250
+ const cy = yMap(p.y, yAxis.domain, [area.y1, area.y0]);
1251
+ const r = useSizes ? typeof p.size === "number" && Number.isFinite(p.size) ? mapRange(p.size, sizeDomain, sizeRange) : fallbackR : 3;
1252
+ const datum = {
1253
+ index,
1254
+ seriesIndex: i,
1255
+ role: "point",
1256
+ label: s.label,
1257
+ anchor: [cx, cy],
1258
+ values: pointValues(p, opts.xAxis, opts.yAxis)
1259
+ };
1260
+ if (shape === "circle") {
1261
+ return chartDatumSvg(`<circle class="stdlib-chart-point" cx="${fmt(cx)}" cy="${fmt(cy)}" r="${fmt(r)}"/>`, datum, opts.inspect);
1262
+ }
1263
+ return chartDatumSvg(`<path class="stdlib-chart-point" d="${markerPath(shape, cx, cy, r)}"/>`, datum, opts.inspect);
1264
+ }).join("");
1265
+ if (elements) body.push(`<g class="${cls}">${elements}</g>`);
1266
+ });
1267
+
1268
+ // Optional trend line (across all series). Renders after data so it's visible.
1269
+ if (opts.trendline) {
1270
+ const reg = linearRegression(finitePoints);
1271
+ if (reg !== null) {
1272
+ const x0 = xAxis.domain[0];
1273
+ const x1 = xAxis.domain[1];
1274
+ const y0 = reg.slope * x0 + reg.intercept;
1275
+ const y1 = reg.slope * x1 + reg.intercept;
1276
+ // Clip to plot area in pixel space (visible portion of the regression).
1277
+ const px0 = xMap(x0, xAxis.domain, [area.x0, area.x1]);
1278
+ const px1 = xMap(x1, xAxis.domain, [area.x0, area.x1]);
1279
+ const py0 = yMap(y0, yAxis.domain, [area.y1, area.y0]);
1280
+ const py1 = yMap(y1, yAxis.domain, [area.y1, area.y0]);
1281
+ body.push(`<line class="stdlib-chart-trendline" x1="${fmt(px0)}" y1="${fmt(py0)}" x2="${fmt(px1)}" y2="${fmt(py1)}"/>`);
1282
+ }
1283
+ }
1284
+
1285
+ // References render AFTER data so labels stay on top (z-order matters in SVG).
1286
+ if (opts.references && opts.references.length > 0) {
1287
+ body.push(renderReferenceLines(opts.references, xAxis, yAxis, area));
1288
+ }
1289
+ const legend = renderLegend(legendItems, width, height - legendHeight);
1290
+ return svgRoot({
1291
+ width,
1292
+ height,
1293
+ className: opts.className
1294
+ }, header.svg + body.join("") + legend.svg);
1295
+ };
1296
+ const collectSeriesLegend = opts => {
1297
+ if (!opts.legend) return [];
1298
+ return opts.series.map((s, i) => ({
1299
+ label: s.label && s.label.length > 0 ? s.label : `Series ${i + 1}`,
1300
+ seriesIndex: i
1301
+ }));
1302
+ };
1303
+
1304
+ /**
1305
+ * Render a line chart. Each series becomes a `<path class="stdlib-chart-line">`
1306
+ * connecting its points (sorted by `x`). Multi-series charts get distinct
1307
+ * `stdlib-chart-series-N` classes.
1308
+ *
1309
+ * Non-finite points are filtered. A series with fewer than 2 finite points
1310
+ * is skipped (no path can be drawn). An empty/all-non-finite chart renders
1311
+ * an empty-state SVG.
1312
+ *
1313
+ * @example
1314
+ * charts.line({ series: [{ data: [{x:1,y:10},{x:2,y:25},{x:3,y:18}] }] });
1315
+ *
1316
+ * @example
1317
+ * charts.line({
1318
+ * series: [
1319
+ * { label: "Revenue", data: [...] },
1320
+ * { label: "Costs", data: [...] },
1321
+ * ],
1322
+ * yAxis: { format: v => `$${v}k` },
1323
+ * });
1324
+ */
1325
+ export const line = opts => {
1326
+ const width = opts.width ?? DEFAULT_WIDTH;
1327
+ const height = opts.height ?? DEFAULT_HEIGHT;
1328
+ const padding = normalizePadding(opts.padding);
1329
+ const header = renderHeader(width, opts.title, opts.subtitle);
1330
+ const legendItems = collectSeriesLegend(opts);
1331
+ const legendHeight = legendItems.length > 0 ? 20 : 0;
1332
+ const finitePoints = opts.series.flatMap(s => s.data).filter(p => Number.isFinite(p.x) && Number.isFinite(p.y));
1333
+ if (finitePoints.length === 0) return emptyChart(width, height, opts.className);
1334
+ const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, !!opts.yAxis?.label, header.height, legendHeight);
1335
+ const xAxis = computeAxisScale(collectAxisValues(opts.series, "x"), opts.xAxis);
1336
+ const yAxis = computeAxisScale(collectAxisValues(opts.series, "y"), opts.yAxis);
1337
+ const xMap = pickMapper(xAxis.scale);
1338
+ const yMap = pickMapper(yAxis.scale);
1339
+ const body = [];
1340
+ body.push(renderYAxis(yAxis, area, opts.yAxis));
1341
+ body.push(renderXAxisNumeric(xAxis, area, height - legendHeight, opts.xAxis));
1342
+
1343
+ // Compute the area baseline (zero if it's in the y-domain, otherwise the
1344
+ // bottom of the plot area). Log axes always start at the bottom.
1345
+ const baselineY = yAxis.scale === "linear" && yAxis.domain[0] <= 0 && yAxis.domain[1] >= 0 ? yMap(0, yAxis.domain, [area.y1, area.y0]) : area.y1;
1346
+
1347
+ // Step plot takes precedence over smooth (treppe with curves doesn't make
1348
+ // sense). Otherwise smooth is the default; explicit `smooth: false` opts out.
1349
+ const pathFn = opts.step ? pts => stepPathD(pts, opts.step) : opts.smooth === false ? linePathD : smoothPathD;
1350
+ opts.series.forEach((s, i) => {
1351
+ const finite = s.data.filter(p => isOnAxis(xAxis, p.x) && isOnAxis(yAxis, p.y));
1352
+ if (opts.inspect) s.data.forEach((p, index) => {
1353
+ if (!isOnAxis(xAxis, p.x) || !isOnAxis(yAxis, p.y)) return;
1354
+ body.push(inspectionPoint({
1355
+ index,
1356
+ seriesIndex: i,
1357
+ role: "point",
1358
+ label: s.label,
1359
+ anchor: [xMap(p.x, xAxis.domain, [area.x0, area.x1]), yMap(p.y, yAxis.domain, [area.y1, area.y0])],
1360
+ values: pointValues(p, opts.xAxis, opts.yAxis)
1361
+ }, opts.inspect));
1362
+ });
1363
+ if (finite.length < 2) return;
1364
+ const sorted = [...finite].sort((a, b) => a.x - b.x);
1365
+ const mapped = sorted.map(p => ({
1366
+ x: xMap(p.x, xAxis.domain, [area.x0, area.x1]),
1367
+ y: yMap(p.y, yAxis.domain, [area.y1, area.y0])
1368
+ }));
1369
+ const linePath = pathFn(mapped);
1370
+
1371
+ // Error band: filled translucent area between errYHigh and errYLow.
1372
+ if (opts.errorBand) {
1373
+ const upper = [];
1374
+ const lower = [];
1375
+ for (const p of sorted) {
1376
+ const err = resolveErrorY(p);
1377
+ if (!err) continue;
1378
+ const [low, high] = err;
1379
+ upper.push({
1380
+ x: xMap(p.x, xAxis.domain, [area.x0, area.x1]),
1381
+ y: yMap(p.y + high, yAxis.domain, [area.y1, area.y0])
1382
+ });
1383
+ lower.push({
1384
+ x: xMap(p.x, xAxis.domain, [area.x0, area.x1]),
1385
+ y: yMap(p.y - low, yAxis.domain, [area.y1, area.y0])
1386
+ });
1387
+ }
1388
+ if (upper.length >= 2) {
1389
+ const upperPath = pathFn(upper);
1390
+ const lowerReversed = lower.slice().reverse();
1391
+ const lowerSegments = lowerReversed.map(pt => ` L ${fmt(pt.x)} ${fmt(pt.y)}`).join("");
1392
+ const bandPath = `${upperPath}${lowerSegments} Z`;
1393
+ body.push(`<path class="stdlib-chart-error-band stdlib-chart-series-${i % 8}" d="${bandPath}"/>`);
1394
+ }
1395
+ }
1396
+ if (opts.area) {
1397
+ const last = mapped[mapped.length - 1];
1398
+ const first = mapped[0];
1399
+ const areaPath = `${linePath} L ${fmt(last.x)} ${fmt(baselineY)} L ${fmt(first.x)} ${fmt(baselineY)} Z`;
1400
+ body.push(`<path class="stdlib-chart-area stdlib-chart-series-${i % 8}" d="${areaPath}"/>`);
1401
+ }
1402
+ const dashStyle = s.lineStyle ?? (opts.autoVariant ? DEFAULT_LINE_STYLES[i % DEFAULT_LINE_STYLES.length] : "solid");
1403
+ const dashAttr = LINE_DASH_PATTERNS[dashStyle];
1404
+ const cls = `stdlib-chart-line stdlib-chart-series-${i % 8}`;
1405
+ const dashAttrStr = dashAttr ? ` stroke-dasharray="${dashAttr}"` : "";
1406
+ body.push(`<path class="${cls}" d="${linePath}"${dashAttrStr}/>`);
1407
+ });
1408
+
1409
+ // Error bars render after lines so caps don't disappear behind the stroke.
1410
+ body.push(renderErrorBars(opts.series, xAxis, yAxis, area));
1411
+
1412
+ // References render AFTER data so labels stay on top.
1413
+ if (opts.references && opts.references.length > 0) {
1414
+ body.push(renderReferenceLines(opts.references, xAxis, yAxis, area));
1415
+ }
1416
+ const legend = renderLegend(legendItems, width, height - legendHeight);
1417
+ return svgRoot({
1418
+ width,
1419
+ height,
1420
+ className: opts.className
1421
+ }, header.svg + body.join("") + legend.svg);
1422
+ };
1423
+
1424
+ // ==========================
1425
+ // BAR
1426
+ // ==========================
1427
+
1428
+ /**
1429
+ * Render a categorical bar chart. The y-domain always includes zero so bars
1430
+ * rest on a visible baseline. Negative values produce bars below the zero
1431
+ * line; mixed positive/negative inputs render the zero line as the X axis.
1432
+ *
1433
+ * Bars use class `stdlib-chart-bar stdlib-chart-series-0` (single-series
1434
+ * only in v1 — grouped/stacked bars are out of scope).
1435
+ *
1436
+ * Non-finite values are filtered. Empty input renders an empty-state SVG.
1437
+ *
1438
+ * @example
1439
+ * charts.bar({ data: [{label:"Q1",value:120},{label:"Q2",value:180}] });
1440
+ *
1441
+ * @example
1442
+ * charts.bar({
1443
+ * data: [{label:"Profit",value:50},{label:"Loss",value:-20}],
1444
+ * yAxis: { format: v => `${v}k` },
1445
+ * });
1446
+ */
1447
+ export const bar = opts => {
1448
+ const width = opts.width ?? DEFAULT_WIDTH;
1449
+ const height = opts.height ?? DEFAULT_HEIGHT;
1450
+ const padding = normalizePadding(opts.padding);
1451
+ const header = renderHeader(width, opts.title, opts.subtitle);
1452
+ const sourceIndices = opts.data.flatMap((d, index) => Number.isFinite(d.value) ? [index] : []);
1453
+ const finite = opts.data.filter(d => Number.isFinite(d.value));
1454
+ if (finite.length === 0) return emptyChart(width, height, opts.className);
1455
+
1456
+ // Legend only useful when bars have distinct colors. Otherwise it's a
1457
+ // redundant single-entry box, so silently drop it.
1458
+ const legendItems = opts.legend && opts.colorByBar ? finite.map((d, i) => ({
1459
+ label: d.label,
1460
+ seriesIndex: itemColorIndex(d, i)
1461
+ })) : [];
1462
+ const legendHeight = legendItems.length > 0 ? 20 : 0;
1463
+ const area = computePlotArea(width, height, padding, false, !!opts.yAxis?.label, header.height, legendHeight);
1464
+ const values = finite.map(d => d.value);
1465
+
1466
+ // For linear scale: include zero so bars rest on a baseline.
1467
+ // For log scale: zero isn't representable; just use the data extent.
1468
+ const yScale = opts.yAxis?.scale === "log" ? "log" : "linear";
1469
+ const valuesForDomain = yScale === "log" ? values : [...values, 0];
1470
+ const yAxis = computeAxisScale(valuesForDomain, opts.yAxis);
1471
+ const yMap = pickMapper(yAxis.scale);
1472
+ const body = [];
1473
+ body.push(renderYAxis(yAxis, area, opts.yAxis));
1474
+ body.push(renderXAxisCategorical(finite.map(d => d.label), area, height - legendHeight, undefined));
1475
+
1476
+ // If domain spans negative and positive (linear only), draw the zero
1477
+ // baseline as a dedicated line on top of the gridlines.
1478
+ if (yAxis.scale === "linear" && yAxis.domain[0] < 0 && yAxis.domain[1] > 0) {
1479
+ const zeroY = yMap(0, yAxis.domain, [area.y1, area.y0]);
1480
+ body.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(zeroY)}" x2="${fmt(area.x1)}" y2="${fmt(zeroY)}"/>`);
1481
+ }
1482
+ const slot = (area.x1 - area.x0) / finite.length;
1483
+ const barWidth = slot * 0.8;
1484
+ const barOffset = slot * 0.1;
1485
+ // Bar baseline: zero on linear scale, bottom of plot for log scale (since
1486
+ // log can't represent zero).
1487
+ const zeroPx = yAxis.scale === "log" ? area.y1 : yMap(0, yAxis.domain, [area.y1, area.y0]);
1488
+ const fmtValue = opts.yAxis?.format ?? (v => String(v));
1489
+ for (let i = 0; i < finite.length; i++) {
1490
+ const d = finite[i];
1491
+ const x = area.x0 + slot * i + barOffset;
1492
+ if (yAxis.scale === "log" && d.value <= 0) continue; // log can't render
1493
+ const valuePx = yMap(d.value, yAxis.domain, [area.y1, area.y0]);
1494
+ const top = Math.min(valuePx, zeroPx);
1495
+ const h = Math.abs(valuePx - zeroPx);
1496
+ const seriesIdx = opts.colorByBar ? itemColorIndex(d, i) : 0;
1497
+ body.push(chartDatumSvg(`<rect class="stdlib-chart-bar stdlib-chart-series-${seriesIdx}" x="${fmt(x)}" y="${fmt(top)}" width="${fmt(barWidth)}" height="${fmt(h)}"/>`, {
1498
+ index: sourceIndices[i],
1499
+ role: "item",
1500
+ label: d.label,
1501
+ anchor: [x + barWidth / 2, top + h / 2],
1502
+ values: [{
1503
+ key: "value",
1504
+ value: d.value,
1505
+ formatted: fmtValue(d.value)
1506
+ }]
1507
+ }, opts.inspect));
1508
+ if (opts.showValues) {
1509
+ const labelY = d.value < 0 ? top + h + 12 : top - 4;
1510
+ const labelX = x + barWidth / 2;
1511
+ body.push(`<text class="stdlib-chart-bar-value" x="${fmt(labelX)}" y="${fmt(labelY)}" text-anchor="middle">${escapeXml(fmtValue(d.value))}</text>`);
1512
+ }
1513
+ }
1514
+
1515
+ // y-axis references render AFTER bars so labels stay on top.
1516
+ // x-axis refs are ignored on bar (the x-axis is categorical).
1517
+ if (opts.references && opts.references.length > 0) {
1518
+ const yRefs = opts.references.filter(r => (r.axis ?? "y") === "y");
1519
+ if (yRefs.length > 0) {
1520
+ body.push(renderReferenceLines(yRefs, {
1521
+ domain: [0, 1],
1522
+ scale: "linear"
1523
+ }, yAxis, area));
1524
+ }
1525
+ }
1526
+ const legend = renderLegend(legendItems, width, height - legendHeight);
1527
+ return svgRoot({
1528
+ width,
1529
+ height,
1530
+ className: opts.className
1531
+ }, header.svg + body.join("") + legend.svg);
1532
+ };
1533
+
1534
+ // ==========================
1535
+ // PIE / DONUT
1536
+ // ==========================
1537
+
1538
+ const renderPie = (opts, defaultInnerRadius) => {
1539
+ const width = opts.width ?? DEFAULT_WIDTH;
1540
+ const height = opts.height ?? DEFAULT_HEIGHT;
1541
+ const header = renderHeader(width, opts.title, opts.subtitle);
1542
+ const sourceIndices = opts.data.flatMap((d, index) => Number.isFinite(d.value) && d.value > 0 ? [index] : []);
1543
+ const finite = opts.data.filter(d => Number.isFinite(d.value) && d.value > 0);
1544
+ const total = finite.reduce((sum, d) => sum + d.value, 0);
1545
+ if (finite.length === 0 || total <= 0) {
1546
+ return emptyChart(width, height, opts.className);
1547
+ }
1548
+
1549
+ // Build legend items up-front (need to measure height before laying out pie).
1550
+ const legendItems = opts.legend ? finite.map((d, i) => {
1551
+ const ratio = d.value / total;
1552
+ const pct = (ratio * 100).toFixed(ratio < 0.1 ? 1 : 0);
1553
+ return {
1554
+ label: `${d.label} (${pct}%)`,
1555
+ seriesIndex: itemColorIndex(d, i)
1556
+ };
1557
+ }) : [];
1558
+ const legendHeight = measureLegendHeight(legendItems, width);
1559
+ const LEGEND_GAP = legendHeight > 0 ? 8 : 0;
1560
+ const innerRatio = Math.max(0, Math.min(0.95, opts.innerRadius ?? defaultInnerRadius));
1561
+ // Reserve outer margin for labels if requested.
1562
+ const baseMargin = 8;
1563
+ const labelMargin = opts.showLabels ? 60 : 0;
1564
+ const margin = baseMargin + labelMargin;
1565
+ // Center vertically in the space below the header, above the legend.
1566
+ const availableHeight = height - header.height - legendHeight - LEGEND_GAP;
1567
+ const cx = width / 2;
1568
+ const cy = header.height + availableHeight / 2;
1569
+ const r = Math.max(0, Math.min(width, availableHeight) / 2 - margin);
1570
+ const innerR = r * innerRatio;
1571
+ const body = [];
1572
+ // Slices clockwise from 12 o'clock (-π/2).
1573
+ let a = -Math.PI / 2;
1574
+ finite.forEach((d, i) => {
1575
+ const sweep = d.value / total * Math.PI * 2;
1576
+ const a1 = a + sweep;
1577
+ const cls = `stdlib-chart-slice stdlib-chart-series-${itemColorIndex(d, i)}`;
1578
+ body.push(chartDatumSvg(`<path class="${cls}" d="${arcPathD(cx, cy, r, a, a1, innerR)}"/>`, {
1579
+ index: sourceIndices[i],
1580
+ role: "item",
1581
+ label: d.label,
1582
+ anchor: [cx + (r + innerR) / 2 * Math.cos(a + sweep / 2), cy + (r + innerR) / 2 * Math.sin(a + sweep / 2)],
1583
+ values: [{
1584
+ key: "value",
1585
+ value: d.value
1586
+ }, {
1587
+ key: "percent",
1588
+ value: d.value / total * 100
1589
+ }, {
1590
+ key: "total",
1591
+ value: total
1592
+ }]
1593
+ }, opts.inspect));
1594
+ if (opts.showLabels) {
1595
+ const mid = a + sweep / 2;
1596
+ // Place label slightly outside the outer radius.
1597
+ const lr = r + 14;
1598
+ const lx = cx + lr * Math.cos(mid);
1599
+ const ly = cy + lr * Math.sin(mid);
1600
+ const pct = (d.value / total * 100).toFixed(d.value / total < 0.1 ? 1 : 0);
1601
+ const anchor = Math.cos(mid) > 0.2 ? "start" : Math.cos(mid) < -0.2 ? "end" : "middle";
1602
+ body.push(`<text class="stdlib-chart-label" x="${fmt(lx)}" y="${fmt(ly + 3)}" text-anchor="${anchor}">${escapeXml(d.label)} (${pct}%)</text>`);
1603
+ }
1604
+ a = a1;
1605
+ });
1606
+ const legend = renderLegend(legendItems, width, height - legendHeight);
1607
+ return svgRoot({
1608
+ width,
1609
+ height,
1610
+ className: opts.className
1611
+ }, header.svg + body.join("") + legend.svg);
1612
+ };
1613
+
1614
+ /**
1615
+ * Render a pie chart. Slices are drawn clockwise starting at 12 o'clock,
1616
+ * proportional to each item's `value`. Pass `showLabels: true` to render
1617
+ * `Label (XX%)` outside each slice, or `legend: true` to render a wrapping
1618
+ * legend below the chart.
1619
+ *
1620
+ * Use `legend` (not `showLabels`) when slices are many or one slice dominates —
1621
+ * outside labels collide in those cases.
1622
+ *
1623
+ * Non-positive and non-finite values are filtered. A 100%-single-slice draws
1624
+ * a complete circle. Empty/all-zero input renders an empty-state SVG.
1625
+ *
1626
+ * @example
1627
+ * charts.pie({ data: [{label:"A",value:30},{label:"B",value:50},{label:"C",value:20}] });
1628
+ *
1629
+ * @example
1630
+ * charts.pie({ data: [...], showLabels: true });
1631
+ *
1632
+ * @example
1633
+ * charts.pie({ data: [...], legend: true }); // recommended for many small slices
1634
+ */
1635
+ export const pie = opts => renderPie(opts, 0);
1636
+
1637
+ /**
1638
+ * Render a donut chart. Identical to {@link pie} but with a hollow center
1639
+ * (default `innerRadius: 0.6`). Override `innerRadius` for a thicker or
1640
+ * thinner ring.
1641
+ *
1642
+ * @example
1643
+ * charts.donut({ data: [{label:"Used",value:67},{label:"Free",value:33}] });
1644
+ *
1645
+ * @example
1646
+ * charts.donut({ data: [...], innerRadius: 0.4, showLabels: true });
1647
+ *
1648
+ * @example
1649
+ * charts.donut({ data: [...], legend: true }); // wrapping legend below the ring
1650
+ */
1651
+ export const donut = opts => renderPie(opts, 0.6);
1652
+
1653
+ // ==========================
1654
+ // HISTOGRAM
1655
+ // ==========================
1656
+
1657
+ /**
1658
+ * Render a histogram (frequency distribution) of the given observations.
1659
+ * Uses Sturges' formula by default for bin count, or accepts an explicit
1660
+ * count or list of bin edges.
1661
+ *
1662
+ * Bars are adjacent (no inter-bar gap) since a histogram represents a
1663
+ * continuous distribution. The x-axis is numeric (bin edges as ticks).
1664
+ *
1665
+ * @example
1666
+ * charts.histogram({ data: observations, title: "Reaction times (ms)" });
1667
+ *
1668
+ * @example
1669
+ * charts.histogram({ data: scores, bins: 20, yAxis: { label: "Count" } });
1670
+ */
1671
+ export const histogram = opts => {
1672
+ const width = opts.width ?? DEFAULT_WIDTH;
1673
+ const height = opts.height ?? DEFAULT_HEIGHT;
1674
+ const padding = normalizePadding(opts.padding);
1675
+ const header = renderHeader(width, opts.title, opts.subtitle);
1676
+ const finite = opts.data.filter(v => Number.isFinite(v));
1677
+ if (finite.length === 0) return emptyChart(width, height, opts.className);
1678
+ const {
1679
+ edges,
1680
+ counts
1681
+ } = autoBin(finite, opts.bins);
1682
+ const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, !!opts.yAxis?.label, header.height, 0);
1683
+ const xAxis = computeAxisScale(edges, opts.xAxis);
1684
+ const yAxis = computeAxisScale([0, ...counts], opts.yAxis);
1685
+ const xMap = pickMapper(xAxis.scale);
1686
+ const yMap = pickMapper(yAxis.scale);
1687
+ const body = [];
1688
+ body.push(renderYAxis(yAxis, area, opts.yAxis));
1689
+ body.push(renderXAxisNumeric(xAxis, area, height, opts.xAxis));
1690
+ const zeroPx = yAxis.scale === "log" ? area.y1 : yMap(0, yAxis.domain, [area.y1, area.y0]);
1691
+ for (let i = 0; i < counts.length; i++) {
1692
+ const left = xMap(edges[i], xAxis.domain, [area.x0, area.x1]);
1693
+ const right = xMap(edges[i + 1], xAxis.domain, [area.x0, area.x1]);
1694
+ const c = counts[i];
1695
+ if (yAxis.scale === "log" && c <= 0) continue;
1696
+ const top = yMap(c, yAxis.domain, [area.y1, area.y0]);
1697
+ body.push(chartDatumSvg(`<rect class="stdlib-chart-bar stdlib-chart-series-0" x="${fmt(left)}" y="${fmt(top)}" width="${fmt(right - left)}" height="${fmt(zeroPx - top)}"/>`, {
1698
+ index: i,
1699
+ role: "bin",
1700
+ anchor: [(left + right) / 2, (top + zeroPx) / 2],
1701
+ values: [{
1702
+ key: "from",
1703
+ value: edges[i],
1704
+ formatted: opts.xAxis?.format?.(edges[i])
1705
+ }, {
1706
+ key: "to",
1707
+ value: edges[i + 1],
1708
+ formatted: opts.xAxis?.format?.(edges[i + 1])
1709
+ }, {
1710
+ key: "upperInclusive",
1711
+ value: i === counts.length - 1 ? "true" : "false"
1712
+ }, {
1713
+ key: "count",
1714
+ value: c
1715
+ }]
1716
+ }, opts.inspect));
1717
+ }
1718
+ if (opts.references && opts.references.length > 0) {
1719
+ body.push(renderReferenceLines(opts.references, xAxis, yAxis, area));
1720
+ }
1721
+ return svgRoot({
1722
+ width,
1723
+ height,
1724
+ className: opts.className
1725
+ }, header.svg + body.join(""));
1726
+ };
1727
+
1728
+ // ==========================
1729
+ // BOX PLOT
1730
+ // ==========================
1731
+
1732
+ /**
1733
+ * Render a box plot (Tukey style): box for the IQR (Q1-Q3), median line,
1734
+ * whiskers extending to 1.5×IQR fences, and individual outlier dots.
1735
+ *
1736
+ * Useful for comparing distributions across categorical groups (e.g. test
1737
+ * scores per class, reaction times per condition).
1738
+ *
1739
+ * @example
1740
+ * charts.boxplot({
1741
+ * groups: [
1742
+ * { label: "Class A", values: scoresA },
1743
+ * { label: "Class B", values: scoresB },
1744
+ * ],
1745
+ * yAxis: { label: "Score" },
1746
+ * });
1747
+ */
1748
+ export const boxplot = opts => {
1749
+ const width = opts.width ?? DEFAULT_WIDTH;
1750
+ const height = opts.height ?? DEFAULT_HEIGHT;
1751
+ const padding = normalizePadding(opts.padding);
1752
+ const header = renderHeader(width, opts.title, opts.subtitle);
1753
+ const showOutliers = opts.showOutliers ?? true;
1754
+ const stats = opts.groups.map((g, index) => ({
1755
+ index,
1756
+ count: g.values.filter(Number.isFinite).length,
1757
+ label: g.label,
1758
+ s: computeBoxStats(g.values)
1759
+ }));
1760
+ const valid = stats.filter(g => g.s !== null);
1761
+ if (valid.length === 0) return emptyChart(width, height, opts.className);
1762
+ const area = computePlotArea(width, height, padding, false, !!opts.yAxis?.label, header.height, 0);
1763
+
1764
+ // Collect all values relevant for the y-domain: whisker extremes + outliers.
1765
+ const axisValues = [];
1766
+ for (const g of valid) {
1767
+ axisValues.push(g.s.whiskerLow, g.s.whiskerHigh);
1768
+ if (showOutliers) axisValues.push(...g.s.outliers);
1769
+ }
1770
+ const yAxis = computeAxisScale(axisValues, opts.yAxis);
1771
+ const yMap = pickMapper(yAxis.scale);
1772
+ const body = [];
1773
+ body.push(renderYAxis(yAxis, area, opts.yAxis));
1774
+ body.push(renderXAxisCategorical(valid.map(g => g.label), area, height, undefined));
1775
+ const slot = (area.x1 - area.x0) / valid.length;
1776
+ const boxWidth = slot * 0.6;
1777
+ const boxOffset = slot * 0.2;
1778
+ for (let i = 0; i < valid.length; i++) {
1779
+ const g = valid[i];
1780
+ const cx = area.x0 + slot * i + slot / 2;
1781
+ const x = area.x0 + slot * i + boxOffset;
1782
+ const seriesIdx = opts.colorByBox ? i % 8 : 0;
1783
+ const seriesCls = `stdlib-chart-series-${seriesIdx}`;
1784
+ const yQ1 = yMap(g.s.q1, yAxis.domain, [area.y1, area.y0]);
1785
+ const yQ2 = yMap(g.s.q2, yAxis.domain, [area.y1, area.y0]);
1786
+ const yQ3 = yMap(g.s.q3, yAxis.domain, [area.y1, area.y0]);
1787
+ const yWhiskerLow = yMap(g.s.whiskerLow, yAxis.domain, [area.y1, area.y0]);
1788
+ const yWhiskerHigh = yMap(g.s.whiskerHigh, yAxis.domain, [area.y1, area.y0]);
1789
+
1790
+ // Whisker line (vertical) from low whisker to high whisker, behind the box.
1791
+ body.push(`<line class="stdlib-chart-box-whisker" x1="${fmt(cx)}" y1="${fmt(yWhiskerHigh)}" x2="${fmt(cx)}" y2="${fmt(yWhiskerLow)}"/>`);
1792
+ // Whisker caps.
1793
+ const capW = boxWidth * 0.4;
1794
+ body.push(`<line class="stdlib-chart-box-cap" x1="${fmt(cx - capW / 2)}" y1="${fmt(yWhiskerHigh)}" x2="${fmt(cx + capW / 2)}" y2="${fmt(yWhiskerHigh)}"/>`);
1795
+ body.push(`<line class="stdlib-chart-box-cap" x1="${fmt(cx - capW / 2)}" y1="${fmt(yWhiskerLow)}" x2="${fmt(cx + capW / 2)}" y2="${fmt(yWhiskerLow)}"/>`);
1796
+ // Box (Q1 to Q3).
1797
+ body.push(chartDatumSvg(`<rect class="stdlib-chart-box ${seriesCls}" x="${fmt(x)}" y="${fmt(yQ3)}" width="${fmt(boxWidth)}" height="${fmt(yQ1 - yQ3)}"/>`, {
1798
+ index: g.index,
1799
+ role: "box",
1800
+ label: g.label,
1801
+ anchor: [cx, yQ2],
1802
+ values: [{
1803
+ key: "count",
1804
+ value: g.count
1805
+ }, ...["q1", "q2", "q3", "whiskerLow", "whiskerHigh"].map(key => ({
1806
+ key,
1807
+ value: g.s[key]
1808
+ })).map(field => ({
1809
+ ...field,
1810
+ formatted: opts.yAxis?.format?.(field.value)
1811
+ }))]
1812
+ }, opts.inspect));
1813
+ // Median line.
1814
+ body.push(`<line class="stdlib-chart-box-median" x1="${fmt(x)}" y1="${fmt(yQ2)}" x2="${fmt(x + boxWidth)}" y2="${fmt(yQ2)}"/>`);
1815
+ // Outliers.
1816
+ if (showOutliers) {
1817
+ const sourceIndices = new Map();
1818
+ if (opts.inspect) opts.groups[g.index].values.forEach((value, index) => {
1819
+ const indices = sourceIndices.get(value) ?? [];
1820
+ indices.push(index);
1821
+ sourceIndices.set(value, indices);
1822
+ });
1823
+ for (const v of g.s.outliers) {
1824
+ const sourceIndex = sourceIndices.get(v)?.shift() ?? 0;
1825
+ const oy = yMap(v, yAxis.domain, [area.y1, area.y0]);
1826
+ body.push(chartDatumSvg(`<circle class="stdlib-chart-box-outlier ${seriesCls}" cx="${fmt(cx)}" cy="${fmt(oy)}" r="2.5"/>`, {
1827
+ index: sourceIndex,
1828
+ seriesIndex: g.index,
1829
+ role: "outlier",
1830
+ label: g.label,
1831
+ anchor: [cx, oy],
1832
+ values: [{
1833
+ key: "value",
1834
+ value: v,
1835
+ formatted: opts.yAxis?.format?.(v)
1836
+ }]
1837
+ }, opts.inspect));
1838
+ }
1839
+ }
1840
+ }
1841
+ if (opts.references && opts.references.length > 0) {
1842
+ const yRefs = opts.references.filter(r => (r.axis ?? "y") === "y");
1843
+ if (yRefs.length > 0) {
1844
+ body.push(renderReferenceLines(yRefs, {
1845
+ domain: [0, 1],
1846
+ scale: "linear"
1847
+ }, yAxis, area));
1848
+ }
1849
+ }
1850
+ return svgRoot({
1851
+ width,
1852
+ height,
1853
+ className: opts.className
1854
+ }, header.svg + body.join(""));
1855
+ };
1856
+
1857
+ // ==========================
1858
+ // DASHBOARD PANELS
1859
+ // ==========================
1860
+
1861
+ const thresholdIndexForValue = (value, thresholds, min, max) => {
1862
+ if (!thresholds || thresholds.length === 0) return 0;
1863
+ const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
1864
+ const clamped = clamp(value, min, max);
1865
+ const idx = sorted.findIndex(t => clamped <= t.value);
1866
+ return idx >= 0 ? idx : Math.max(0, sorted.length - 1);
1867
+ };
1868
+ const thresholdForIndex = (thresholds, index) => {
1869
+ if (!thresholds || thresholds.length === 0) return undefined;
1870
+ const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
1871
+ return sorted[index];
1872
+ };
1873
+
1874
+ /**
1875
+ * Render a radial single-value gauge for KPI, quota, saturation, or SLO style
1876
+ * dashboard panels.
1877
+ */
1878
+ export const gauge = opts => {
1879
+ const width = opts.width ?? 260;
1880
+ const height = opts.height ?? 180;
1881
+ const [min, max] = normalizeMinMax(opts.min, opts.max);
1882
+ const value = Number.isFinite(opts.value) ? opts.value : min;
1883
+ const clamped = clamp(value, min, max);
1884
+ const startAngle = Math.PI * 5 / 6;
1885
+ const endAngle = Math.PI * 13 / 6;
1886
+ const valueAngle = mapRange(clamped, [min, max], [startAngle, endAngle]);
1887
+ const cx = width / 2;
1888
+ const cy = height * 0.64;
1889
+ const radius = Math.min(width * 0.34, height * 0.43);
1890
+ const startPoint = polarPoint(cx, cy, radius, startAngle);
1891
+ const endPoint = polarPoint(cx, cy, radius, endAngle);
1892
+ const endpointLabelY = Math.min(height - 10, Math.max(cy + 32, startPoint.y + 16));
1893
+ const progress = clamp(mapRange(clamped, [min, max], [0, 100]), 0, 100);
1894
+ const gaugePath = arcLinePathD(cx, cy, radius, startAngle, endAngle);
1895
+ const gradientStops = gaugeThresholdStops(opts.thresholds, min, max);
1896
+ const thresholdIdx = thresholdIndexForValue(clamped, opts.thresholds, min, max);
1897
+ const threshold = thresholdForIndex(opts.thresholds, thresholdIdx);
1898
+ const thresholdColor = threshold?.color;
1899
+ const valueText = formatNumberValue(value, opts.format, opts.unit);
1900
+ const label = opts.label ?? opts.title;
1901
+ const fillStroke = gradientStops.length > 0 ? ` stroke="${escapeXml(gaugeColorAt(gradientStops, clamped))}"` : thresholdStrokeAttr(thresholdColor);
1902
+ const fillClass = gradientStops.length > 0 || thresholdColor ? "stdlib-chart-gauge-fill" : `stdlib-chart-gauge-fill stdlib-chart-series-${thresholdIdx % 8}`;
1903
+ const body = [];
1904
+ if (gradientStops.length > 0) {
1905
+ body.push(renderGaugeGradientSegments({
1906
+ stops: gradientStops,
1907
+ min,
1908
+ max,
1909
+ cx,
1910
+ cy,
1911
+ radius,
1912
+ startAngle,
1913
+ endAngle,
1914
+ className: "stdlib-chart-gauge-gradient-segment stdlib-chart-gauge-gradient-scale"
1915
+ }));
1916
+ body.push(renderGaugeGradientSegments({
1917
+ stops: gradientStops,
1918
+ min,
1919
+ max,
1920
+ cx,
1921
+ cy,
1922
+ radius,
1923
+ startAngle,
1924
+ endAngle,
1925
+ progress,
1926
+ className: "stdlib-chart-gauge-gradient-segment"
1927
+ }));
1928
+ } else {
1929
+ body.push(`<path class="stdlib-chart-gauge-track" d="${gaugePath}"/>`);
1930
+ if (progress > 0) {
1931
+ body.push(`<path class="${fillClass}"${fillStroke} pathLength="100" stroke-dasharray="${fmt(progress)} 100" d="${gaugePath}"/>`);
1932
+ }
1933
+ }
1934
+ if (opts.showNeedle) {
1935
+ const tip = polarPoint(cx, cy, radius - 8, valueAngle);
1936
+ const needleClass = thresholdColor || gradientStops.length > 0 ? "stdlib-chart-gauge-needle" : `stdlib-chart-gauge-needle stdlib-chart-series-${thresholdIdx % 8}`;
1937
+ body.push(`<line class="${needleClass}"${fillStroke} x1="${fmt(cx)}" y1="${fmt(cy)}" x2="${fmt(tip.x)}" y2="${fmt(tip.y)}"/>`);
1938
+ body.push(`<circle class="stdlib-chart-gauge-hub" cx="${fmt(cx)}" cy="${fmt(cy)}" r="3"/>`);
1939
+ }
1940
+ body.push(`<text class="stdlib-chart-gauge-value" x="${fmt(cx)}" y="${fmt(cy - 2)}" text-anchor="middle">${escapeXml(valueText)}</text>`);
1941
+ if (label) {
1942
+ body.push(`<text class="stdlib-chart-gauge-label" x="${fmt(cx)}" y="${fmt(cy + 20)}" text-anchor="middle">${escapeXml(label)}</text>`);
1943
+ }
1944
+ body.push(`<text class="stdlib-chart-gauge-unit" x="${fmt(startPoint.x)}" y="${fmt(endpointLabelY)}" text-anchor="middle">${escapeXml(formatNumberValue(min, opts.format, opts.unit))}</text>`);
1945
+ body.push(`<text class="stdlib-chart-gauge-unit" x="${fmt(endPoint.x)}" y="${fmt(endpointLabelY)}" text-anchor="middle">${escapeXml(formatNumberValue(max, opts.format, opts.unit))}</text>`);
1946
+ return svgRoot({
1947
+ width,
1948
+ height,
1949
+ className: opts.className
1950
+ }, chartDatumSvg(body.join(""), {
1951
+ index: 0,
1952
+ role: "value",
1953
+ label,
1954
+ anchor: [cx, cy],
1955
+ values: [{
1956
+ key: "value",
1957
+ value,
1958
+ formatted: valueText
1959
+ }, {
1960
+ key: "min",
1961
+ value: min
1962
+ }, {
1963
+ key: "max",
1964
+ value: max
1965
+ }, ...(threshold ? [{
1966
+ key: "threshold",
1967
+ value: threshold.label ?? threshold.value
1968
+ }] : [])]
1969
+ }, opts.inspect));
1970
+ };
1971
+
1972
+ /** Render compact horizontal bar gauges for multiple reduced metrics. */
1973
+ export const barGauge = opts => {
1974
+ const width = opts.width ?? 420;
1975
+ const rowHeight = 28;
1976
+ const top = opts.title || opts.subtitle ? 42 : 16;
1977
+ const height = opts.height ?? Math.max(80, top + opts.data.length * rowHeight + 14);
1978
+ const header = renderHeader(width, opts.title, opts.subtitle);
1979
+ const body = [header.svg];
1980
+ const labelW = Math.min(140, Math.max(74, width * 0.34));
1981
+ const valueW = 56;
1982
+ const trackX = labelW + 14;
1983
+ const trackW = Math.max(24, width - trackX - valueW - 14);
1984
+ const trackH = 10;
1985
+ const sourceIndices = opts.data.flatMap((d, index) => Number.isFinite(d.value) ? [index] : []);
1986
+ const data = opts.data.filter(d => Number.isFinite(d.value));
1987
+ if (data.length === 0) {
1988
+ body.push(`<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle">No data</text>`);
1989
+ return svgRoot({
1990
+ width,
1991
+ height,
1992
+ className: opts.className
1993
+ }, body.join(""));
1994
+ }
1995
+ data.forEach((d, i) => {
1996
+ const [min, max] = normalizeMinMax(d.min ?? opts.min, d.max ?? opts.max);
1997
+ const pct = clamp((d.value - min) / (max - min), 0, 1);
1998
+ const y = top + i * rowHeight;
1999
+ const thresholdIdx = thresholdIndexForValue(d.value, opts.thresholds, min, max);
2000
+ const threshold = thresholdForIndex(opts.thresholds, thresholdIdx);
2001
+ const thresholdColor = threshold?.color;
2002
+ const unit = d.unit ?? opts.unit ?? "";
2003
+ const start = body.length;
2004
+ body.push(`<text class="stdlib-chart-bar-gauge-label" x="12" y="${fmt(y + 12)}" dominant-baseline="middle">${escapeXml(d.label)}</text>`);
2005
+ body.push(`<rect class="stdlib-chart-bar-gauge-track" x="${fmt(trackX)}" y="${fmt(y + 7)}" width="${fmt(trackW)}" height="${fmt(trackH)}" rx="2"/>`);
2006
+ body.push(`<rect class="stdlib-chart-bar-gauge-fill stdlib-chart-series-${thresholdIdx % 8}"${thresholdFillAttr(thresholdColor)} x="${fmt(trackX)}" y="${fmt(y + 7)}" width="${fmt(trackW * pct)}" height="${fmt(trackH)}" rx="2"/>`);
2007
+ body.push(`<text class="stdlib-chart-bar-gauge-value" x="${fmt(width - 12)}" y="${fmt(y + 12)}" text-anchor="end" dominant-baseline="middle">${escapeXml(formatNumberValue(d.value, opts.format, unit))}</text>`);
2008
+ const shapes = body.splice(start).join("");
2009
+ body.push(chartDatumSvg(shapes, {
2010
+ index: sourceIndices[i],
2011
+ role: "item",
2012
+ label: d.label,
2013
+ anchor: [trackX + trackW / 2, y + 12],
2014
+ values: [{
2015
+ key: "value",
2016
+ value: d.value,
2017
+ formatted: formatNumberValue(d.value, opts.format, unit)
2018
+ }, {
2019
+ key: "min",
2020
+ value: min
2021
+ }, {
2022
+ key: "max",
2023
+ value: max
2024
+ }, ...(threshold ? [{
2025
+ key: "threshold",
2026
+ value: threshold.label ?? threshold.value
2027
+ }] : [])]
2028
+ }, opts.inspect));
2029
+ });
2030
+ return svgRoot({
2031
+ width,
2032
+ height,
2033
+ className: opts.className
2034
+ }, body.join(""));
2035
+ };
2036
+ const renderInlineSparkline = (values, x, y, width, height, inspect) => {
2037
+ if (!values || values.length < 2) return "";
2038
+ const entries = sparklineEntries(values);
2039
+ const points = entries.map(entry => entry.point);
2040
+ if (points.length < 2) return "";
2041
+ const xs = points.map(p => p.x);
2042
+ const ys = points.map(p => p.y);
2043
+ const xDomain = computeDomain(xs);
2044
+ const yDomain = computeDomain(ys);
2045
+ const mapped = [...points].sort((a, b) => a.x - b.x).map(p => ({
2046
+ x: mapRange(p.x, xDomain, [x, x + width]),
2047
+ y: mapRange(p.y, yDomain, [y + height, y])
2048
+ }));
2049
+ const linePath = smoothPathD(mapped);
2050
+ const first = mapped[0];
2051
+ const last = mapped[mapped.length - 1];
2052
+ const areaPath = `${linePath} L ${fmt(last.x)} ${fmt(y + height)} L ${fmt(first.x)} ${fmt(y + height)} Z`;
2053
+ return `<path class="stdlib-chart-stat-sparkline-area" d="${areaPath}"/>` + `<path class="stdlib-chart-stat-sparkline" d="${linePath}"/>` + (inspect ? [...points].sort((a, b) => a.x - b.x).map((p, index) => inspectionPoint({
2054
+ index: entries[index].index,
2055
+ role: "point",
2056
+ anchor: [mapped[index].x, mapped[index].y],
2057
+ values: pointValues(p)
2058
+ }, inspect)).join("") : "");
2059
+ };
2060
+
2061
+ /** Render a large value panel with optional delta and inline sparkline. */
2062
+ export const stat = opts => {
2063
+ const width = opts.width ?? 260;
2064
+ const height = opts.height ?? 150;
2065
+ const value = typeof opts.value === "number" ? formatNumberValue(opts.value, opts.format, opts.unit) : `${opts.value}${opts.unit ?? ""}`;
2066
+ const trend = opts.trend ?? (typeof opts.delta === "number" ? opts.delta > 0 ? "up" : opts.delta < 0 ? "down" : "neutral" : "neutral");
2067
+ const deltaText = typeof opts.delta === "number" ? `${opts.delta > 0 ? "+" : ""}${opts.deltaFormat ? opts.deltaFormat(opts.delta) : fmt(opts.delta)}` : opts.delta;
2068
+ const deltaClass = trend === "up" ? " stdlib-chart-stat-delta-up" : trend === "down" ? " stdlib-chart-stat-delta-down" : "";
2069
+ const body = [];
2070
+ body.push(`<text class="stdlib-chart-stat-label" x="16" y="24">${escapeXml(opts.label)}</text>`);
2071
+ body.push(`<text class="stdlib-chart-stat-value" x="16" y="70">${escapeXml(value)}</text>`);
2072
+ if (deltaText !== undefined) {
2073
+ body.push(`<text class="stdlib-chart-stat-delta${deltaClass}" x="${fmt(width - 16)}" y="70" text-anchor="end">${escapeXml(String(deltaText))}</text>`);
2074
+ }
2075
+ const summary = chartDatumSvg((opts.inspect ? `<rect x="0" y="0" width="${fmt(width)}" height="${fmt(Math.max(80, height - 48))}" fill="transparent" stroke="none"/>` : "") + body.join(""), {
2076
+ index: 0,
2077
+ role: "value",
2078
+ label: opts.label,
2079
+ anchor: [width / 2, 50],
2080
+ values: [{
2081
+ key: "value",
2082
+ value: opts.value,
2083
+ formatted: value
2084
+ }, ...(opts.delta !== undefined ? [{
2085
+ key: "delta",
2086
+ value: opts.delta,
2087
+ formatted: deltaText
2088
+ }] : [])]
2089
+ }, opts.inspect);
2090
+ return svgRoot({
2091
+ width,
2092
+ height,
2093
+ className: opts.className
2094
+ }, summary + renderInlineSparkline(opts.sparkline, 16, height - 42, width - 32, 26, opts.inspect));
2095
+ };
2096
+
2097
+ /**
2098
+ * Render a categorical two-dimensional heatmap. Cell opacity represents value
2099
+ * intensity; labels are derived from first occurrence order unless provided.
2100
+ */
2101
+ export const heatmap = opts => {
2102
+ const width = opts.width ?? 460;
2103
+ const height = opts.height ?? 260;
2104
+ const padding = normalizePadding(opts.padding ?? {
2105
+ top: 36,
2106
+ right: 16,
2107
+ bottom: 32,
2108
+ left: 54
2109
+ });
2110
+ const header = renderHeader(width, opts.title, opts.subtitle);
2111
+ const xLabels = opts.xLabels ?? [...new Set(opts.data.map(d => d.x))];
2112
+ const yLabels = opts.yLabels ?? [...new Set(opts.data.map(d => d.y))];
2113
+ if (xLabels.length === 0 || yLabels.length === 0) {
2114
+ return svgRoot({
2115
+ width,
2116
+ height,
2117
+ className: opts.className
2118
+ }, header.svg + `<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle">No data</text>`);
2119
+ }
2120
+ const area = computePlotArea(width, height, padding, false, false, header.height, 0);
2121
+ const values = opts.data.map(d => d.value).filter(Number.isFinite);
2122
+ const [autoMin, autoMax] = computeDomain(values);
2123
+ const min = Number.isFinite(opts.min) ? opts.min : autoMin;
2124
+ const max = Number.isFinite(opts.max) ? opts.max : autoMax;
2125
+ const indexMap = new Map(opts.data.map((d, index) => [`${d.x}\u0000${d.y}`, index]));
2126
+ const valueMap = new Map(opts.data.map(d => [`${d.x}\u0000${d.y}`, d.value]));
2127
+ const cellW = (area.x1 - area.x0) / xLabels.length;
2128
+ const cellH = (area.y1 - area.y0) / yLabels.length;
2129
+ const body = [header.svg];
2130
+ const format = opts.format ?? (v => fmt(v));
2131
+ xLabels.forEach((label, i) => {
2132
+ const x = area.x0 + cellW * (i + 0.5);
2133
+ body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(x)}" y="${fmt(area.y1 + 14)}" text-anchor="middle">${escapeXml(label)}</text>`);
2134
+ });
2135
+ yLabels.forEach((label, i) => {
2136
+ const y = area.y0 + cellH * (i + 0.5);
2137
+ body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(area.x0 - 8)}" y="${fmt(y)}" text-anchor="end" dominant-baseline="middle">${escapeXml(label)}</text>`);
2138
+ });
2139
+ for (let yi = 0; yi < yLabels.length; yi++) {
2140
+ for (let xi = 0; xi < xLabels.length; xi++) {
2141
+ const valueAtCell = valueMap.get(`${xLabels[xi]}\u0000${yLabels[yi]}`);
2142
+ if (!Number.isFinite(valueAtCell)) continue;
2143
+ const intensity = clamp(mapRange(valueAtCell, [min, max], [0.12, 1]), 0.12, 1);
2144
+ const x = area.x0 + xi * cellW;
2145
+ const y = area.y0 + yi * cellH;
2146
+ body.push(chartDatumSvg(`<rect class="stdlib-chart-heatmap-cell stdlib-chart-series-0" x="${fmt(x)}" y="${fmt(y)}" width="${fmt(Math.max(0, cellW - 1))}" height="${fmt(Math.max(0, cellH - 1))}" opacity="${fmt(intensity)}"/>`, {
2147
+ index: indexMap.get(`${xLabels[xi]}\u0000${yLabels[yi]}`),
2148
+ role: "cell",
2149
+ anchor: [x + cellW / 2, y + cellH / 2],
2150
+ grid: [xi, yi],
2151
+ values: [{
2152
+ key: "x",
2153
+ value: xLabels[xi]
2154
+ }, {
2155
+ key: "y",
2156
+ value: yLabels[yi]
2157
+ }, {
2158
+ key: "value",
2159
+ value: valueAtCell,
2160
+ formatted: format(valueAtCell)
2161
+ }]
2162
+ }, opts.inspect));
2163
+ if (opts.showValues) {
2164
+ body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(x + cellW / 2)}" y="${fmt(y + cellH / 2)}" text-anchor="middle" dominant-baseline="middle">${escapeXml(format(valueAtCell))}</text>`);
2165
+ }
2166
+ }
2167
+ }
2168
+ return svgRoot({
2169
+ width,
2170
+ height,
2171
+ className: opts.className
2172
+ }, body.join(""));
2173
+ };
2174
+
2175
+ // ==========================
2176
+ // STATE TIMELINE
2177
+ // ==========================
2178
+
2179
+ /**
2180
+ * Render state regions over a numeric timeline for services, jobs, deploys, or
2181
+ * health checks.
2182
+ */
2183
+ export const stateTimeline = opts => {
2184
+ const width = opts.width ?? 560;
2185
+ const rowHeight = 24;
2186
+ const legendItems = opts.legend === false ? [] : (opts.states ?? []).map((s, i) => ({
2187
+ label: s.label ?? s.state,
2188
+ seriesIndex: i
2189
+ }));
2190
+ const legendHeight = measureLegendHeight(legendItems, width);
2191
+ const height = opts.height ?? Math.max(120, 56 + opts.rows.length * rowHeight + legendHeight);
2192
+ const padding = normalizePadding(opts.padding ?? {
2193
+ top: 36,
2194
+ right: 16,
2195
+ bottom: 28,
2196
+ left: 74
2197
+ });
2198
+ const header = renderHeader(width, opts.title, opts.subtitle);
2199
+ const allIntervals = opts.rows.flatMap(r => r.intervals);
2200
+ const timeValues = allIntervals.flatMap(i => [i.from, i.to]).filter(Number.isFinite);
2201
+ if (opts.rows.length === 0 || timeValues.length === 0) {
2202
+ return svgRoot({
2203
+ width,
2204
+ height,
2205
+ className: opts.className
2206
+ }, header.svg + `<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle">No data</text>`);
2207
+ }
2208
+ const [minT, maxT] = computeDomain(timeValues);
2209
+ const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, false, header.height, legendHeight);
2210
+ const stateKeys = opts.states?.map(s => s.state) ?? [...new Set(allIntervals.map(i => i.state))];
2211
+ const stateStyles = new Map((opts.states ?? []).map((s, i) => [s.state, {
2212
+ ...s,
2213
+ index: i
2214
+ }]));
2215
+ const stateIndex = state => {
2216
+ const explicit = stateStyles.get(state)?.index;
2217
+ if (explicit !== undefined) return explicit;
2218
+ const idx = stateKeys.indexOf(state);
2219
+ return idx >= 0 ? idx : 0;
2220
+ };
2221
+ const body = [header.svg];
2222
+ const format = opts.xAxis?.format ?? (v => fmt(v));
2223
+ const ticks = extendDomainToNice(minT, maxT, niceStep(maxT - minT, 4)).ticks.slice(0, 6);
2224
+ opts.rows.forEach((row, rowIdx) => {
2225
+ const y = area.y0 + rowIdx * rowHeight;
2226
+ body.push(`<text class="stdlib-chart-state-label" x="${fmt(area.x0 - 8)}" y="${fmt(y + rowHeight / 2)}" text-anchor="end" dominant-baseline="middle">${escapeXml(row.label)}</text>`);
2227
+ for (const [index, interval] of row.intervals.entries()) {
2228
+ if (!Number.isFinite(interval.from) || !Number.isFinite(interval.to)) continue;
2229
+ const from = clamp(Math.min(interval.from, interval.to), minT, maxT);
2230
+ const to = clamp(Math.max(interval.from, interval.to), minT, maxT);
2231
+ const x = mapRange(from, [minT, maxT], [area.x0, area.x1]);
2232
+ const x2 = mapRange(to, [minT, maxT], [area.x0, area.x1]);
2233
+ const idx = stateIndex(interval.state);
2234
+ const color = stateStyles.get(interval.state)?.color;
2235
+ body.push(chartDatumSvg(`<rect class="stdlib-chart-state-region stdlib-chart-series-${idx % 8}"${thresholdFillAttr(color)} x="${fmt(x)}" y="${fmt(y + 3)}" width="${fmt(Math.max(1, x2 - x))}" height="${fmt(rowHeight - 6)}" rx="2"/>`, {
2236
+ index,
2237
+ seriesIndex: rowIdx,
2238
+ role: "interval",
2239
+ label: row.label,
2240
+ anchor: [(x + x2) / 2, y + rowHeight / 2],
2241
+ grid: [index, rowIdx],
2242
+ values: [{
2243
+ key: "state",
2244
+ value: interval.state,
2245
+ formatted: stateStyles.get(interval.state)?.label
2246
+ }, {
2247
+ key: "from",
2248
+ value: from,
2249
+ formatted: format(from)
2250
+ }, {
2251
+ key: "to",
2252
+ value: to,
2253
+ formatted: format(to)
2254
+ }, {
2255
+ key: "duration",
2256
+ value: to - from
2257
+ }]
2258
+ }, opts.inspect));
2259
+ }
2260
+ });
2261
+ for (const tick of ticks) {
2262
+ if (tick < minT || tick > maxT) continue;
2263
+ const x = mapRange(tick, [minT, maxT], [area.x0, area.x1]);
2264
+ body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(x)}" y="${fmt(area.y1 + 15)}" text-anchor="middle">${escapeXml(format(tick))}</text>`);
2265
+ }
2266
+ if (opts.xAxis?.label) {
2267
+ body.push(`<text class="stdlib-chart-axis-label" x="${fmt((area.x0 + area.x1) / 2)}" y="${fmt(height - legendHeight - 4)}" text-anchor="middle">${escapeXml(opts.xAxis.label)}</text>`);
2268
+ }
2269
+ if (legendItems.length > 0) {
2270
+ body.push(renderLegend(legendItems, width, height - legendHeight).svg);
2271
+ }
2272
+ return svgRoot({
2273
+ width,
2274
+ height,
2275
+ className: opts.className
2276
+ }, body.join(""));
2277
+ };
2278
+
2279
+ // ==========================
2280
+ // SPARKLINE
2281
+ // ==========================
2282
+
2283
+ // Monotonically incrementing counter for per-instance gradient IDs. Using a
2284
+ // module-level counter (vs. random) keeps output stable enough that repeated
2285
+ // renders of the same input in a process produce predictable IDs in sequence,
2286
+ // while still being unique within a document.
2287
+ let sparklineGradientCounter = 0;
2288
+ const sparklineEntries = data => data.map((value, index) => ({
2289
+ point: typeof value === "number" ? {
2290
+ x: index,
2291
+ y: value
2292
+ } : value,
2293
+ index
2294
+ })).filter(({
2295
+ point
2296
+ }) => Number.isFinite(point.x) && Number.isFinite(point.y)).sort((a, b) => a.point.x - b.point.x);
2297
+
2298
+ /**
2299
+ * Render a minimalist sparkline — a tiny inline chart with no axes, no
2300
+ * labels, and minimal padding. Designed to fit alongside text or in dense
2301
+ * tables.
2302
+ *
2303
+ * Stroke uses `currentColor` by default, so it adopts the surrounding text
2304
+ * color. Pass `className` to scope a different color.
2305
+ *
2306
+ * @example
2307
+ * charts.sparkline({ data: [3, 7, 5, 9, 12, 10, 14] });
2308
+ *
2309
+ * @example
2310
+ * charts.sparkline({
2311
+ * data: [3, 7, 5, 9, 12, 10, 14],
2312
+ * smooth: true,
2313
+ * showLast: true,
2314
+ * width: 120,
2315
+ * });
2316
+ *
2317
+ * @example
2318
+ * // Dashboard-tile look: stroke + soft gradient fill fading to transparent.
2319
+ * charts.sparkline({ data: [3, 7, 5, 9, 12, 10, 14], area: true });
2320
+ */
2321
+ export const sparkline = opts => {
2322
+ const width = opts.width ?? 80;
2323
+ const height = opts.height ?? 20;
2324
+ const entries = sparklineEntries(opts.data);
2325
+ const points = entries.map(entry => entry.point);
2326
+ if (points.length < 2) {
2327
+ // Empty spark — return a same-sized invisible svg so layout stays stable.
2328
+ return svgRoot({
2329
+ width,
2330
+ height,
2331
+ className: opts.className
2332
+ }, "");
2333
+ }
2334
+
2335
+ // Inset reserves space so the stroke and any dots sit fully inside the
2336
+ // viewBox. Dots have r=2; without dots the line stroke (1.5px wide) only
2337
+ // needs ~0.75px of breathing room.
2338
+ const DOT_R = 2;
2339
+ const hasDots = !!(opts.showLast || opts.showMinMax);
2340
+ const inset = hasDots ? DOT_R + 0.75 : 1.5;
2341
+ const xs = points.map(p => p.x);
2342
+ const ys = points.map(p => p.y);
2343
+ const xDomain = computeDomain(xs);
2344
+ const yDomain = computeDomain(ys);
2345
+ const sorted = [...points].sort((a, b) => a.x - b.x);
2346
+ const mapped = sorted.map(p => ({
2347
+ x: mapRange(p.x, xDomain, [inset, width - inset]),
2348
+ y: mapRange(p.y, yDomain, [height - inset, inset])
2349
+ }));
2350
+ const pathFn = opts.smooth === false ? linePathD : smoothPathD;
2351
+ const linePath = pathFn(mapped);
2352
+ const body = [];
2353
+ if (opts.area) {
2354
+ // Gradient-fill area UNDER the stroke line: fades from a translucent
2355
+ // currentColor at the top to fully transparent at the bottom. The fill
2356
+ // path extends all the way down to the bottom of the viewBox; the
2357
+ // gradient handles the visual fade-out — no need for special bottom
2358
+ // padding. Stroke renders on top via the regular `.sparkline` path below.
2359
+ const gradId = `stdlib-spark-grad-${++sparklineGradientCounter}`;
2360
+ const first = mapped[0];
2361
+ const last = mapped[mapped.length - 1];
2362
+ const areaPath = `${linePath} L ${fmt(last.x)} ${fmt(height)} L ${fmt(first.x)} ${fmt(height)} Z`;
2363
+ body.push(`<defs><linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1">` + `<stop offset="0%" stop-color="currentColor" stop-opacity="0.28"/>` + `<stop offset="100%" stop-color="currentColor" stop-opacity="0"/>` + `</linearGradient></defs>`);
2364
+ body.push(`<path class="stdlib-chart-sparkline-area" fill="url(#${gradId})" d="${areaPath}"/>`);
2365
+ }
2366
+ body.push(`<path class="stdlib-chart-sparkline" d="${linePath}"/>`);
2367
+ if (opts.showMinMax) {
2368
+ let minIdx = 0;
2369
+ let maxIdx = 0;
2370
+ let minV = Number.POSITIVE_INFINITY;
2371
+ let maxV = Number.NEGATIVE_INFINITY;
2372
+ for (let i = 0; i < sorted.length; i++) {
2373
+ const v = sorted[i].y;
2374
+ if (v < minV) {
2375
+ minV = v;
2376
+ minIdx = i;
2377
+ }
2378
+ if (v > maxV) {
2379
+ maxV = v;
2380
+ maxIdx = i;
2381
+ }
2382
+ }
2383
+ if (minV < maxV) {
2384
+ const max = mapped[maxIdx];
2385
+ const min = mapped[minIdx];
2386
+ body.push(`<circle class="stdlib-chart-sparkline-max" cx="${fmt(max.x)}" cy="${fmt(max.y)}" r="2"/>`);
2387
+ body.push(`<circle class="stdlib-chart-sparkline-min" cx="${fmt(min.x)}" cy="${fmt(min.y)}" r="2"/>`);
2388
+ }
2389
+ }
2390
+ if (opts.showLast && mapped.length > 0) {
2391
+ const last = mapped[mapped.length - 1];
2392
+ body.push(`<circle class="stdlib-chart-sparkline-last" cx="${fmt(last.x)}" cy="${fmt(last.y)}" r="2"/>`);
2393
+ }
2394
+ if (opts.inspect) sorted.forEach((p, index) => body.push(inspectionPoint({
2395
+ index: entries[index].index,
2396
+ role: "point",
2397
+ anchor: [mapped[index].x, mapped[index].y],
2398
+ values: pointValues(p)
2399
+ }, opts.inspect)));
2400
+ return svgRoot({
2401
+ width,
2402
+ height,
2403
+ className: opts.className
2404
+ }, body.join(""));
2405
+ };
2406
+ //# sourceMappingURL=svg-renderers.js.map