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