@k2b/ui 0.51.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 (206) hide show
  1. package/dist/base.css +3 -0
  2. package/dist/browser/actions/Toolbar.js +8 -2
  3. package/dist/browser/actions/Toolbar.js.map +1 -1
  4. package/dist/browser/charts/core/bar-labels.js +5 -0
  5. package/dist/browser/charts/core/bar-labels.js.map +1 -0
  6. package/dist/browser/charts/core/bubble.js +166 -0
  7. package/dist/browser/charts/core/bubble.js.map +1 -0
  8. package/dist/browser/charts/core/default-styles.js +83 -0
  9. package/dist/browser/charts/core/default-styles.js.map +1 -0
  10. package/dist/browser/charts/core/funnel-layout.js +79 -0
  11. package/dist/browser/charts/core/funnel-layout.js.map +1 -0
  12. package/dist/browser/charts/core/funnel.js +27 -0
  13. package/dist/browser/charts/core/funnel.js.map +1 -0
  14. package/dist/browser/charts/core/index.js +6 -1
  15. package/dist/browser/charts/core/index.js.map +1 -1
  16. package/dist/browser/charts/core/pareto.js +120 -0
  17. package/dist/browser/charts/core/pareto.js.map +1 -0
  18. package/dist/browser/charts/core/radar.js +101 -0
  19. package/dist/browser/charts/core/radar.js.map +1 -0
  20. package/dist/browser/charts/core/registry.js +11 -1
  21. package/dist/browser/charts/core/registry.js.map +1 -1
  22. package/dist/browser/charts/core/render-size.js +3 -1
  23. package/dist/browser/charts/core/render-size.js.map +1 -1
  24. package/dist/browser/charts/core/render.js +19 -0
  25. package/dist/browser/charts/core/render.js.map +1 -1
  26. package/dist/browser/charts/core/snapshot.js +1 -1
  27. package/dist/browser/charts/core/snapshot.js.map +1 -1
  28. package/dist/browser/charts/core/svg-barGauge.js +67 -0
  29. package/dist/browser/charts/core/svg-barGauge.js.map +1 -0
  30. package/dist/browser/charts/core/svg-boxplot.js +127 -0
  31. package/dist/browser/charts/core/svg-boxplot.js.map +1 -0
  32. package/dist/browser/charts/core/svg-common.js +1065 -0
  33. package/dist/browser/charts/core/svg-common.js.map +1 -0
  34. package/dist/browser/charts/core/svg-gauge.js +185 -0
  35. package/dist/browser/charts/core/svg-gauge.js.map +1 -0
  36. package/dist/browser/charts/core/svg-heatmap.js +80 -0
  37. package/dist/browser/charts/core/svg-heatmap.js.map +1 -0
  38. package/dist/browser/charts/core/svg-histogram.js +73 -0
  39. package/dist/browser/charts/core/svg-histogram.js.map +1 -0
  40. package/dist/browser/charts/core/svg-renderers.js +9 -1777
  41. package/dist/browser/charts/core/svg-renderers.js.map +1 -1
  42. package/dist/browser/charts/core/svg-scatter.js +114 -0
  43. package/dist/browser/charts/core/svg-scatter.js.map +1 -0
  44. package/dist/browser/charts/core/treemap.js +138 -0
  45. package/dist/browser/charts/core/treemap.js.map +1 -0
  46. package/dist/browser/charts/description.js.map +1 -1
  47. package/dist/browser/content/ChartRoot.js +21 -7
  48. package/dist/browser/content/ChartRoot.js.map +1 -1
  49. package/dist/browser/content/ChartSnapshotView.js +4 -1
  50. package/dist/browser/content/ChartSnapshotView.js.map +1 -1
  51. package/dist/browser/content/DataTable.js +186 -193
  52. package/dist/browser/content/DataTable.js.map +1 -1
  53. package/dist/browser/content/Lightbox.js +55 -23
  54. package/dist/browser/content/Lightbox.js.map +1 -1
  55. package/dist/browser/content/ThumbnailStrip.js +174 -0
  56. package/dist/browser/content/ThumbnailStrip.js.map +1 -0
  57. package/dist/browser/content/chart-bar.js +98 -0
  58. package/dist/browser/content/chart-bar.js.map +1 -1
  59. package/dist/browser/content/chart-inspection-core.js +28 -8
  60. package/dist/browser/content/chart-inspection-core.js.map +1 -1
  61. package/dist/browser/content/chart-message-catalog.js +18 -0
  62. package/dist/browser/content/chart-message-catalog.js.map +1 -1
  63. package/dist/browser/content/index.js +1 -0
  64. package/dist/browser/content/index.js.map +1 -1
  65. package/dist/browser/content/thumbnail-strip-messages.js +24 -0
  66. package/dist/browser/content/thumbnail-strip-messages.js.map +1 -0
  67. package/dist/browser/inputs/ChoiceInputs.js +132 -101
  68. package/dist/browser/inputs/ChoiceInputs.js.map +1 -1
  69. package/dist/browser/inputs/index.js +1 -0
  70. package/dist/browser/inputs/index.js.map +1 -1
  71. package/dist/browser/inputs/markdown/MarkdownSelectionToolbar.js +330 -0
  72. package/dist/browser/inputs/markdown/MarkdownSelectionToolbar.js.map +1 -0
  73. package/dist/browser/internal/field.js +96 -77
  74. package/dist/browser/internal/field.js.map +1 -1
  75. package/dist/browser/layout/AppWorkspace.js +7 -5
  76. package/dist/browser/layout/AppWorkspace.js.map +1 -1
  77. package/dist/browser/layout/PanelDialog.js +92 -68
  78. package/dist/browser/layout/PanelDialog.js.map +1 -1
  79. package/dist/browser/surfaces/StatCell.js +82 -70
  80. package/dist/browser/surfaces/StatCell.js.map +1 -1
  81. package/dist/browser/surfaces/stat-cell-messages.js +4 -2
  82. package/dist/browser/surfaces/stat-cell-messages.js.map +1 -1
  83. package/dist/browser/widgets/DashboardFrame.js +93 -88
  84. package/dist/browser/widgets/DashboardFrame.js.map +1 -1
  85. package/dist/ssr/actions/Toolbar.js +8 -2
  86. package/dist/ssr/actions/Toolbar.js.map +1 -1
  87. package/dist/ssr/charts/core/bar-labels.js +5 -0
  88. package/dist/ssr/charts/core/bar-labels.js.map +1 -0
  89. package/dist/ssr/charts/core/bubble.js +166 -0
  90. package/dist/ssr/charts/core/bubble.js.map +1 -0
  91. package/dist/ssr/charts/core/default-styles.js +83 -0
  92. package/dist/ssr/charts/core/default-styles.js.map +1 -0
  93. package/dist/ssr/charts/core/funnel-layout.js +79 -0
  94. package/dist/ssr/charts/core/funnel-layout.js.map +1 -0
  95. package/dist/ssr/charts/core/funnel.js +27 -0
  96. package/dist/ssr/charts/core/funnel.js.map +1 -0
  97. package/dist/ssr/charts/core/index.js +6 -1
  98. package/dist/ssr/charts/core/index.js.map +1 -1
  99. package/dist/ssr/charts/core/pareto.js +120 -0
  100. package/dist/ssr/charts/core/pareto.js.map +1 -0
  101. package/dist/ssr/charts/core/radar.js +101 -0
  102. package/dist/ssr/charts/core/radar.js.map +1 -0
  103. package/dist/ssr/charts/core/registry.js +11 -1
  104. package/dist/ssr/charts/core/registry.js.map +1 -1
  105. package/dist/ssr/charts/core/render-size.js +3 -1
  106. package/dist/ssr/charts/core/render-size.js.map +1 -1
  107. package/dist/ssr/charts/core/render.js +19 -0
  108. package/dist/ssr/charts/core/render.js.map +1 -1
  109. package/dist/ssr/charts/core/snapshot.js +1 -1
  110. package/dist/ssr/charts/core/snapshot.js.map +1 -1
  111. package/dist/ssr/charts/core/svg-barGauge.js +67 -0
  112. package/dist/ssr/charts/core/svg-barGauge.js.map +1 -0
  113. package/dist/ssr/charts/core/svg-boxplot.js +127 -0
  114. package/dist/ssr/charts/core/svg-boxplot.js.map +1 -0
  115. package/dist/ssr/charts/core/svg-common.js +1065 -0
  116. package/dist/ssr/charts/core/svg-common.js.map +1 -0
  117. package/dist/ssr/charts/core/svg-gauge.js +185 -0
  118. package/dist/ssr/charts/core/svg-gauge.js.map +1 -0
  119. package/dist/ssr/charts/core/svg-heatmap.js +80 -0
  120. package/dist/ssr/charts/core/svg-heatmap.js.map +1 -0
  121. package/dist/ssr/charts/core/svg-histogram.js +73 -0
  122. package/dist/ssr/charts/core/svg-histogram.js.map +1 -0
  123. package/dist/ssr/charts/core/svg-renderers.js +9 -1777
  124. package/dist/ssr/charts/core/svg-renderers.js.map +1 -1
  125. package/dist/ssr/charts/core/svg-scatter.js +114 -0
  126. package/dist/ssr/charts/core/svg-scatter.js.map +1 -0
  127. package/dist/ssr/charts/core/treemap.js +138 -0
  128. package/dist/ssr/charts/core/treemap.js.map +1 -0
  129. package/dist/ssr/charts/description.js.map +1 -1
  130. package/dist/ssr/content/ChartRoot.js +21 -7
  131. package/dist/ssr/content/ChartRoot.js.map +1 -1
  132. package/dist/ssr/content/ChartSnapshotView.js +1 -0
  133. package/dist/ssr/content/ChartSnapshotView.js.map +1 -1
  134. package/dist/ssr/content/DataTable.js +12 -16
  135. package/dist/ssr/content/DataTable.js.map +1 -1
  136. package/dist/ssr/content/Lightbox.js +32 -3
  137. package/dist/ssr/content/Lightbox.js.map +1 -1
  138. package/dist/ssr/content/ThumbnailStrip.js +103 -0
  139. package/dist/ssr/content/ThumbnailStrip.js.map +1 -0
  140. package/dist/ssr/content/chart-bar.js +98 -0
  141. package/dist/ssr/content/chart-bar.js.map +1 -1
  142. package/dist/ssr/content/chart-inspection-core.js +28 -8
  143. package/dist/ssr/content/chart-inspection-core.js.map +1 -1
  144. package/dist/ssr/content/chart-message-catalog.js +18 -0
  145. package/dist/ssr/content/chart-message-catalog.js.map +1 -1
  146. package/dist/ssr/content/index.js +1 -0
  147. package/dist/ssr/content/index.js.map +1 -1
  148. package/dist/ssr/content/thumbnail-strip-messages.js +24 -0
  149. package/dist/ssr/content/thumbnail-strip-messages.js.map +1 -0
  150. package/dist/ssr/inputs/ChoiceInputs.js +55 -40
  151. package/dist/ssr/inputs/ChoiceInputs.js.map +1 -1
  152. package/dist/ssr/inputs/index.js +1 -0
  153. package/dist/ssr/inputs/index.js.map +1 -1
  154. package/dist/ssr/inputs/markdown/MarkdownSelectionToolbar.js +293 -0
  155. package/dist/ssr/inputs/markdown/MarkdownSelectionToolbar.js.map +1 -0
  156. package/dist/ssr/internal/field.js +36 -24
  157. package/dist/ssr/internal/field.js.map +1 -1
  158. package/dist/ssr/layout/AppWorkspace.js +5 -1
  159. package/dist/ssr/layout/AppWorkspace.js.map +1 -1
  160. package/dist/ssr/layout/PanelDialog.js +40 -26
  161. package/dist/ssr/layout/PanelDialog.js.map +1 -1
  162. package/dist/ssr/surfaces/StatCell.js +29 -18
  163. package/dist/ssr/surfaces/StatCell.js.map +1 -1
  164. package/dist/ssr/surfaces/stat-cell-messages.js +4 -2
  165. package/dist/ssr/surfaces/stat-cell-messages.js.map +1 -1
  166. package/dist/ssr/widgets/DashboardFrame.js +6 -11
  167. package/dist/ssr/widgets/DashboardFrame.js.map +1 -1
  168. package/dist/styles.css +1 -1
  169. package/dist/types/actions/Toolbar.d.ts +2 -0
  170. package/dist/types/charts/core/bar-labels.d.ts +1 -0
  171. package/dist/types/charts/core/bubble.d.ts +66 -0
  172. package/dist/types/charts/core/default-styles.d.ts +1 -0
  173. package/dist/types/charts/core/funnel-layout.d.ts +43 -0
  174. package/dist/types/charts/core/funnel.d.ts +13 -0
  175. package/dist/types/charts/core/index.d.ts +6 -1
  176. package/dist/types/charts/core/pareto.d.ts +40 -0
  177. package/dist/types/charts/core/radar.d.ts +47 -0
  178. package/dist/types/charts/core/registry.d.ts +10 -0
  179. package/dist/types/charts/core/render-size.d.ts +1 -1
  180. package/dist/types/charts/core/svg-barGauge.d.ts +3 -0
  181. package/dist/types/charts/core/svg-boxplot.d.ts +18 -0
  182. package/dist/types/charts/core/svg-common.d.ts +612 -0
  183. package/dist/types/charts/core/svg-gauge.d.ts +6 -0
  184. package/dist/types/charts/core/svg-heatmap.d.ts +6 -0
  185. package/dist/types/charts/core/svg-histogram.d.ts +16 -0
  186. package/dist/types/charts/core/svg-renderers.d.ts +8 -612
  187. package/dist/types/charts/core/svg-scatter.d.ts +23 -0
  188. package/dist/types/charts/core/treemap.d.ts +45 -0
  189. package/dist/types/charts/description.d.ts +63 -0
  190. package/dist/types/content/ChartRoot.d.ts +1 -1
  191. package/dist/types/content/Lightbox.d.ts +2 -0
  192. package/dist/types/content/ThumbnailStrip.d.ts +29 -0
  193. package/dist/types/content/chart-bar.d.ts +38 -2
  194. package/dist/types/content/chart-inspection-core.d.ts +7 -0
  195. package/dist/types/content/chart-inspection.d.ts +1 -0
  196. package/dist/types/content/chart-message-catalog.d.ts +8 -0
  197. package/dist/types/content/index.d.ts +1 -0
  198. package/dist/types/content/thumbnail-strip-messages.d.ts +10 -0
  199. package/dist/types/inputs/ChoiceInputs.d.ts +2 -0
  200. package/dist/types/inputs/index.d.ts +2 -0
  201. package/dist/types/inputs/markdown/MarkdownSelectionToolbar.d.ts +19 -0
  202. package/dist/types/internal/field.d.ts +2 -0
  203. package/dist/types/layout/PanelDialog.d.ts +5 -0
  204. package/dist/types/surfaces/stat-cell-messages.d.ts +1 -0
  205. package/dist/types/widgets/DashboardFrame.d.ts +4 -1
  206. package/package.json +2 -2
@@ -1,1305 +1,12 @@
1
- // Ported from @k2b/stdlib 0.30.0 (ISC); retain SVG and numeric algorithms until parity proves changes.
2
- // ==========================
3
- // SVG Chart Generation
4
- // ==========================
5
- //
6
- // Pure-native SVG generation for the four basic chart types: scatter, line,
7
- // bar, and pie/donut. Returns SVG strings — inject directly into the DOM,
8
- // write to disk, or send over the wire. No peer dependencies.
9
- //
10
- // Charts ship with embedded default CSS using semantic class names and CSS
11
- // custom properties for colors. Consumers override styles via class selectors
12
- // (their CSS wins on specificity) or CSS variables (`--stdlib-chart-c1` ...
13
- // `--stdlib-chart-c8`). Axes and labels use `currentColor` so parent `color`
14
- // drives theming (dark mode "just works").
15
-
16
- // ==========================
17
- // PUBLIC TYPES
18
- // ==========================
19
-
20
- /** Marker shapes for `scatter` data points. Auto-cycles per series when
21
- * `autoVariant` is enabled on the chart. */
22
-
23
- /** Line dash patterns for `line` series. Auto-cycles per series when
24
- * `autoVariant` is enabled. */
25
-
26
- const itemColorIndex = (item, fallback) => {
27
- const index = item.colorIndex ?? fallback;
28
- if (!Number.isInteger(index) || index < 0) throw new RangeError("Chart colorIndex must be a nonnegative integer");
29
- return index % 8;
30
- };
31
- /** One selectable datum in an inspected SVG. Indices refer to the source arrays.
32
- * `anchor` uses the containing SVG coordinate system, including nested map SVGs.
33
- * Values are raw data; `formatted` contains the renderer's axis/value formatting.
34
- */
35
-
36
- /** Wrap renderer-owned geometry with escaped, inert inspection metadata. */
37
- export const chartDatumSvg = (svg, datum, inspect, titleText) => {
38
- if (!inspect || !datum.anchor.every(Number.isFinite)) return svg;
39
- const title = titleText ?? [datum.label, ...datum.values.map(field => `${field.key}: ${field.formatted ?? field.value}`)].filter(Boolean).join(" · ");
40
- return `<g data-chart-role="${escapeXml(datum.role)}" data-chart-datum="${escapeXml(JSON.stringify(datum))}"><title>${escapeXml(title)}</title>${svg}</g>`;
41
- };
42
- const inspectionPoint = (datum, inspect) => inspect ? chartDatumSvg(`<circle class="stdlib-chart-inspection-point" cx="${fmt(datum.anchor[0])}" cy="${fmt(datum.anchor[1])}" r="3" fill="transparent" stroke="none"/>`, datum, true) : "";
43
- const pointValues = (p, xAxis, yAxis) => [{
44
- key: "x",
45
- value: p.x,
46
- formatted: xAxis?.format?.(p.x)
47
- }, {
48
- key: "y",
49
- value: p.y,
50
- formatted: yAxis?.format?.(p.y)
51
- }, ...Object.entries(p).filter(([key, value]) => key !== "x" && key !== "y" && typeof value === "number" && Number.isFinite(value)).map(([key, value]) => ({
52
- key,
53
- value
54
- }))];
55
-
56
- /**
57
- * A horizontal or vertical reference line drawn on a cartesian chart, e.g.
58
- * for thresholds, targets, or averages.
59
- */
60
-
61
- /** Internal shared attributes for raw cartesian charts and UI bar layouts. */
62
- export const referenceLineAttributes = (ref, label = false) => {
63
- const declarations = [];
64
- if (!label && ref.style !== undefined) {
65
- const styles = {
66
- solid: "none",
67
- dashed: "4 4",
68
- dotted: "1 3"
69
- };
70
- const dash = styles[ref.style];
71
- if (typeof dash !== "string") throw new RangeError("Invalid reference line style");
72
- declarations.push(`stroke-dasharray:${dash}`);
73
- if (ref.style === "dotted") declarations.push("stroke-linecap:round");
74
- }
75
- if (ref.tone !== undefined) {
76
- const tones = {
77
- neutral: "currentColor",
78
- info: "var(--k2b-info-text,#1d4ed8)",
79
- success: "var(--k2b-success-text,#047857)",
80
- warning: "var(--k2b-warning-text,#92400e)",
81
- danger: "var(--k2b-danger-text,#b91c1c)"
82
- };
83
- const color = tones[ref.tone];
84
- if (typeof color !== "string") throw new RangeError("Invalid reference line tone");
85
- declarations.push(`color:${color}`);
86
- }
87
- return declarations.length ? ` style="${declarations.join(";")}"` : "";
88
- };
89
-
90
- // ==========================
91
- // CONSTANTS
92
- // ==========================
93
-
94
- const DEFAULT_WIDTH = 400;
95
- const DEFAULT_HEIGHT = 240;
96
- const DEFAULT_PADDING = {
97
- top: 16,
98
- right: 16,
99
- bottom: 32,
100
- left: 40
101
- };
102
- const DEFAULT_TICKS = 5;
103
- const DEFAULT_MARKERS = ["circle", "square", "triangle", "diamond", "plus", "cross"];
104
- const DEFAULT_LINE_STYLES = ["solid", "dashed", "dotted", "dashdot"];
105
-
106
- /** SVG `stroke-dasharray` values per line style. Empty string = no dasharray. */
107
- const LINE_DASH_PATTERNS = {
108
- solid: "",
109
- dashed: "6 4",
110
- dotted: "2 3",
111
- dashdot: "6 3 2 3"
112
- };
113
-
114
- // CSS rule order is significant. Series-N rules emit first so shape-specific
115
- // rules below can override (e.g. line's `fill: none` beats series fill, and
116
- // slice/point's `stroke: white` beats series stroke).
117
- const DEFAULT_STYLES = `
118
- /* font-family is intentionally not set here so the chart inherits the app's
119
- font from its surrounding HTML context. For standalone SVG usage, set
120
- font-family on a wrapping element or override .stdlib-chart in your CSS. */
121
- .stdlib-chart {
122
- color: #1f2937;
123
- --stdlib-chart-c1: #3b82f6; --stdlib-chart-c2: #10b981;
124
- --stdlib-chart-c3: #f59e0b; --stdlib-chart-c4: #ef4444;
125
- --stdlib-chart-c5: #8b5cf6; --stdlib-chart-c6: #ec4899;
126
- --stdlib-chart-c7: #14b8a6; --stdlib-chart-c8: #f97316;
127
- }
128
- .stdlib-chart-series-0 { fill: var(--stdlib-chart-c1); stroke: var(--stdlib-chart-c1); }
129
- .stdlib-chart-series-1 { fill: var(--stdlib-chart-c2); stroke: var(--stdlib-chart-c2); }
130
- .stdlib-chart-series-2 { fill: var(--stdlib-chart-c3); stroke: var(--stdlib-chart-c3); }
131
- .stdlib-chart-series-3 { fill: var(--stdlib-chart-c4); stroke: var(--stdlib-chart-c4); }
132
- .stdlib-chart-series-4 { fill: var(--stdlib-chart-c5); stroke: var(--stdlib-chart-c5); }
133
- .stdlib-chart-series-5 { fill: var(--stdlib-chart-c6); stroke: var(--stdlib-chart-c6); }
134
- .stdlib-chart-series-6 { fill: var(--stdlib-chart-c7); stroke: var(--stdlib-chart-c7); }
135
- .stdlib-chart-series-7 { fill: var(--stdlib-chart-c8); stroke: var(--stdlib-chart-c8); }
136
- .stdlib-chart-axis { stroke: currentColor; opacity: 0.4; fill: none; }
137
- .stdlib-chart-tick-label { font-size: 10px; fill: currentColor; opacity: 0.6; }
138
- .stdlib-chart-axis-label { font-size: 11px; fill: currentColor; opacity: 0.85; }
139
- .stdlib-chart-grid { stroke: currentColor; opacity: 0.08; stroke-dasharray: 2 2; fill: none; }
140
- .stdlib-chart-title { font-size: 14px; font-weight: 600; fill: currentColor; }
141
- .stdlib-chart-subtitle { font-size: 11px; fill: currentColor; opacity: 0.7; }
142
- .stdlib-chart-reference { stroke: currentColor; opacity: 0.5; stroke-dasharray: 4 4; fill: none; }
143
- .stdlib-chart-reference-label { font-size: 10px; fill: currentColor; opacity: 0.7; }
144
- .stdlib-chart-line { fill: none; stroke-width: 2; }
145
- .stdlib-chart-area { fill-opacity: 0.18; stroke: none; }
146
- .stdlib-chart-sparkline { fill: none; stroke-width: 1.5; stroke: currentColor; }
147
- .stdlib-chart-sparkline-area { stroke: none; }
148
- .stdlib-chart-sparkline-last { fill: currentColor; stroke: none; }
149
- .stdlib-chart-sparkline-max { fill: #10b981; stroke: none; }
150
- .stdlib-chart-sparkline-min { fill: #ef4444; stroke: none; }
151
- .stdlib-chart-point { stroke: white; stroke-width: 1.5; }
152
- .stdlib-chart-slice { stroke: white; stroke-width: 2; stroke-linejoin: round; }
153
- .stdlib-chart-label { font-size: 11px; fill: currentColor; }
154
- .stdlib-chart-bar-value { font-size: 10px; fill: currentColor; opacity: 0.8; }
155
- .stdlib-chart-errorbar { stroke: currentColor; opacity: 0.55; fill: none; stroke-width: 1; }
156
- .stdlib-chart-error-band { fill-opacity: 0.15; stroke: none; }
157
- .stdlib-chart-trendline { stroke: currentColor; opacity: 0.55; stroke-width: 1.5; fill: none; stroke-dasharray: 5 4; }
158
- .stdlib-chart-minor-tick { stroke: currentColor; opacity: 0.25; }
159
- .stdlib-chart-box { fill-opacity: 0.4; stroke-width: 1; }
160
- .stdlib-chart-box-median { stroke: currentColor; stroke-width: 1.5; fill: none; }
161
- .stdlib-chart-box-whisker { stroke: currentColor; opacity: 0.6; fill: none; }
162
- .stdlib-chart-box-cap { stroke: currentColor; opacity: 0.6; fill: none; }
163
- .stdlib-chart-box-outlier { fill: currentColor; opacity: 0.5; stroke: white; stroke-width: 1; }
164
- .stdlib-chart-legend-swatch { stroke: none; }
165
- .stdlib-chart-legend-label { font-size: 11px; font-weight: 400; fill: currentColor; stroke: none; }
166
- .stdlib-chart-empty-text { font-size: 11px; fill: currentColor; opacity: 0.5; }
167
- .stdlib-chart-gauge-track { stroke: currentColor; stroke-width: 10; opacity: 0.12; fill: none; stroke-linecap: round; }
168
- .stdlib-chart-gauge-fill { stroke-width: 10; fill: none; stroke-linecap: round; }
169
- .stdlib-chart-gauge-gradient-segment { stroke-width: 10; fill: none; stroke-linecap: butt; }
170
- .stdlib-chart-gauge-gradient-scale { opacity: 0.22; }
171
- .stdlib-chart-gauge-needle { stroke-width: 2; fill: none; stroke-linecap: round; }
172
- .stdlib-chart-gauge-hub { fill: currentColor; stroke: none; }
173
- .stdlib-chart-gauge-value { font-size: 28px; font-weight: 700; fill: currentColor; }
174
- .stdlib-chart-gauge-label { font-size: 12px; fill: currentColor; opacity: 0.72; }
175
- .stdlib-chart-gauge-unit { font-size: 11px; fill: currentColor; opacity: 0.6; }
176
- .stdlib-chart-bar-gauge-track { fill: currentColor; opacity: 0.1; }
177
- .stdlib-chart-bar-gauge-fill { stroke: none; }
178
- .stdlib-chart-bar-gauge-label { font-size: 11px; fill: currentColor; opacity: 0.75; }
179
- .stdlib-chart-bar-gauge-value { font-size: 11px; font-weight: 600; fill: currentColor; }
180
- .stdlib-chart-stat-label { font-size: 12px; fill: currentColor; opacity: 0.72; }
181
- .stdlib-chart-stat-value { font-size: 30px; font-weight: 700; fill: currentColor; }
182
- .stdlib-chart-stat-unit { font-size: 14px; font-weight: 600; fill: currentColor; opacity: 0.72; }
183
- .stdlib-chart-stat-delta { font-size: 12px; font-weight: 600; fill: currentColor; opacity: 0.72; }
184
- .stdlib-chart-stat-delta-up { fill: #10b981; opacity: 1; }
185
- .stdlib-chart-stat-delta-down { fill: #ef4444; opacity: 1; }
186
- .stdlib-chart-stat-sparkline { fill: none; stroke: currentColor; stroke-width: 1.6; opacity: 0.86; }
187
- .stdlib-chart-stat-sparkline-area { stroke: none; opacity: 0.18; }
188
- .stdlib-chart-heatmap-cell { stroke: white; stroke-width: 1; }
189
- .stdlib-chart-heatmap-label { font-size: 10px; fill: currentColor; opacity: 0.68; }
190
- .stdlib-chart-map-land { fill: currentColor; opacity: var(--stdlib-chart-map-land-opacity, 0.12); stroke: currentColor; stroke-width: 0.5; stroke-linejoin: round; }
191
- .stdlib-chart-map-point { stroke: var(--stdlib-chart-map-point-stroke, white); stroke-width: 1.5; }
192
- .stdlib-chart-map-empty { font-size: 11px; fill: currentColor; opacity: 0.55; }
193
- .stdlib-chart-state-region { stroke: white; stroke-width: 1; }
194
- .stdlib-chart-state-label { font-size: 11px; fill: currentColor; opacity: 0.75; }
195
- `.trim();
196
-
197
- // ==========================
198
- // HELPERS (pure)
199
- // ==========================
200
-
201
- /** XML-escape a string for safe inclusion in attribute values or text content. */
202
- export const escapeXml = s => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
203
-
204
- /** Normalize a `Padding` input (number or partial object) to a full `Padding`. */
205
- export const normalizePadding = p => {
206
- if (p === undefined) return {
207
- ...DEFAULT_PADDING
208
- };
209
- if (typeof p === "number") return {
210
- top: p,
211
- right: p,
212
- bottom: p,
213
- left: p
214
- };
215
- return {
216
- top: p.top ?? DEFAULT_PADDING.top,
217
- right: p.right ?? DEFAULT_PADDING.right,
218
- bottom: p.bottom ?? DEFAULT_PADDING.bottom,
219
- left: p.left ?? DEFAULT_PADDING.left
220
- };
221
- };
222
-
223
- /**
224
- * Compute `[min, max]` from a list of numeric values, ignoring non-finite
225
- * entries. Returns `[0, 1]` for an empty/all-non-finite list and pads ±1
226
- * around a single finite value.
227
- */
228
- export const computeDomain = values => {
229
- let min = Number.POSITIVE_INFINITY;
230
- let max = Number.NEGATIVE_INFINITY;
231
- for (const v of values) {
232
- if (!Number.isFinite(v)) continue;
233
- if (v < min) min = v;
234
- if (v > max) max = v;
235
- }
236
- if (!Number.isFinite(min) || !Number.isFinite(max)) return [0, 1];
237
- if (min === max) return [min - 1, max + 1];
238
- return [min, max];
239
- };
240
-
241
- /**
242
- * Pick a "nice" axis step (1, 2, 5, 10, 20, 50, ...) that splits `range`
243
- * into roughly `target` intervals. Avoids ugly tick labels like 0.473.
244
- */
245
- export const niceStep = (range, target) => {
246
- if (range <= 0 || target <= 0) return 1;
247
- const rough = range / target;
248
- const mag = Math.pow(10, Math.floor(Math.log10(rough)));
249
- const norm = rough / mag;
250
- const nice = norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10;
251
- return nice * mag;
252
- };
253
-
254
- /** The most ticks one linear axis counts, the same budget as a time axis; more never fit a readable axis. */
255
- export const MAX_AXIS_TICKS = 1_000;
256
-
257
- /**
258
- * Round `min` down and `max` up to the nearest multiples of `step`, so the
259
- * domain edges fall on tick boundaries. Returns the extended domain plus the
260
- * tick values within it (inclusive of both ends).
261
- */
262
- export const extendDomainToNice = (min, max, step) => {
263
- const lo = Math.floor(min / step) * step;
264
- const hi = Math.ceil(max / step) * step;
265
- const ticks = [];
266
- // Use rounding to avoid floating-point drift at tick positions.
267
- const decimals = Math.max(0, -Math.floor(Math.log10(step)));
268
- const round = v => Number(v.toFixed(Math.min(decimals + 2, 12)));
269
- // A step below the float spacing of large values never advances, and a tiny step counts without end: keep the ends.
270
- const ends = {
271
- domain: [lo, hi],
272
- ticks: [...new Set([round(lo), round(hi)])]
273
- };
274
- if ((hi - lo) / step > MAX_AXIS_TICKS) return ends;
275
- for (let v = lo; v <= hi + step / 2;) {
276
- ticks.push(round(v));
277
- const next = v + step;
278
- if (next <= v) return ends;
279
- v = next;
280
- }
281
- return {
282
- domain: [lo, hi],
283
- ticks
284
- };
285
- };
286
-
287
- /** Linear map of `value` from input domain `[d0, d1]` to output range `[r0, r1]`. */
288
- export const mapRange = (value, [d0, d1], [r0, r1]) => {
289
- if (d1 === d0) return (r0 + r1) / 2;
290
- return r0 + (value - d0) / (d1 - d0) * (r1 - r0);
291
- };
292
-
293
- /**
294
- * Logarithmic (base-10) map of `value` from input domain `[d0, d1]` to
295
- * output range `[r0, r1]`. Both domain endpoints must be strictly positive.
296
- * Non-positive values are clamped to a small epsilon to avoid `-Infinity`.
297
- */
298
- export const mapLog = (value, [d0, d1], [r0, r1]) => {
299
- if (d0 <= 0 || d1 <= 0) return (r0 + r1) / 2;
300
- const v = Math.max(value, 1e-300);
301
- const logD0 = Math.log10(d0);
302
- const logD1 = Math.log10(d1);
303
- if (logD0 === logD1) return (r0 + r1) / 2;
304
- return r0 + (Math.log10(v) - logD0) / (logD1 - logD0) * (r1 - r0);
305
- };
306
-
307
- /**
308
- * Compute logarithmic ticks (powers of 10) within `[min, max]`. The
309
- * returned array always includes both decade boundaries enclosing the
310
- * domain so the axis line spans the data.
311
- */
312
- export const niceLogTicks = (min, max) => {
313
- const safeMin = Math.max(min, 1e-300);
314
- const safeMax = Math.max(max, safeMin);
315
- // Clamp the log-tick range to a finite, SVG-safe span so callers passing
316
- // Number.MAX_VALUE (or non-finite extremes) don't trigger an infinite loop.
317
- // 1e-30 .. 1e30 covers every real-world scientific magnitude.
318
- const MIN_EXP = -30;
319
- const MAX_EXP = 30;
320
- const loExp = Math.max(MIN_EXP, Math.floor(Math.log10(safeMin)));
321
- const hiExp = Math.min(MAX_EXP, Math.ceil(Math.log10(safeMax)));
322
- const lo = Math.pow(10, loExp);
323
- const hi = Math.pow(10, Math.max(loExp, hiExp));
324
- const ticks = [];
325
- // Iterate by exponent to avoid floating-point drift at extreme ranges.
326
- for (let e = loExp; e <= Math.max(loExp, hiExp); e++) {
327
- ticks.push(Math.pow(10, e));
328
- }
329
- return {
330
- domain: [lo, hi],
331
- ticks
332
- };
333
- };
334
-
335
- /**
336
- * Least-squares linear regression. Returns slope, intercept, and r² for the
337
- * regression line `y = slope * x + intercept`. Returns null for fewer than
338
- * two finite points or all-x-equal input.
339
- */
340
- export const linearRegression = points => {
341
- const finite = points.filter(p => Number.isFinite(p.x) && Number.isFinite(p.y));
342
- const n = finite.length;
343
- if (n < 2) return null;
344
- let sumX = 0;
345
- let sumY = 0;
346
- for (const p of finite) {
347
- sumX += p.x;
348
- sumY += p.y;
349
- }
350
- const meanX = sumX / n;
351
- const meanY = sumY / n;
352
- let num = 0;
353
- let denom = 0;
354
- let totalSS = 0;
355
- for (const p of finite) {
356
- const dx = p.x - meanX;
357
- const dy = p.y - meanY;
358
- num += dx * dy;
359
- denom += dx * dx;
360
- totalSS += dy * dy;
361
- }
362
- if (denom === 0) return null;
363
- const slope = num / denom;
364
- const intercept = meanY - slope * meanX;
365
- // r² via 1 - SSres / SStot
366
- let resSS = 0;
367
- for (const p of finite) {
368
- const predicted = slope * p.x + intercept;
369
- const resid = p.y - predicted;
370
- resSS += resid * resid;
371
- }
372
- const r2 = totalSS === 0 ? 1 : 1 - resSS / totalSS;
373
- return {
374
- slope,
375
- intercept,
376
- r2
377
- };
378
- };
379
-
380
- /**
381
- * Compute box-plot statistics for a set of observations:
382
- * min/max, quartiles (q1/q2/q3 via R-7 linear interpolation), Tukey whiskers
383
- * (1.5×IQR rule clamped to data extents), and outliers beyond the whiskers.
384
- *
385
- * Returns null for an empty/all-non-finite input.
386
- */
387
- export const computeBoxStats = values => {
388
- const finite = values.filter(v => Number.isFinite(v));
389
- if (finite.length === 0) return null;
390
- const sorted = [...finite].sort((a, b) => a - b);
391
- const quantile = q => {
392
- // R-7 (linear interpolation between consecutive order statistics).
393
- const pos = q * (sorted.length - 1);
394
- const lo = Math.floor(pos);
395
- const hi = Math.ceil(pos);
396
- if (lo === hi) return sorted[lo];
397
- return sorted[lo] + (pos - lo) * (sorted[hi] - sorted[lo]);
398
- };
399
- const q1 = quantile(0.25);
400
- const q2 = quantile(0.5);
401
- const q3 = quantile(0.75);
402
- const iqr = q3 - q1;
403
- const fenceLow = q1 - 1.5 * iqr;
404
- const fenceHigh = q3 + 1.5 * iqr;
405
- // Whiskers extend to the most-extreme data point still inside the fences.
406
- let whiskerLow = q1;
407
- let whiskerHigh = q3;
408
- for (const v of sorted) {
409
- if (v >= fenceLow && v < whiskerLow) whiskerLow = v;
410
- if (v <= fenceHigh && v > whiskerHigh) whiskerHigh = v;
411
- }
412
- const outliers = sorted.filter(v => v < fenceLow || v > fenceHigh);
413
- return {
414
- min: sorted[0],
415
- max: sorted[sorted.length - 1],
416
- q1,
417
- q2,
418
- q3,
419
- whiskerLow,
420
- whiskerHigh,
421
- outliers
422
- };
423
- };
424
-
425
- /**
426
- * Bin a numeric dataset into a histogram. `bins` may be:
427
- * - undefined → Sturges' formula `ceil(log2(n)) + 1`
428
- * - a number → that many equal-width bins
429
- * - an array of edges (length k+1 → k bins)
430
- *
431
- * Non-finite input values are filtered. Returns bin edges and per-bin counts.
432
- */
433
- export const autoBin = (values, bins) => {
434
- const finite = values.filter(v => Number.isFinite(v));
435
- if (finite.length === 0) return {
436
- edges: [0, 1],
437
- counts: [0]
438
- };
439
-
440
- // Cap bin count so a malicious / mistyped `bins: 1e9` doesn't allocate
441
- // gigabytes. 1024 is generous: 30 is Sturges' for 1e9 samples.
442
- const MAX_BINS = 1024;
443
- let edges;
444
- if (Array.isArray(bins)) {
445
- const sorted = [...bins].filter(e => Number.isFinite(e)).sort((a, b) => a - b);
446
- if (sorted.length >= 2) {
447
- edges = sorted;
448
- } else {
449
- // Empty or single-edge input → fall back to a single auto-bin span over
450
- // the data so we never emit `[undefined, NaN]` edges.
451
- const dmin = Math.min(...finite);
452
- const dmax = Math.max(...finite);
453
- edges = dmin === dmax ? [dmin - 0.5, dmin + 0.5] : [dmin, dmax];
454
- }
455
- } else {
456
- // Single-loop min/max — `Math.min(...arr)` fails with RangeError on huge
457
- // arrays (call-stack overflow) and is also O(n) anyway.
458
- let min = Infinity;
459
- let max = -Infinity;
460
- for (const v of finite) {
461
- if (v < min) min = v;
462
- if (v > max) max = v;
463
- }
464
- const range = max - min;
465
- let k;
466
- if (typeof bins === "number" && bins > 0) {
467
- k = Math.min(MAX_BINS, Math.floor(bins));
468
- } else {
469
- k = Math.max(1, Math.min(MAX_BINS, Math.ceil(Math.log2(finite.length)) + 1));
470
- }
471
- if (range === 0) {
472
- edges = [min - 0.5, min + 0.5];
473
- } else {
474
- const step = range / k;
475
- edges = Array.from({
476
- length: k + 1
477
- }, (_, i) => min + i * step);
478
- }
479
- }
480
- const counts = new Array(edges.length - 1).fill(0);
481
- for (const v of finite) {
482
- // Right-open intervals [e_i, e_{i+1}); last bin closed-closed.
483
- let bin = -1;
484
- for (let i = 0; i < counts.length; i++) {
485
- const isLast = i === counts.length - 1;
486
- if (v >= edges[i] && (isLast ? v <= edges[i + 1] : v < edges[i + 1])) {
487
- bin = i;
488
- break;
489
- }
490
- }
491
- if (bin >= 0) counts[bin] += 1;
492
- }
493
- return {
494
- edges,
495
- counts
496
- };
497
- };
498
-
499
- // ==========================
500
- // SVG SKELETON
501
- // ==========================
502
-
503
- export const computePlotArea = (width, height, padding, hasXAxisLabel, hasYAxisLabel, headerHeight = 0, legendHeight = 0) => {
504
- // Reserve extra space when axis labels are present.
505
- const extraBottom = hasXAxisLabel ? 14 : 0;
506
- const extraLeft = hasYAxisLabel ? 14 : 0;
507
- return {
508
- x0: padding.left + extraLeft,
509
- y0: padding.top + headerHeight,
510
- x1: width - padding.right,
511
- y1: height - padding.bottom - extraBottom - legendHeight
512
- };
513
- };
514
-
515
- /**
516
- * Render an optional centered header (title + subtitle) at the top of an
517
- * SVG. Returns the SVG fragment plus the pixel height it consumed so the
518
- * caller can shift the plot area down accordingly.
519
- */
520
- export const renderHeader = (width, title, subtitle) => {
521
- if (!title && !subtitle) return {
522
- svg: "",
523
- height: 0
524
- };
525
- const cx = width / 2;
526
- const parts = [];
527
- let y = 16;
528
- if (title) {
529
- parts.push(`<text class="stdlib-chart-title" x="${fmt(cx)}" y="${fmt(y)}" text-anchor="middle">${escapeXml(title)}</text>`);
530
- y += 14;
531
- }
532
- if (subtitle) {
533
- parts.push(`<text class="stdlib-chart-subtitle" x="${fmt(cx)}" y="${fmt(y)}" text-anchor="middle">${escapeXml(subtitle)}</text>`);
534
- y += 6;
535
- }
536
- return {
537
- svg: parts.join(""),
538
- height: y
539
- };
540
- };
541
-
542
- /**
543
- * Render reference lines (horizontal or vertical thresholds) within the plot
544
- * area. Out-of-domain values are silently skipped. Honors per-axis scale
545
- * (linear or log).
546
- */
547
- const renderReferenceLines = (refs, xAxis, yAxis, area) => {
548
- const xMap = pickMapper(xAxis.scale);
549
- const yMap = pickMapper(yAxis.scale);
550
- const parts = [];
551
- for (const ref of refs) {
552
- if (!Number.isFinite(ref.value)) continue;
553
- const axis = ref.axis ?? "y";
554
- if (axis === "y") {
555
- if (ref.value < yAxis.domain[0] || ref.value > yAxis.domain[1]) continue;
556
- const y = yMap(ref.value, yAxis.domain, [area.y1, area.y0]);
557
- parts.push(`<line class="stdlib-chart-reference"${referenceLineAttributes(ref)} x1="${fmt(area.x0)}" y1="${fmt(y)}" x2="${fmt(area.x1)}" y2="${fmt(y)}"/>`);
558
- if (ref.label) {
559
- parts.push(`<text class="stdlib-chart-reference-label"${referenceLineAttributes(ref, true)} x="${fmt(area.x1 - 4)}" y="${fmt(y - 4)}" text-anchor="end">${escapeXml(ref.label)}</text>`);
560
- }
561
- } else {
562
- if (ref.value < xAxis.domain[0] || ref.value > xAxis.domain[1]) continue;
563
- const x = xMap(ref.value, xAxis.domain, [area.x0, area.x1]);
564
- parts.push(`<line class="stdlib-chart-reference"${referenceLineAttributes(ref)} x1="${fmt(x)}" y1="${fmt(area.y0)}" x2="${fmt(x)}" y2="${fmt(area.y1)}"/>`);
565
- if (ref.label) {
566
- parts.push(`<text class="stdlib-chart-reference-label"${referenceLineAttributes(ref, true)} x="${fmt(x + 4)}" y="${fmt(area.y0 + 12)}">${escapeXml(ref.label)}</text>`);
567
- }
568
- }
569
- }
570
- return parts.join("");
571
- };
572
-
573
- /**
574
- * Resolve a point's effective error extents into `[low, high]` magnitudes
575
- * (relative deltas, both ≥ 0). Asymmetric `errYHigh`/`errYLow` take precedence
576
- * over symmetric `errY`. Returns null when no error info is set.
577
- */
578
- const resolveErrorY = p => {
579
- const high = p.errYHigh ?? p.errY;
580
- const low = p.errYLow ?? p.errY;
581
- if (high === undefined && low === undefined) return null;
582
- return [Number.isFinite(low) ? Math.abs(low) : 0, Number.isFinite(high) ? Math.abs(high) : 0];
583
- };
584
- const resolveErrorX = p => {
585
- const high = p.errXHigh ?? p.errX;
586
- const low = p.errXLow ?? p.errX;
587
- if (high === undefined && low === undefined) return null;
588
- return [Number.isFinite(low) ? Math.abs(low) : 0, Number.isFinite(high) ? Math.abs(high) : 0];
589
- };
590
-
591
- /** Build the SVG fragment for the per-point error bars across all series. */
592
- const renderErrorBars = (series, xAxis, yAxis, area) => {
593
- const xMap = pickMapper(xAxis.scale);
594
- const yMap = pickMapper(yAxis.scale);
595
- const CAP = 4; // half-width of error bar caps in pixels
596
- const parts = [];
597
- for (const s of series) {
598
- for (const p of s.data) {
599
- if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) continue;
600
- const cx = xMap(p.x, xAxis.domain, [area.x0, area.x1]);
601
- const cy = yMap(p.y, yAxis.domain, [area.y1, area.y0]);
602
- const yErr = resolveErrorY(p);
603
- if (yErr) {
604
- const [low, high] = yErr;
605
- const yHi = yMap(p.y + high, yAxis.domain, [area.y1, area.y0]);
606
- const yLo = yMap(p.y - low, yAxis.domain, [area.y1, area.y0]);
607
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx)}" y1="${fmt(yHi)}" x2="${fmt(cx)}" y2="${fmt(yLo)}"/>`);
608
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx - CAP)}" y1="${fmt(yHi)}" x2="${fmt(cx + CAP)}" y2="${fmt(yHi)}"/>`);
609
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(cx - CAP)}" y1="${fmt(yLo)}" x2="${fmt(cx + CAP)}" y2="${fmt(yLo)}"/>`);
610
- // Mark we need cy to match data point — ensure we use it (silences unused warnings if any).
611
- void cy;
612
- }
613
- const xErr = resolveErrorX(p);
614
- if (xErr) {
615
- const [low, high] = xErr;
616
- const xHi = xMap(p.x + high, xAxis.domain, [area.x0, area.x1]);
617
- const xLo = xMap(p.x - low, xAxis.domain, [area.x0, area.x1]);
618
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xLo)}" y1="${fmt(cy)}" x2="${fmt(xHi)}" y2="${fmt(cy)}"/>`);
619
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xLo)}" y1="${fmt(cy - CAP)}" x2="${fmt(xLo)}" y2="${fmt(cy + CAP)}"/>`);
620
- parts.push(`<line class="stdlib-chart-errorbar" x1="${fmt(xHi)}" y1="${fmt(cy - CAP)}" x2="${fmt(xHi)}" y2="${fmt(cy + CAP)}"/>`);
621
- }
622
- }
623
- }
624
- return parts.join("");
625
- };
626
-
627
- /** Collect all values relevant for axis-domain computation, including error
628
- * extents so error bars don't get clipped. */
629
- const collectAxisValues = (series, axis) => {
630
- const out = [];
631
- for (const s of series) {
632
- for (const p of s.data) {
633
- const v = axis === "x" ? p.x : p.y;
634
- if (!Number.isFinite(v)) continue;
635
- out.push(v);
636
- const err = axis === "x" ? resolveErrorX(p) : resolveErrorY(p);
637
- if (err) {
638
- out.push(v - err[0]);
639
- out.push(v + err[1]);
640
- }
641
- }
642
- }
643
- return out;
644
- };
645
-
646
- /**
647
- * Render a single-row centered legend at the bottom of the SVG. Returns the
648
- * SVG fragment plus the height it consumed so callers can shift the plot
649
- * area up accordingly. Empty input yields height 0.
650
- */
651
- export const renderLegend = (items, width, yTop) => {
652
- if (items.length === 0) return {
653
- svg: "",
654
- height: 0
655
- };
656
- const ROW_HEIGHT = 20;
657
- const ITEM_GAP = 16;
658
- const SWATCH = 8;
659
- const SWATCH_GAP = 4;
660
- const SIDE_PADDING = 4;
661
- // Approximate text width per character at 11px — good enough for centering.
662
- const charWidth = 6.5;
663
- const itemWidths = items.map(it => SWATCH + SWATCH_GAP + Math.max(it.label.length, 1) * charWidth);
664
-
665
- // Greedy line-break: pack items into rows so each row fits inside the
666
- // available width. Single-row legends (≤ a few short labels) still render
667
- // on one line — no visual change for the line/scatter/bar callers that
668
- // typically have only 2-4 series. Pie/donut with long "Label (XX%)" entries
669
- // and 5+ slices wrap to multiple rows instead of overflowing the viewBox.
670
- const availableWidth = Math.max(40, width - 2 * SIDE_PADDING);
671
- const rows = [];
672
- let cur = [];
673
- let curW = 0;
674
- items.forEach((item, i) => {
675
- const w = itemWidths[i];
676
- const projected = cur.length === 0 ? w : curW + ITEM_GAP + w;
677
- if (cur.length > 0 && projected > availableWidth) {
678
- rows.push({
679
- items: cur,
680
- widths: cur.map((_, j) => itemWidths[i - cur.length + j]),
681
- totalWidth: curW
682
- });
683
- cur = [item];
684
- curW = w;
685
- } else {
686
- cur = [...cur, item];
687
- curW = projected;
688
- }
689
- });
690
- if (cur.length > 0) {
691
- rows.push({
692
- items: cur,
693
- widths: cur.map((_, j) => itemWidths[items.length - cur.length + j]),
694
- totalWidth: curW
695
- });
696
- }
697
- const parts = [`<g class="stdlib-chart-legend">`];
698
- rows.forEach((row, rowIdx) => {
699
- let cursor = Math.max(SIDE_PADDING, (width - row.totalWidth) / 2);
700
- const baseY = yTop + ROW_HEIGHT / 2 + rowIdx * ROW_HEIGHT;
701
- row.items.forEach((item, i) => {
702
- parts.push(`<g class="stdlib-chart-legend-item stdlib-chart-series-${item.seriesIndex % 8}">`);
703
- parts.push(`<rect class="stdlib-chart-legend-swatch" x="${fmt(cursor)}" y="${fmt(baseY - SWATCH / 2)}" width="${SWATCH}" height="${SWATCH}" rx="1"/>`);
704
- parts.push(`<text class="stdlib-chart-legend-label" x="${fmt(cursor + SWATCH + SWATCH_GAP)}" y="${fmt(baseY)}" dominant-baseline="middle">${escapeXml(item.label)}</text>`);
705
- parts.push(`</g>`);
706
- cursor += row.widths[i] + ITEM_GAP;
707
- });
708
- });
709
- parts.push(`</g>`);
710
- return {
711
- svg: parts.join(""),
712
- height: rows.length * ROW_HEIGHT
713
- };
714
- };
715
-
716
- /** Measure the total height a legend with `items` will consume in `width`,
717
- * without actually rendering. Used by chart functions to reserve vertical
718
- * space before computing the plot area. */
719
- export const measureLegendHeight = (items, width) => {
720
- if (items.length === 0) return 0;
721
- const ROW_HEIGHT = 20;
722
- const ITEM_GAP = 16;
723
- const SWATCH = 8;
724
- const SWATCH_GAP = 4;
725
- const charWidth = 6.5;
726
- const availableWidth = Math.max(40, width - 8);
727
- let curW = 0;
728
- let rows = 1;
729
- items.forEach((it, i) => {
730
- const w = SWATCH + SWATCH_GAP + Math.max(it.label.length, 1) * charWidth;
731
- const projected = i === 0 ? w : curW + ITEM_GAP + w;
732
- if (i > 0 && projected > availableWidth) {
733
- rows++;
734
- curW = w;
735
- } else {
736
- curW = projected;
737
- }
738
- });
739
- return rows * ROW_HEIGHT;
740
- };
741
-
742
- /** Wrap chart body in a root `<svg>` with embedded default styles. */
743
- export const svgRoot = (opts, body) => {
744
- const cls = opts.className ? `stdlib-chart ${escapeXml(opts.className)}` : "stdlib-chart";
745
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${opts.width} ${opts.height}" class="${cls}"><style>${DEFAULT_STYLES}</style>${body}</svg>`;
746
- };
747
-
748
- // ==========================
749
- // GEOMETRY HELPERS
750
- // ==========================
751
-
752
- /** Format an SVG path `d` attribute for a polyline through `points`. */
753
- export const linePathD = points => {
754
- if (points.length === 0) return "";
755
- let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
756
- for (let i = 1; i < points.length; i++) {
757
- d += ` L ${fmt(points[i].x)} ${fmt(points[i].y)}`;
758
- }
759
- return d;
760
- };
761
-
762
- /**
763
- * Format an SVG path `d` for a smooth curve through `points` using cubic
764
- * Bezier segments with Catmull-Rom-derived vertical control points.
765
- *
766
- * Vertical control points use neighboring `points[i-1]` and `points[i+2]`
767
- * (reflecting the end points at boundaries) with the standard Catmull-Rom
768
- * tension factor of 1/6. Horizontal control points stay at the segment's
769
- * thirds, so x progresses linearly and never doubles back when point spacing
770
- * is uneven.
771
- */
772
- export const smoothPathD = points => {
773
- const n = points.length;
774
- if (n === 0) return "";
775
- if (n === 1) return `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
776
- if (n === 2) return linePathD(points);
777
- let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
778
- for (let i = 0; i < n - 1; i++) {
779
- const p0 = i > 0 ? points[i - 1] : points[i];
780
- const p1 = points[i];
781
- const p2 = points[i + 1];
782
- const p3 = i + 2 < n ? points[i + 2] : points[i + 1];
783
- const dx = p2.x - p1.x;
784
- const cp1x = p1.x + dx / 3;
785
- const cp1y = p1.y + (p2.y - p0.y) / 6;
786
- const cp2x = p2.x - dx / 3;
787
- const cp2y = p2.y - (p3.y - p1.y) / 6;
788
- d += ` C ${fmt(cp1x)} ${fmt(cp1y)} ${fmt(cp2x)} ${fmt(cp2y)} ${fmt(p2.x)} ${fmt(p2.y)}`;
789
- }
790
- return d;
791
- };
792
-
793
- /**
794
- * Build an SVG path `d` attribute for a pie slice (or donut sector).
795
- *
796
- * Angles are in radians, measured from the +X axis. Slices grow clockwise,
797
- * which in SVG's y-down coordinate space means `a1 > a0` produces a clockwise
798
- * arc when drawn with the large-arc and sweep flags set appropriately.
799
- *
800
- * Full-circle (a1 - a0 ≈ 2π) is split into two 180° arcs because a single
801
- * `A` command can't draw a complete circle unambiguously.
802
- */
803
- export const arcPathD = (cx, cy, r, a0, a1, innerR = 0) => {
804
- const sweep = a1 - a0;
805
- // Full circle: split into two halves to avoid degenerate `A` command.
806
- if (sweep >= Math.PI * 2 - 1e-9) {
807
- const aMid = a0 + Math.PI;
808
- if (innerR <= 0) {
809
- const ox0 = cx + r * Math.cos(a0),
810
- oy0 = cy + r * Math.sin(a0);
811
- const oxM = cx + r * Math.cos(aMid),
812
- oyM = cy + r * Math.sin(aMid);
813
- return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(oxM)} ${fmt(oyM)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(ox0)} ${fmt(oy0)} Z`;
814
- }
815
- const ox0 = cx + r * Math.cos(a0),
816
- oy0 = cy + r * Math.sin(a0);
817
- const oxM = cx + r * Math.cos(aMid),
818
- oyM = cy + r * Math.sin(aMid);
819
- const ix0 = cx + innerR * Math.cos(a0),
820
- iy0 = cy + innerR * Math.sin(a0);
821
- const ixM = cx + innerR * Math.cos(aMid),
822
- iyM = cy + innerR * Math.sin(aMid);
823
- // Outer ring CW, inner ring CCW (using even-odd fill rule via SVG default).
824
- return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(oxM)} ${fmt(oyM)} A ${fmt(r)} ${fmt(r)} 0 0 1 ${fmt(ox0)} ${fmt(oy0)} Z` + ` M ${fmt(ix0)} ${fmt(iy0)} A ${fmt(innerR)} ${fmt(innerR)} 0 0 0 ${fmt(ixM)} ${fmt(iyM)} A ${fmt(innerR)} ${fmt(innerR)} 0 0 0 ${fmt(ix0)} ${fmt(iy0)} Z`;
825
- }
826
- const large = sweep > Math.PI ? 1 : 0;
827
- const ox0 = cx + r * Math.cos(a0),
828
- oy0 = cy + r * Math.sin(a0);
829
- const ox1 = cx + r * Math.cos(a1),
830
- oy1 = cy + r * Math.sin(a1);
831
- if (innerR <= 0) {
832
- return `M ${fmt(cx)} ${fmt(cy)} L ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 ${large} 1 ${fmt(ox1)} ${fmt(oy1)} Z`;
833
- }
834
- const ix0 = cx + innerR * Math.cos(a0),
835
- iy0 = cy + innerR * Math.sin(a0);
836
- const ix1 = cx + innerR * Math.cos(a1),
837
- iy1 = cy + innerR * Math.sin(a1);
838
- return `M ${fmt(ox0)} ${fmt(oy0)} A ${fmt(r)} ${fmt(r)} 0 ${large} 1 ${fmt(ox1)} ${fmt(oy1)} L ${fmt(ix1)} ${fmt(iy1)} A ${fmt(innerR)} ${fmt(innerR)} 0 ${large} 0 ${fmt(ix0)} ${fmt(iy0)} Z`;
839
- };
840
-
841
- /**
842
- * SVG path `d` for a marker shape centered at `(cx, cy)` with circumradius `r`.
843
- *
844
- * The shapes are sized so a typical visual radius matches `r`:
845
- * - circle: full radius
846
- * - square: side = sqrt(2)·r so the diagonal equals 2·r (visually balanced
847
- * next to a circle of the same r)
848
- * - triangle: equilateral pointing up, circumradius r
849
- * - diamond: square rotated 45°, half-diagonal = r
850
- * - plus: cross-shape at thickness r·0.5
851
- * - cross: X-shape at thickness r·0.4
852
- */
853
- export const markerPath = (shape, cx, cy, r) => {
854
- switch (shape) {
855
- case "circle":
856
- // Single arc command pair to draw a closed circle.
857
- return `M ${fmt(cx - r)} ${fmt(cy)} A ${fmt(r)} ${fmt(r)} 0 1 0 ${fmt(cx + r)} ${fmt(cy)} A ${fmt(r)} ${fmt(r)} 0 1 0 ${fmt(cx - r)} ${fmt(cy)} Z`;
858
- case "square":
859
- {
860
- const s = r * Math.SQRT2 / 2; // half-side
861
- return `M ${fmt(cx - s)} ${fmt(cy - s)} L ${fmt(cx + s)} ${fmt(cy - s)} L ${fmt(cx + s)} ${fmt(cy + s)} L ${fmt(cx - s)} ${fmt(cy + s)} Z`;
862
- }
863
- case "triangle":
864
- {
865
- // Equilateral pointing up. Circumradius r.
866
- const h = r * Math.sin(Math.PI / 3) * 1.5; // altitude from base to apex
867
- return `M ${fmt(cx)} ${fmt(cy - r)} L ${fmt(cx + h * Math.cos(Math.PI / 6))} ${fmt(cy + r * 0.5)} L ${fmt(cx - h * Math.cos(Math.PI / 6))} ${fmt(cy + r * 0.5)} Z`;
868
- }
869
- case "diamond":
870
- return `M ${fmt(cx)} ${fmt(cy - r)} L ${fmt(cx + r)} ${fmt(cy)} L ${fmt(cx)} ${fmt(cy + r)} L ${fmt(cx - r)} ${fmt(cy)} Z`;
871
- case "plus":
872
- {
873
- const t = r * 0.32; // half-thickness
874
- return `M ${fmt(cx - r)} ${fmt(cy - t)} L ${fmt(cx - t)} ${fmt(cy - t)} L ${fmt(cx - t)} ${fmt(cy - r)} L ${fmt(cx + t)} ${fmt(cy - r)} L ${fmt(cx + t)} ${fmt(cy - t)} L ${fmt(cx + r)} ${fmt(cy - t)} L ${fmt(cx + r)} ${fmt(cy + t)} L ${fmt(cx + t)} ${fmt(cy + t)} L ${fmt(cx + t)} ${fmt(cy + r)} L ${fmt(cx - t)} ${fmt(cy + r)} L ${fmt(cx - t)} ${fmt(cy + t)} L ${fmt(cx - r)} ${fmt(cy + t)} Z`;
875
- }
876
- case "cross":
877
- {
878
- // X shape — same as plus rotated 45°. Build by composing two oriented bars.
879
- const a = r * 0.7;
880
- const t = r * 0.28;
881
- return `M ${fmt(cx - a + t)} ${fmt(cy - a - t)} L ${fmt(cx - a - t)} ${fmt(cy - a + t)} L ${fmt(cx + a - t)} ${fmt(cy + a + t)} L ${fmt(cx + a + t)} ${fmt(cy + a - t)} Z` + ` M ${fmt(cx + a - t)} ${fmt(cy - a - t)} L ${fmt(cx + a + t)} ${fmt(cy - a + t)} L ${fmt(cx - a + t)} ${fmt(cy + a + t)} L ${fmt(cx - a - t)} ${fmt(cy + a - t)} Z`;
882
- }
883
- }
884
- };
885
-
886
- /**
887
- * SVG path `d` for a step (stair) line. `mode` controls where the vertical
888
- * step happens relative to the data points:
889
- * - `before` — vertical step at the new x BEFORE the value updates (state
890
- * machine "Mealy" style: change at input)
891
- * - `after` — value updates at the data point's x and persists until next x
892
- * - `middle` — vertical step at the midpoint between consecutive x-values
893
- */
894
- export const stepPathD = (points, mode) => {
895
- if (points.length === 0) return "";
896
- if (points.length === 1) return `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
897
- let d = `M ${fmt(points[0].x)} ${fmt(points[0].y)}`;
898
- for (let i = 1; i < points.length; i++) {
899
- const p = points[i];
900
- const prev = points[i - 1];
901
- if (mode === "before") {
902
- // step at next-x: extend horizontally to new x at OLD y, then jump to new y.
903
- d += ` L ${fmt(p.x)} ${fmt(prev.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
904
- } else if (mode === "after") {
905
- // step at current-x: jump to new y immediately, persist until next x.
906
- d += ` L ${fmt(prev.x)} ${fmt(p.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
907
- } else {
908
- // middle: step at midpoint of x.
909
- const mx = (prev.x + p.x) / 2;
910
- d += ` L ${fmt(mx)} ${fmt(prev.y)} L ${fmt(mx)} ${fmt(p.y)} L ${fmt(p.x)} ${fmt(p.y)}`;
911
- }
912
- }
913
- return d;
914
- };
915
-
916
- /** Format a number for SVG attributes — short, no scientific notation. */
917
- export const fmt = n => {
918
- if (!Number.isFinite(n)) return "0";
919
- // 2 decimals is enough for sub-pixel precision at typical sizes.
920
- const rounded = Math.round(n * 100) / 100;
921
- return Number.isInteger(rounded) ? `${rounded}` : `${rounded}`;
922
- };
923
- export const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
924
- const normalizeMinMax = (min, max) => {
925
- const lo = Number.isFinite(min) ? min : 0;
926
- const hi = Number.isFinite(max) ? max : 100;
927
- return lo === hi ? [lo, lo + 1] : lo < hi ? [lo, hi] : [hi, lo];
928
- };
929
- const formatNumberValue = (value, format, unit = "") => {
930
- if (!Number.isFinite(value)) return "";
931
- return `${format ? format(value) : fmt(value)}${unit}`;
932
- };
933
- const thresholdFillAttr = color => color ? ` fill="${escapeXml(color)}"` : "";
934
- const thresholdStrokeAttr = color => color ? ` stroke="${escapeXml(color)}"` : "";
935
- const polarPoint = (cx, cy, r, angleRad) => ({
936
- x: cx + r * Math.cos(angleRad),
937
- y: cy + r * Math.sin(angleRad)
938
- });
939
- const arcLinePathD = (cx, cy, r, a0, a1) => {
940
- const start = polarPoint(cx, cy, r, a0);
941
- const end = polarPoint(cx, cy, r, a1);
942
- const large = Math.abs(a1 - a0) > Math.PI ? 1 : 0;
943
- const sweep = a1 >= a0 ? 1 : 0;
944
- return `M ${fmt(start.x)} ${fmt(start.y)} A ${fmt(r)} ${fmt(r)} 0 ${large} ${sweep} ${fmt(end.x)} ${fmt(end.y)}`;
945
- };
946
- const parseHexColor = color => {
947
- const short = /^#([0-9a-f]{3})$/i.exec(color);
948
- if (short) {
949
- const [r, g, b] = short[1].split("").map(c => Number.parseInt(c + c, 16));
950
- return {
951
- r: r,
952
- g: g,
953
- b: b
954
- };
955
- }
956
- const long = /^#([0-9a-f]{6})$/i.exec(color);
957
- if (!long) return null;
958
- const value = long[1];
959
- return {
960
- r: Number.parseInt(value.slice(0, 2), 16),
961
- g: Number.parseInt(value.slice(2, 4), 16),
962
- b: Number.parseInt(value.slice(4, 6), 16)
963
- };
964
- };
965
- const hexColor = color => `#${[color.r, color.g, color.b].map(value => clamp(Math.round(value), 0, 255).toString(16).padStart(2, "0")).join("")}`;
966
- const interpolateColor = (from, to, t) => {
967
- const a = parseHexColor(from);
968
- const b = parseHexColor(to);
969
- if (!a || !b) return t < 0.5 ? from : to;
970
- return hexColor({
971
- r: a.r + (b.r - a.r) * t,
972
- g: a.g + (b.g - a.g) * t,
973
- b: a.b + (b.b - a.b) * t
974
- });
975
- };
976
- const gaugeThresholdStops = (thresholds, min, max) => {
977
- if (!thresholds || thresholds.length === 0) return [];
978
- const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
979
- if (sorted.length === 0) return [];
980
- const colorFor = (threshold, index) => threshold.color ?? `var(--stdlib-chart-c${index % 8 + 1})`;
981
- return [{
982
- value: min,
983
- color: colorFor(sorted[0], 0)
984
- }, ...sorted.map((threshold, index) => ({
985
- value: clamp(threshold.value, min, max),
986
- color: colorFor(threshold, index)
987
- }))];
988
- };
989
- const gaugeColorAt = (stops, value) => {
990
- if (stops.length === 0) return "currentColor";
991
- for (let i = 1; i < stops.length; i++) {
992
- const prev = stops[i - 1];
993
- const next = stops[i];
994
- if (value <= next.value) {
995
- const t = next.value === prev.value ? 1 : clamp((value - prev.value) / (next.value - prev.value), 0, 1);
996
- return interpolateColor(prev.color, next.color, t);
997
- }
998
- }
999
- return stops[stops.length - 1].color;
1000
- };
1001
- const renderGaugeGradientSegments = opts => {
1002
- if (opts.stops.length === 0) return "";
1003
- const segments = 72;
1004
- const maxProgress = opts.progress ?? 100;
1005
- const parts = [];
1006
- for (let i = 0; i < segments; i++) {
1007
- const p0 = i / segments * 100;
1008
- const p1 = Math.min((i + 1) / segments * 100, maxProgress);
1009
- if (p0 >= maxProgress || p1 <= p0) break;
1010
- const v0 = mapRange(p0, [0, 100], [opts.min, opts.max]);
1011
- const v1 = mapRange(p1, [0, 100], [opts.min, opts.max]);
1012
- const color = gaugeColorAt(opts.stops, (v0 + v1) / 2);
1013
- const a0 = mapRange(p0, [0, 100], [opts.startAngle, opts.endAngle]);
1014
- const a1 = mapRange(p1, [0, 100], [opts.startAngle, opts.endAngle]);
1015
- parts.push(`<path class="${opts.className}" stroke="${escapeXml(color)}" d="${arcLinePathD(opts.cx, opts.cy, opts.radius, a0, a1)}"/>`);
1016
- }
1017
- return parts.join("");
1018
- };
1019
-
1020
- // ==========================
1021
- // AXIS RENDERERS
1022
- // ==========================
1023
-
1024
- const pickMapper = scale => scale === "log" ? mapLog : mapRange;
1025
-
1026
- /**
1027
- * Whether a value is renderable on the given axis. Log axes reject zero and
1028
- * negative values (since `log(<=0)` is undefined). Used to filter data
1029
- * points before rendering so we don't emit huge off-plot SVG coordinates.
1030
- */
1031
- const isOnAxis = (axis, v) => Number.isFinite(v) && (axis.scale !== "log" || v > 0);
1032
-
1033
- /**
1034
- * Compute the domain, major ticks, and (optional) minor ticks for an axis,
1035
- * choosing linear or log scale per `axisOpts`. Filters non-positive values
1036
- * out under log scale and falls back to `[1, 10]` if none remain.
1037
- */
1038
- const computeAxisScale = (values, axisOpts, fallbackTicks = DEFAULT_TICKS) => {
1039
- const scale = axisOpts?.scale === "log" ? "log" : "linear";
1040
- if (axisOpts?.domain) {
1041
- const [lo, hi] = axisOpts.domain;
1042
- if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo >= hi || !Number.isFinite(hi - lo) || scale === "log" && lo <= 0) {
1043
- throw new RangeError("Chart axis domain must have finite increasing bounds (positive for log scales)");
1044
- }
1045
- if (values.some(v => Number.isFinite(v) && (scale !== "log" || v > 0) && (v < lo || v > hi))) {
1046
- throw new RangeError("Chart axis domain must contain all plotted values and bounds");
1047
- }
1048
- const ticks = [];
1049
- if (scale === "log") {
1050
- for (let exponent = Math.floor(Math.log10(lo)); exponent <= Math.ceil(Math.log10(hi)); exponent++) {
1051
- const value = 10 ** exponent;
1052
- if (value > lo && value < hi) ticks.push(value);
1053
- }
1054
- } else {
1055
- const step = niceStep(hi - lo, axisOpts.ticks ?? fallbackTicks);
1056
- // At extreme magnitudes the step may be smaller than one representable
1057
- // increment. Keep endpoint ticks instead of entering a non-advancing loop.
1058
- if (step > 0 && Number.isFinite(step) && (hi - lo) / step <= MAX_AXIS_TICKS) {
1059
- for (let value = Math.ceil(lo / step) * step; value < hi;) {
1060
- if (value > lo && (!axisOpts.insetEndpointLabels || value - lo >= step && hi - value >= step)) ticks.push(value);
1061
- const next = value + step;
1062
- if (next <= value) break;
1063
- value = next;
1064
- }
1065
- }
1066
- }
1067
- return {
1068
- domain: [lo, hi],
1069
- ticks: [...new Set([lo, ...ticks.filter(v => v > lo && v < hi), hi])],
1070
- minorTicks: [],
1071
- scale
1072
- };
1073
- }
1074
- if (scale === "log") {
1075
- const positive = values.filter(v => Number.isFinite(v) && v > 0);
1076
- if (positive.length === 0) {
1077
- return {
1078
- domain: [1, 10],
1079
- ticks: [1, 10],
1080
- minorTicks: [],
1081
- scale
1082
- };
1083
- }
1084
- const min = Math.min(...positive);
1085
- const max = Math.max(...positive);
1086
- const r = niceLogTicks(min, max);
1087
- const minorTicks = [];
1088
- if (axisOpts?.minorTicks) {
1089
- for (let i = 0; i < r.ticks.length - 1; i++) {
1090
- const decade = r.ticks[i];
1091
- for (let m = 2; m <= 9; m++) minorTicks.push(decade * m);
1092
- }
1093
- }
1094
- return {
1095
- domain: r.domain,
1096
- ticks: r.ticks,
1097
- minorTicks,
1098
- scale
1099
- };
1100
- }
1101
- const [minRaw, maxRaw] = computeDomain(values);
1102
- const step = niceStep(maxRaw - minRaw, axisOpts?.ticks ?? fallbackTicks);
1103
- const r = extendDomainToNice(minRaw, maxRaw, step);
1104
- const minorTicks = [];
1105
- if (axisOpts?.minorTicks && r.ticks.length > 1) {
1106
- const SUBDIVISIONS = 5;
1107
- for (let i = 0; i < r.ticks.length - 1; i++) {
1108
- const a = r.ticks[i];
1109
- const b = r.ticks[i + 1];
1110
- const sub = (b - a) / SUBDIVISIONS;
1111
- for (let m = 1; m < SUBDIVISIONS; m++) minorTicks.push(a + sub * m);
1112
- }
1113
- }
1114
- return {
1115
- domain: r.domain,
1116
- ticks: r.ticks,
1117
- minorTicks,
1118
- scale
1119
- };
1120
- };
1121
- const renderYAxis = (axis, area, opts) => {
1122
- const format = opts?.format ?? (v => String(v));
1123
- const map = pickMapper(axis.scale);
1124
- const parts = [];
1125
- for (const t of axis.ticks) {
1126
- const y = map(t, axis.domain, [area.y1, area.y0]);
1127
- parts.push(`<line class="stdlib-chart-grid" x1="${fmt(area.x0)}" y1="${fmt(y)}" x2="${fmt(area.x1)}" y2="${fmt(y)}"/>`);
1128
- parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(area.x0 - 6)}" y="${fmt(y + 3)}" text-anchor="end">${escapeXml(format(t))}</text>`);
1129
- }
1130
- for (const mt of axis.minorTicks) {
1131
- const y = map(mt, axis.domain, [area.y1, area.y0]);
1132
- parts.push(`<line class="stdlib-chart-minor-tick" x1="${fmt(area.x0 - 3)}" y1="${fmt(y)}" x2="${fmt(area.x0)}" y2="${fmt(y)}"/>`);
1133
- }
1134
- parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y0)}" x2="${fmt(area.x0)}" y2="${fmt(area.y1)}"/>`);
1135
- if (opts?.label) {
1136
- const cx = 12;
1137
- const cy = (area.y0 + area.y1) / 2;
1138
- parts.push(`<text class="stdlib-chart-axis-label" x="${fmt(cx)}" y="${fmt(cy)}" text-anchor="middle" transform="rotate(-90 ${fmt(cx)} ${fmt(cy)})">${escapeXml(opts.label)}</text>`);
1139
- }
1140
- return parts.join("");
1141
- };
1142
- const renderXAxisNumeric = (axis, area, height, opts) => {
1143
- const format = opts?.format ?? (v => String(v));
1144
- const map = pickMapper(axis.scale);
1145
- const parts = [];
1146
- for (const t of axis.ticks) {
1147
- const x = map(t, axis.domain, [area.x0, area.x1]);
1148
- const anchor = opts?.domain && opts.insetEndpointLabels ? t === axis.domain[0] ? "start" : t === axis.domain[1] ? "end" : "middle" : "middle";
1149
- parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(x)}" y="${fmt(area.y1 + 14)}" text-anchor="${anchor}">${escapeXml(format(t))}</text>`);
1150
- }
1151
- for (const mt of axis.minorTicks) {
1152
- const x = map(mt, axis.domain, [area.x0, area.x1]);
1153
- parts.push(`<line class="stdlib-chart-minor-tick" x1="${fmt(x)}" y1="${fmt(area.y1)}" x2="${fmt(x)}" y2="${fmt(area.y1 + 3)}"/>`);
1154
- }
1155
- parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y1)}" x2="${fmt(area.x1)}" y2="${fmt(area.y1)}"/>`);
1156
- if (opts?.label) {
1157
- parts.push(`<text class="stdlib-chart-axis-label" x="${fmt((area.x0 + area.x1) / 2)}" y="${fmt(height - 4)}" text-anchor="middle">${escapeXml(opts.label)}</text>`);
1158
- }
1159
- return parts.join("");
1160
- };
1161
- const renderXAxisCategorical = (labels, area, height, axisLabel) => {
1162
- const parts = [];
1163
- if (labels.length > 0) {
1164
- const step = (area.x1 - area.x0) / labels.length;
1165
- for (let i = 0; i < labels.length; i++) {
1166
- const cx = area.x0 + step * (i + 0.5);
1167
- parts.push(`<text class="stdlib-chart-tick-label" x="${fmt(cx)}" y="${fmt(area.y1 + 14)}" text-anchor="middle">${escapeXml(labels[i])}</text>`);
1168
- }
1169
- }
1170
- parts.push(`<line class="stdlib-chart-axis" x1="${fmt(area.x0)}" y1="${fmt(area.y1)}" x2="${fmt(area.x1)}" y2="${fmt(area.y1)}"/>`);
1171
- if (axisLabel) {
1172
- parts.push(`<text class="stdlib-chart-axis-label" x="${fmt((area.x0 + area.x1) / 2)}" y="${fmt(height - 4)}" text-anchor="middle">${escapeXml(axisLabel)}</text>`);
1173
- }
1174
- return parts.join("");
1175
- };
1176
- const emptyChart = (width, height, className, message = "no data") => svgRoot({
1177
- width,
1178
- height,
1179
- className
1180
- }, `<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle" dominant-baseline="middle">${escapeXml(message)}</text>`);
1181
-
1182
- // ==========================
1183
- // CHART FUNCTIONS
1184
- // ==========================
1185
-
1186
- /**
1187
- * Render a scatter plot. Each series produces a group of circles, one per
1188
- * data point, classed `stdlib-chart-series-N` so series colors stay
1189
- * consistent across charts.
1190
- *
1191
- * Non-finite x or y values are filtered out. An empty `series` (or one with
1192
- * no finite points) renders an empty-state SVG with a "no data" label.
1193
- *
1194
- * @example
1195
- * charts.scatter({ series: [{ data: [{x:1,y:2},{x:2,y:5},{x:3,y:3}] }] });
1196
- *
1197
- * @example
1198
- * charts.scatter({
1199
- * series: [
1200
- * { label: "Group A", data: [...] },
1201
- * { label: "Group B", data: [...] },
1202
- * ],
1203
- * xAxis: { label: "Time (s)" },
1204
- * yAxis: { label: "Value", format: v => `${v}k` },
1205
- * });
1206
- */
1207
- export const scatter = opts => {
1208
- const width = opts.width ?? DEFAULT_WIDTH;
1209
- const height = opts.height ?? DEFAULT_HEIGHT;
1210
- const padding = normalizePadding(opts.padding);
1211
- const header = renderHeader(width, opts.title, opts.subtitle);
1212
- const legendItems = collectSeriesLegend(opts);
1213
- const legendHeight = legendItems.length > 0 ? 20 : 0;
1214
- const finitePoints = opts.series.flatMap(s => s.data).filter(p => Number.isFinite(p.x) && Number.isFinite(p.y));
1215
- if (finitePoints.length === 0) return emptyChart(width, height, opts.className);
1216
- const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, !!opts.yAxis?.label, header.height, legendHeight);
1217
- const xAxis = computeAxisScale(collectAxisValues(opts.series, "x"), opts.xAxis);
1218
- const yAxis = computeAxisScale(collectAxisValues(opts.series, "y"), opts.yAxis);
1219
- const xMap = pickMapper(xAxis.scale);
1220
- const yMap = pickMapper(yAxis.scale);
1221
-
1222
- // Size dimension: if any point has a finite `size`, normalize across all
1223
- // points to the configured pixel range; points without size fall back to
1224
- // the midpoint so they remain visible.
1225
- const sizes = finitePoints.map(p => p.size).filter(s => typeof s === "number" && Number.isFinite(s));
1226
- const sizeRange = opts.sizeRange ?? [3, 12];
1227
- const useSizes = sizes.length > 0;
1228
- const sizeDomain = useSizes ? computeDomain(sizes) : [0, 1];
1229
- const fallbackR = (sizeRange[0] + sizeRange[1]) / 2;
1230
- const body = [];
1231
- body.push(renderYAxis(yAxis, area, opts.yAxis));
1232
- body.push(renderXAxisNumeric(xAxis, area, height - legendHeight, opts.xAxis));
1233
-
1234
- // Error bars render under the points so the points sit on top of the bar
1235
- // intersections — easier to read.
1236
- body.push(renderErrorBars(opts.series, xAxis, yAxis, area));
1237
- opts.series.forEach((s, i) => {
1238
- const cls = `stdlib-chart-series-${i % 8}`;
1239
- const shape = s.marker ?? (opts.autoVariant ? DEFAULT_MARKERS[i % DEFAULT_MARKERS.length] : "circle");
1240
- const elements = s.data.map((p, index) => ({
1241
- p,
1242
- index
1243
- })).filter(({
1244
- p
1245
- }) => isOnAxis(xAxis, p.x) && isOnAxis(yAxis, p.y)).map(({
1246
- p,
1247
- index
1248
- }) => {
1249
- const cx = xMap(p.x, xAxis.domain, [area.x0, area.x1]);
1250
- const cy = yMap(p.y, yAxis.domain, [area.y1, area.y0]);
1251
- const r = useSizes ? typeof p.size === "number" && Number.isFinite(p.size) ? mapRange(p.size, sizeDomain, sizeRange) : fallbackR : 3;
1252
- const datum = {
1253
- index,
1254
- seriesIndex: i,
1255
- role: "point",
1256
- label: s.label,
1257
- anchor: [cx, cy],
1258
- values: pointValues(p, opts.xAxis, opts.yAxis)
1259
- };
1260
- if (shape === "circle") {
1261
- return chartDatumSvg(`<circle class="stdlib-chart-point" cx="${fmt(cx)}" cy="${fmt(cy)}" r="${fmt(r)}"/>`, datum, opts.inspect);
1262
- }
1263
- return chartDatumSvg(`<path class="stdlib-chart-point" d="${markerPath(shape, cx, cy, r)}"/>`, datum, opts.inspect);
1264
- }).join("");
1265
- if (elements) body.push(`<g class="${cls}">${elements}</g>`);
1266
- });
1267
-
1268
- // Optional trend line (across all series). Renders after data so it's visible.
1269
- if (opts.trendline) {
1270
- const reg = linearRegression(finitePoints);
1271
- if (reg !== null) {
1272
- const x0 = xAxis.domain[0];
1273
- const x1 = xAxis.domain[1];
1274
- const y0 = reg.slope * x0 + reg.intercept;
1275
- const y1 = reg.slope * x1 + reg.intercept;
1276
- // Clip to plot area in pixel space (visible portion of the regression).
1277
- const px0 = xMap(x0, xAxis.domain, [area.x0, area.x1]);
1278
- const px1 = xMap(x1, xAxis.domain, [area.x0, area.x1]);
1279
- const py0 = yMap(y0, yAxis.domain, [area.y1, area.y0]);
1280
- const py1 = yMap(y1, yAxis.domain, [area.y1, area.y0]);
1281
- body.push(`<line class="stdlib-chart-trendline" x1="${fmt(px0)}" y1="${fmt(py0)}" x2="${fmt(px1)}" y2="${fmt(py1)}"/>`);
1282
- }
1283
- }
1284
-
1285
- // References render AFTER data so labels stay on top (z-order matters in SVG).
1286
- if (opts.references && opts.references.length > 0) {
1287
- body.push(renderReferenceLines(opts.references, xAxis, yAxis, area));
1288
- }
1289
- const legend = renderLegend(legendItems, width, height - legendHeight);
1290
- return svgRoot({
1291
- width,
1292
- height,
1293
- className: opts.className
1294
- }, header.svg + body.join("") + legend.svg);
1295
- };
1296
- const collectSeriesLegend = opts => {
1297
- if (!opts.legend) return [];
1298
- return opts.series.map((s, i) => ({
1299
- label: s.label && s.label.length > 0 ? s.label : `Series ${i + 1}`,
1300
- seriesIndex: i
1301
- }));
1302
- };
1
+ import { arcPathD, chartDatumSvg, clamp, collectAxisValues, collectSeriesLegend, computeAxisScale, computeDomain, computePlotArea, DEFAULT_HEIGHT, DEFAULT_LINE_STYLES, DEFAULT_WIDTH, emptyChart, escapeXml, extendDomainToNice, fmt, formatNumberValue, inspectionPoint, isOnAxis, itemColorIndex, LINE_DASH_PATTERNS, linePathD, mapRange, measureLegendHeight, niceStep, normalizePadding, pickMapper, pointValues, renderErrorBars, renderHeader, renderLegend, renderReferenceLines, renderXAxisCategorical, renderXAxisNumeric, renderYAxis, resolveErrorY, smoothPathD, stepPathD, svgRoot, thresholdFillAttr } from "./svg-common";
2
+ export { barGauge } from "./svg-barGauge";
3
+ export { boxplot } from "./svg-boxplot";
4
+ export * from "./svg-common";
5
+ export { gauge } from "./svg-gauge";
6
+ export { heatmap } from "./svg-heatmap";
7
+ export { histogram } from "./svg-histogram";
8
+ // Preserve the portable exports while allowing bundlers to load each renderer independently.
9
+ export { scatter } from "./svg-scatter";
1303
10
 
1304
11
  /**
1305
12
  * Render a line chart. Each series becomes a `<path class="stdlib-chart-line">`
@@ -1421,10 +128,6 @@ export const line = opts => {
1421
128
  }, header.svg + body.join("") + legend.svg);
1422
129
  };
1423
130
 
1424
- // ==========================
1425
- // BAR
1426
- // ==========================
1427
-
1428
131
  /**
1429
132
  * Render a categorical bar chart. The y-domain always includes zero so bars
1430
133
  * rest on a visible baseline. Negative values produce bars below the zero
@@ -1530,11 +233,6 @@ export const bar = opts => {
1530
233
  className: opts.className
1531
234
  }, header.svg + body.join("") + legend.svg);
1532
235
  };
1533
-
1534
- // ==========================
1535
- // PIE / DONUT
1536
- // ==========================
1537
-
1538
236
  const renderPie = (opts, defaultInnerRadius) => {
1539
237
  const width = opts.width ?? DEFAULT_WIDTH;
1540
238
  const height = opts.height ?? DEFAULT_HEIGHT;
@@ -1649,390 +347,6 @@ export const pie = opts => renderPie(opts, 0);
1649
347
  * charts.donut({ data: [...], legend: true }); // wrapping legend below the ring
1650
348
  */
1651
349
  export const donut = opts => renderPie(opts, 0.6);
1652
-
1653
- // ==========================
1654
- // HISTOGRAM
1655
- // ==========================
1656
-
1657
- /**
1658
- * Render a histogram (frequency distribution) of the given observations.
1659
- * Uses Sturges' formula by default for bin count, or accepts an explicit
1660
- * count or list of bin edges.
1661
- *
1662
- * Bars are adjacent (no inter-bar gap) since a histogram represents a
1663
- * continuous distribution. The x-axis is numeric (bin edges as ticks).
1664
- *
1665
- * @example
1666
- * charts.histogram({ data: observations, title: "Reaction times (ms)" });
1667
- *
1668
- * @example
1669
- * charts.histogram({ data: scores, bins: 20, yAxis: { label: "Count" } });
1670
- */
1671
- export const histogram = opts => {
1672
- const width = opts.width ?? DEFAULT_WIDTH;
1673
- const height = opts.height ?? DEFAULT_HEIGHT;
1674
- const padding = normalizePadding(opts.padding);
1675
- const header = renderHeader(width, opts.title, opts.subtitle);
1676
- const finite = opts.data.filter(v => Number.isFinite(v));
1677
- if (finite.length === 0) return emptyChart(width, height, opts.className);
1678
- const {
1679
- edges,
1680
- counts
1681
- } = autoBin(finite, opts.bins);
1682
- const area = computePlotArea(width, height, padding, !!opts.xAxis?.label, !!opts.yAxis?.label, header.height, 0);
1683
- const xAxis = computeAxisScale(edges, opts.xAxis);
1684
- const yAxis = computeAxisScale([0, ...counts], opts.yAxis);
1685
- const xMap = pickMapper(xAxis.scale);
1686
- const yMap = pickMapper(yAxis.scale);
1687
- const body = [];
1688
- body.push(renderYAxis(yAxis, area, opts.yAxis));
1689
- body.push(renderXAxisNumeric(xAxis, area, height, opts.xAxis));
1690
- const zeroPx = yAxis.scale === "log" ? area.y1 : yMap(0, yAxis.domain, [area.y1, area.y0]);
1691
- for (let i = 0; i < counts.length; i++) {
1692
- const left = xMap(edges[i], xAxis.domain, [area.x0, area.x1]);
1693
- const right = xMap(edges[i + 1], xAxis.domain, [area.x0, area.x1]);
1694
- const c = counts[i];
1695
- if (yAxis.scale === "log" && c <= 0) continue;
1696
- const top = yMap(c, yAxis.domain, [area.y1, area.y0]);
1697
- body.push(chartDatumSvg(`<rect class="stdlib-chart-bar stdlib-chart-series-0" x="${fmt(left)}" y="${fmt(top)}" width="${fmt(right - left)}" height="${fmt(zeroPx - top)}"/>`, {
1698
- index: i,
1699
- role: "bin",
1700
- anchor: [(left + right) / 2, (top + zeroPx) / 2],
1701
- values: [{
1702
- key: "from",
1703
- value: edges[i],
1704
- formatted: opts.xAxis?.format?.(edges[i])
1705
- }, {
1706
- key: "to",
1707
- value: edges[i + 1],
1708
- formatted: opts.xAxis?.format?.(edges[i + 1])
1709
- }, {
1710
- key: "upperInclusive",
1711
- value: i === counts.length - 1 ? "true" : "false"
1712
- }, {
1713
- key: "count",
1714
- value: c
1715
- }]
1716
- }, opts.inspect));
1717
- }
1718
- if (opts.references && opts.references.length > 0) {
1719
- body.push(renderReferenceLines(opts.references, xAxis, yAxis, area));
1720
- }
1721
- return svgRoot({
1722
- width,
1723
- height,
1724
- className: opts.className
1725
- }, header.svg + body.join(""));
1726
- };
1727
-
1728
- // ==========================
1729
- // BOX PLOT
1730
- // ==========================
1731
-
1732
- /**
1733
- * Render a box plot (Tukey style): box for the IQR (Q1-Q3), median line,
1734
- * whiskers extending to 1.5×IQR fences, and individual outlier dots.
1735
- *
1736
- * Useful for comparing distributions across categorical groups (e.g. test
1737
- * scores per class, reaction times per condition).
1738
- *
1739
- * @example
1740
- * charts.boxplot({
1741
- * groups: [
1742
- * { label: "Class A", values: scoresA },
1743
- * { label: "Class B", values: scoresB },
1744
- * ],
1745
- * yAxis: { label: "Score" },
1746
- * });
1747
- */
1748
- export const boxplot = opts => {
1749
- const width = opts.width ?? DEFAULT_WIDTH;
1750
- const height = opts.height ?? DEFAULT_HEIGHT;
1751
- const padding = normalizePadding(opts.padding);
1752
- const header = renderHeader(width, opts.title, opts.subtitle);
1753
- const showOutliers = opts.showOutliers ?? true;
1754
- const stats = opts.groups.map((g, index) => ({
1755
- index,
1756
- count: g.values.filter(Number.isFinite).length,
1757
- label: g.label,
1758
- s: computeBoxStats(g.values)
1759
- }));
1760
- const valid = stats.filter(g => g.s !== null);
1761
- if (valid.length === 0) return emptyChart(width, height, opts.className);
1762
- const area = computePlotArea(width, height, padding, false, !!opts.yAxis?.label, header.height, 0);
1763
-
1764
- // Collect all values relevant for the y-domain: whisker extremes + outliers.
1765
- const axisValues = [];
1766
- for (const g of valid) {
1767
- axisValues.push(g.s.whiskerLow, g.s.whiskerHigh);
1768
- if (showOutliers) axisValues.push(...g.s.outliers);
1769
- }
1770
- const yAxis = computeAxisScale(axisValues, opts.yAxis);
1771
- const yMap = pickMapper(yAxis.scale);
1772
- const body = [];
1773
- body.push(renderYAxis(yAxis, area, opts.yAxis));
1774
- body.push(renderXAxisCategorical(valid.map(g => g.label), area, height, undefined));
1775
- const slot = (area.x1 - area.x0) / valid.length;
1776
- const boxWidth = slot * 0.6;
1777
- const boxOffset = slot * 0.2;
1778
- for (let i = 0; i < valid.length; i++) {
1779
- const g = valid[i];
1780
- const cx = area.x0 + slot * i + slot / 2;
1781
- const x = area.x0 + slot * i + boxOffset;
1782
- const seriesIdx = opts.colorByBox ? i % 8 : 0;
1783
- const seriesCls = `stdlib-chart-series-${seriesIdx}`;
1784
- const yQ1 = yMap(g.s.q1, yAxis.domain, [area.y1, area.y0]);
1785
- const yQ2 = yMap(g.s.q2, yAxis.domain, [area.y1, area.y0]);
1786
- const yQ3 = yMap(g.s.q3, yAxis.domain, [area.y1, area.y0]);
1787
- const yWhiskerLow = yMap(g.s.whiskerLow, yAxis.domain, [area.y1, area.y0]);
1788
- const yWhiskerHigh = yMap(g.s.whiskerHigh, yAxis.domain, [area.y1, area.y0]);
1789
-
1790
- // Whisker line (vertical) from low whisker to high whisker, behind the box.
1791
- body.push(`<line class="stdlib-chart-box-whisker" x1="${fmt(cx)}" y1="${fmt(yWhiskerHigh)}" x2="${fmt(cx)}" y2="${fmt(yWhiskerLow)}"/>`);
1792
- // Whisker caps.
1793
- const capW = boxWidth * 0.4;
1794
- body.push(`<line class="stdlib-chart-box-cap" x1="${fmt(cx - capW / 2)}" y1="${fmt(yWhiskerHigh)}" x2="${fmt(cx + capW / 2)}" y2="${fmt(yWhiskerHigh)}"/>`);
1795
- body.push(`<line class="stdlib-chart-box-cap" x1="${fmt(cx - capW / 2)}" y1="${fmt(yWhiskerLow)}" x2="${fmt(cx + capW / 2)}" y2="${fmt(yWhiskerLow)}"/>`);
1796
- // Box (Q1 to Q3).
1797
- body.push(chartDatumSvg(`<rect class="stdlib-chart-box ${seriesCls}" x="${fmt(x)}" y="${fmt(yQ3)}" width="${fmt(boxWidth)}" height="${fmt(yQ1 - yQ3)}"/>`, {
1798
- index: g.index,
1799
- role: "box",
1800
- label: g.label,
1801
- anchor: [cx, yQ2],
1802
- values: [{
1803
- key: "count",
1804
- value: g.count
1805
- }, ...["q1", "q2", "q3", "whiskerLow", "whiskerHigh"].map(key => ({
1806
- key,
1807
- value: g.s[key]
1808
- })).map(field => ({
1809
- ...field,
1810
- formatted: opts.yAxis?.format?.(field.value)
1811
- }))]
1812
- }, opts.inspect));
1813
- // Median line.
1814
- body.push(`<line class="stdlib-chart-box-median" x1="${fmt(x)}" y1="${fmt(yQ2)}" x2="${fmt(x + boxWidth)}" y2="${fmt(yQ2)}"/>`);
1815
- // Outliers.
1816
- if (showOutliers) {
1817
- const sourceIndices = new Map();
1818
- if (opts.inspect) opts.groups[g.index].values.forEach((value, index) => {
1819
- const indices = sourceIndices.get(value) ?? [];
1820
- indices.push(index);
1821
- sourceIndices.set(value, indices);
1822
- });
1823
- for (const v of g.s.outliers) {
1824
- const sourceIndex = sourceIndices.get(v)?.shift() ?? 0;
1825
- const oy = yMap(v, yAxis.domain, [area.y1, area.y0]);
1826
- body.push(chartDatumSvg(`<circle class="stdlib-chart-box-outlier ${seriesCls}" cx="${fmt(cx)}" cy="${fmt(oy)}" r="2.5"/>`, {
1827
- index: sourceIndex,
1828
- seriesIndex: g.index,
1829
- role: "outlier",
1830
- label: g.label,
1831
- anchor: [cx, oy],
1832
- values: [{
1833
- key: "value",
1834
- value: v,
1835
- formatted: opts.yAxis?.format?.(v)
1836
- }]
1837
- }, opts.inspect));
1838
- }
1839
- }
1840
- }
1841
- if (opts.references && opts.references.length > 0) {
1842
- const yRefs = opts.references.filter(r => (r.axis ?? "y") === "y");
1843
- if (yRefs.length > 0) {
1844
- body.push(renderReferenceLines(yRefs, {
1845
- domain: [0, 1],
1846
- scale: "linear"
1847
- }, yAxis, area));
1848
- }
1849
- }
1850
- return svgRoot({
1851
- width,
1852
- height,
1853
- className: opts.className
1854
- }, header.svg + body.join(""));
1855
- };
1856
-
1857
- // ==========================
1858
- // DASHBOARD PANELS
1859
- // ==========================
1860
-
1861
- const thresholdIndexForValue = (value, thresholds, min, max) => {
1862
- if (!thresholds || thresholds.length === 0) return 0;
1863
- const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
1864
- const clamped = clamp(value, min, max);
1865
- const idx = sorted.findIndex(t => clamped <= t.value);
1866
- return idx >= 0 ? idx : Math.max(0, sorted.length - 1);
1867
- };
1868
- const thresholdForIndex = (thresholds, index) => {
1869
- if (!thresholds || thresholds.length === 0) return undefined;
1870
- const sorted = [...thresholds].filter(t => Number.isFinite(t.value)).sort((a, b) => a.value - b.value);
1871
- return sorted[index];
1872
- };
1873
-
1874
- /**
1875
- * Render a radial single-value gauge for KPI, quota, saturation, or SLO style
1876
- * dashboard panels.
1877
- */
1878
- export const gauge = opts => {
1879
- const width = opts.width ?? 260;
1880
- const height = opts.height ?? 180;
1881
- const [min, max] = normalizeMinMax(opts.min, opts.max);
1882
- const value = Number.isFinite(opts.value) ? opts.value : min;
1883
- const clamped = clamp(value, min, max);
1884
- const startAngle = Math.PI * 5 / 6;
1885
- const endAngle = Math.PI * 13 / 6;
1886
- const valueAngle = mapRange(clamped, [min, max], [startAngle, endAngle]);
1887
- const cx = width / 2;
1888
- const cy = height * 0.64;
1889
- const radius = Math.min(width * 0.34, height * 0.43);
1890
- const startPoint = polarPoint(cx, cy, radius, startAngle);
1891
- const endPoint = polarPoint(cx, cy, radius, endAngle);
1892
- const endpointLabelY = Math.min(height - 10, Math.max(cy + 32, startPoint.y + 16));
1893
- const progress = clamp(mapRange(clamped, [min, max], [0, 100]), 0, 100);
1894
- const gaugePath = arcLinePathD(cx, cy, radius, startAngle, endAngle);
1895
- const gradientStops = gaugeThresholdStops(opts.thresholds, min, max);
1896
- const thresholdIdx = thresholdIndexForValue(clamped, opts.thresholds, min, max);
1897
- const threshold = thresholdForIndex(opts.thresholds, thresholdIdx);
1898
- const thresholdColor = threshold?.color;
1899
- const valueText = formatNumberValue(value, opts.format, opts.unit);
1900
- const label = opts.label ?? opts.title;
1901
- const fillStroke = gradientStops.length > 0 ? ` stroke="${escapeXml(gaugeColorAt(gradientStops, clamped))}"` : thresholdStrokeAttr(thresholdColor);
1902
- const fillClass = gradientStops.length > 0 || thresholdColor ? "stdlib-chart-gauge-fill" : `stdlib-chart-gauge-fill stdlib-chart-series-${thresholdIdx % 8}`;
1903
- const body = [];
1904
- if (gradientStops.length > 0) {
1905
- body.push(renderGaugeGradientSegments({
1906
- stops: gradientStops,
1907
- min,
1908
- max,
1909
- cx,
1910
- cy,
1911
- radius,
1912
- startAngle,
1913
- endAngle,
1914
- className: "stdlib-chart-gauge-gradient-segment stdlib-chart-gauge-gradient-scale"
1915
- }));
1916
- body.push(renderGaugeGradientSegments({
1917
- stops: gradientStops,
1918
- min,
1919
- max,
1920
- cx,
1921
- cy,
1922
- radius,
1923
- startAngle,
1924
- endAngle,
1925
- progress,
1926
- className: "stdlib-chart-gauge-gradient-segment"
1927
- }));
1928
- } else {
1929
- body.push(`<path class="stdlib-chart-gauge-track" d="${gaugePath}"/>`);
1930
- if (progress > 0) {
1931
- body.push(`<path class="${fillClass}"${fillStroke} pathLength="100" stroke-dasharray="${fmt(progress)} 100" d="${gaugePath}"/>`);
1932
- }
1933
- }
1934
- if (opts.showNeedle) {
1935
- const tip = polarPoint(cx, cy, radius - 8, valueAngle);
1936
- const needleClass = thresholdColor || gradientStops.length > 0 ? "stdlib-chart-gauge-needle" : `stdlib-chart-gauge-needle stdlib-chart-series-${thresholdIdx % 8}`;
1937
- body.push(`<line class="${needleClass}"${fillStroke} x1="${fmt(cx)}" y1="${fmt(cy)}" x2="${fmt(tip.x)}" y2="${fmt(tip.y)}"/>`);
1938
- body.push(`<circle class="stdlib-chart-gauge-hub" cx="${fmt(cx)}" cy="${fmt(cy)}" r="3"/>`);
1939
- }
1940
- body.push(`<text class="stdlib-chart-gauge-value" x="${fmt(cx)}" y="${fmt(cy - 2)}" text-anchor="middle">${escapeXml(valueText)}</text>`);
1941
- if (label) {
1942
- body.push(`<text class="stdlib-chart-gauge-label" x="${fmt(cx)}" y="${fmt(cy + 20)}" text-anchor="middle">${escapeXml(label)}</text>`);
1943
- }
1944
- body.push(`<text class="stdlib-chart-gauge-unit" x="${fmt(startPoint.x)}" y="${fmt(endpointLabelY)}" text-anchor="middle">${escapeXml(formatNumberValue(min, opts.format, opts.unit))}</text>`);
1945
- body.push(`<text class="stdlib-chart-gauge-unit" x="${fmt(endPoint.x)}" y="${fmt(endpointLabelY)}" text-anchor="middle">${escapeXml(formatNumberValue(max, opts.format, opts.unit))}</text>`);
1946
- return svgRoot({
1947
- width,
1948
- height,
1949
- className: opts.className
1950
- }, chartDatumSvg(body.join(""), {
1951
- index: 0,
1952
- role: "value",
1953
- label,
1954
- anchor: [cx, cy],
1955
- values: [{
1956
- key: "value",
1957
- value,
1958
- formatted: valueText
1959
- }, {
1960
- key: "min",
1961
- value: min
1962
- }, {
1963
- key: "max",
1964
- value: max
1965
- }, ...(threshold ? [{
1966
- key: "threshold",
1967
- value: threshold.label ?? threshold.value
1968
- }] : [])]
1969
- }, opts.inspect));
1970
- };
1971
-
1972
- /** Render compact horizontal bar gauges for multiple reduced metrics. */
1973
- export const barGauge = opts => {
1974
- const width = opts.width ?? 420;
1975
- const rowHeight = 28;
1976
- const top = opts.title || opts.subtitle ? 42 : 16;
1977
- const height = opts.height ?? Math.max(80, top + opts.data.length * rowHeight + 14);
1978
- const header = renderHeader(width, opts.title, opts.subtitle);
1979
- const body = [header.svg];
1980
- const labelW = Math.min(140, Math.max(74, width * 0.34));
1981
- const valueW = 56;
1982
- const trackX = labelW + 14;
1983
- const trackW = Math.max(24, width - trackX - valueW - 14);
1984
- const trackH = 10;
1985
- const sourceIndices = opts.data.flatMap((d, index) => Number.isFinite(d.value) ? [index] : []);
1986
- const data = opts.data.filter(d => Number.isFinite(d.value));
1987
- if (data.length === 0) {
1988
- body.push(`<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle">No data</text>`);
1989
- return svgRoot({
1990
- width,
1991
- height,
1992
- className: opts.className
1993
- }, body.join(""));
1994
- }
1995
- data.forEach((d, i) => {
1996
- const [min, max] = normalizeMinMax(d.min ?? opts.min, d.max ?? opts.max);
1997
- const pct = clamp((d.value - min) / (max - min), 0, 1);
1998
- const y = top + i * rowHeight;
1999
- const thresholdIdx = thresholdIndexForValue(d.value, opts.thresholds, min, max);
2000
- const threshold = thresholdForIndex(opts.thresholds, thresholdIdx);
2001
- const thresholdColor = threshold?.color;
2002
- const unit = d.unit ?? opts.unit ?? "";
2003
- const start = body.length;
2004
- body.push(`<text class="stdlib-chart-bar-gauge-label" x="12" y="${fmt(y + 12)}" dominant-baseline="middle">${escapeXml(d.label)}</text>`);
2005
- body.push(`<rect class="stdlib-chart-bar-gauge-track" x="${fmt(trackX)}" y="${fmt(y + 7)}" width="${fmt(trackW)}" height="${fmt(trackH)}" rx="2"/>`);
2006
- body.push(`<rect class="stdlib-chart-bar-gauge-fill stdlib-chart-series-${thresholdIdx % 8}"${thresholdFillAttr(thresholdColor)} x="${fmt(trackX)}" y="${fmt(y + 7)}" width="${fmt(trackW * pct)}" height="${fmt(trackH)}" rx="2"/>`);
2007
- body.push(`<text class="stdlib-chart-bar-gauge-value" x="${fmt(width - 12)}" y="${fmt(y + 12)}" text-anchor="end" dominant-baseline="middle">${escapeXml(formatNumberValue(d.value, opts.format, unit))}</text>`);
2008
- const shapes = body.splice(start).join("");
2009
- body.push(chartDatumSvg(shapes, {
2010
- index: sourceIndices[i],
2011
- role: "item",
2012
- label: d.label,
2013
- anchor: [trackX + trackW / 2, y + 12],
2014
- values: [{
2015
- key: "value",
2016
- value: d.value,
2017
- formatted: formatNumberValue(d.value, opts.format, unit)
2018
- }, {
2019
- key: "min",
2020
- value: min
2021
- }, {
2022
- key: "max",
2023
- value: max
2024
- }, ...(threshold ? [{
2025
- key: "threshold",
2026
- value: threshold.label ?? threshold.value
2027
- }] : [])]
2028
- }, opts.inspect));
2029
- });
2030
- return svgRoot({
2031
- width,
2032
- height,
2033
- className: opts.className
2034
- }, body.join(""));
2035
- };
2036
350
  const renderInlineSparkline = (values, x, y, width, height, inspect) => {
2037
351
  if (!values || values.length < 2) return "";
2038
352
  const entries = sparklineEntries(values);
@@ -2094,84 +408,6 @@ export const stat = opts => {
2094
408
  }, summary + renderInlineSparkline(opts.sparkline, 16, height - 42, width - 32, 26, opts.inspect));
2095
409
  };
2096
410
 
2097
- /**
2098
- * Render a categorical two-dimensional heatmap. Cell opacity represents value
2099
- * intensity; labels are derived from first occurrence order unless provided.
2100
- */
2101
- export const heatmap = opts => {
2102
- const width = opts.width ?? 460;
2103
- const height = opts.height ?? 260;
2104
- const padding = normalizePadding(opts.padding ?? {
2105
- top: 36,
2106
- right: 16,
2107
- bottom: 32,
2108
- left: 54
2109
- });
2110
- const header = renderHeader(width, opts.title, opts.subtitle);
2111
- const xLabels = opts.xLabels ?? [...new Set(opts.data.map(d => d.x))];
2112
- const yLabels = opts.yLabels ?? [...new Set(opts.data.map(d => d.y))];
2113
- if (xLabels.length === 0 || yLabels.length === 0) {
2114
- return svgRoot({
2115
- width,
2116
- height,
2117
- className: opts.className
2118
- }, header.svg + `<text class="stdlib-chart-empty-text" x="${fmt(width / 2)}" y="${fmt(height / 2)}" text-anchor="middle">No data</text>`);
2119
- }
2120
- const area = computePlotArea(width, height, padding, false, false, header.height, 0);
2121
- const values = opts.data.map(d => d.value).filter(Number.isFinite);
2122
- const [autoMin, autoMax] = computeDomain(values);
2123
- const min = Number.isFinite(opts.min) ? opts.min : autoMin;
2124
- const max = Number.isFinite(opts.max) ? opts.max : autoMax;
2125
- const indexMap = new Map(opts.data.map((d, index) => [`${d.x}\u0000${d.y}`, index]));
2126
- const valueMap = new Map(opts.data.map(d => [`${d.x}\u0000${d.y}`, d.value]));
2127
- const cellW = (area.x1 - area.x0) / xLabels.length;
2128
- const cellH = (area.y1 - area.y0) / yLabels.length;
2129
- const body = [header.svg];
2130
- const format = opts.format ?? (v => fmt(v));
2131
- xLabels.forEach((label, i) => {
2132
- const x = area.x0 + cellW * (i + 0.5);
2133
- body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(x)}" y="${fmt(area.y1 + 14)}" text-anchor="middle">${escapeXml(label)}</text>`);
2134
- });
2135
- yLabels.forEach((label, i) => {
2136
- const y = area.y0 + cellH * (i + 0.5);
2137
- body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(area.x0 - 8)}" y="${fmt(y)}" text-anchor="end" dominant-baseline="middle">${escapeXml(label)}</text>`);
2138
- });
2139
- for (let yi = 0; yi < yLabels.length; yi++) {
2140
- for (let xi = 0; xi < xLabels.length; xi++) {
2141
- const valueAtCell = valueMap.get(`${xLabels[xi]}\u0000${yLabels[yi]}`);
2142
- if (!Number.isFinite(valueAtCell)) continue;
2143
- const intensity = clamp(mapRange(valueAtCell, [min, max], [0.12, 1]), 0.12, 1);
2144
- const x = area.x0 + xi * cellW;
2145
- const y = area.y0 + yi * cellH;
2146
- body.push(chartDatumSvg(`<rect class="stdlib-chart-heatmap-cell stdlib-chart-series-0" x="${fmt(x)}" y="${fmt(y)}" width="${fmt(Math.max(0, cellW - 1))}" height="${fmt(Math.max(0, cellH - 1))}" opacity="${fmt(intensity)}"/>`, {
2147
- index: indexMap.get(`${xLabels[xi]}\u0000${yLabels[yi]}`),
2148
- role: "cell",
2149
- anchor: [x + cellW / 2, y + cellH / 2],
2150
- grid: [xi, yi],
2151
- values: [{
2152
- key: "x",
2153
- value: xLabels[xi]
2154
- }, {
2155
- key: "y",
2156
- value: yLabels[yi]
2157
- }, {
2158
- key: "value",
2159
- value: valueAtCell,
2160
- formatted: format(valueAtCell)
2161
- }]
2162
- }, opts.inspect));
2163
- if (opts.showValues) {
2164
- body.push(`<text class="stdlib-chart-heatmap-label" x="${fmt(x + cellW / 2)}" y="${fmt(y + cellH / 2)}" text-anchor="middle" dominant-baseline="middle">${escapeXml(format(valueAtCell))}</text>`);
2165
- }
2166
- }
2167
- }
2168
- return svgRoot({
2169
- width,
2170
- height,
2171
- className: opts.className
2172
- }, body.join(""));
2173
- };
2174
-
2175
411
  // ==========================
2176
412
  // STATE TIMELINE
2177
413
  // ==========================
@@ -2276,10 +512,6 @@ export const stateTimeline = opts => {
2276
512
  }, body.join(""));
2277
513
  };
2278
514
 
2279
- // ==========================
2280
- // SPARKLINE
2281
- // ==========================
2282
-
2283
515
  // Monotonically incrementing counter for per-instance gradient IDs. Using a
2284
516
  // module-level counter (vs. random) keeps output stable enough that repeated
2285
517
  // renders of the same input in a process produce predictable IDs in sequence,