@tetrascience-npm/ts-lib-viz 0.0.0-stage → 0.1.5

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 (278) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2171 -2
  3. package/dist/src/builder/PlotPanel.d.ts +42 -0
  4. package/dist/src/builder/PlotPanel.js +433 -0
  5. package/dist/src/builder/Popover.d.ts +37 -0
  6. package/dist/src/builder/Popover.js +32 -0
  7. package/dist/src/builder/Stepper.d.ts +21 -0
  8. package/dist/src/builder/Stepper.js +41 -0
  9. package/dist/src/builder/index.d.ts +10 -0
  10. package/dist/src/builder/index.js +10 -0
  11. package/dist/src/core/adapters.d.ts +86 -0
  12. package/dist/src/core/adapters.js +219 -0
  13. package/dist/src/core/aggregate.d.ts +74 -0
  14. package/dist/src/core/aggregate.js +102 -0
  15. package/dist/src/core/annotations.d.ts +34 -0
  16. package/dist/src/core/annotations.js +71 -0
  17. package/dist/src/core/band-order.d.ts +86 -0
  18. package/dist/src/core/band-order.js +132 -0
  19. package/dist/src/core/binning.d.ts +123 -0
  20. package/dist/src/core/binning.js +193 -0
  21. package/dist/src/core/bounds.d.ts +40 -0
  22. package/dist/src/core/bounds.js +107 -0
  23. package/dist/src/core/brush.d.ts +73 -0
  24. package/dist/src/core/brush.js +102 -0
  25. package/dist/src/core/build.d.ts +322 -0
  26. package/dist/src/core/build.js +496 -0
  27. package/dist/src/core/camera.d.ts +152 -0
  28. package/dist/src/core/camera.js +303 -0
  29. package/dist/src/core/capabilities.d.ts +24 -0
  30. package/dist/src/core/capabilities.js +307 -0
  31. package/dist/src/core/chord.d.ts +49 -0
  32. package/dist/src/core/chord.js +57 -0
  33. package/dist/src/core/circular.d.ts +83 -0
  34. package/dist/src/core/circular.js +63 -0
  35. package/dist/src/core/cluster.d.ts +136 -0
  36. package/dist/src/core/cluster.js +607 -0
  37. package/dist/src/core/critique.d.ts +92 -0
  38. package/dist/src/core/critique.js +905 -0
  39. package/dist/src/core/density.d.ts +38 -0
  40. package/dist/src/core/density.js +82 -0
  41. package/dist/src/core/figure-set.d.ts +34 -0
  42. package/dist/src/core/figure-set.js +55 -0
  43. package/dist/src/core/finding-codes.d.ts +10 -0
  44. package/dist/src/core/finding-codes.js +1 -0
  45. package/dist/src/core/fit-types.d.ts +46 -0
  46. package/dist/src/core/fit-types.js +7 -0
  47. package/dist/src/core/fitter.d.ts +62 -0
  48. package/dist/src/core/fitter.js +102 -0
  49. package/dist/src/core/frame-geometry.d.ts +407 -0
  50. package/dist/src/core/frame-geometry.js +612 -0
  51. package/dist/src/core/frame.d.ts +329 -0
  52. package/dist/src/core/frame.js +1432 -0
  53. package/dist/src/core/geom-table.d.ts +503 -0
  54. package/dist/src/core/geom-table.js +484 -0
  55. package/dist/src/core/geom-types.d.ts +182 -0
  56. package/dist/src/core/geom-types.js +17 -0
  57. package/dist/src/core/grammar.d.ts +359 -0
  58. package/dist/src/core/grammar.js +397 -0
  59. package/dist/src/core/heat-reductions.d.ts +36 -0
  60. package/dist/src/core/heat-reductions.js +133 -0
  61. package/dist/src/core/hexbin.d.ts +84 -0
  62. package/dist/src/core/hexbin.js +168 -0
  63. package/dist/src/core/hierarchy.d.ts +59 -0
  64. package/dist/src/core/hierarchy.js +248 -0
  65. package/dist/src/core/hit.d.ts +75 -0
  66. package/dist/src/core/hit.js +37 -0
  67. package/dist/src/core/index.d.ts +33 -0
  68. package/dist/src/core/index.js +18 -0
  69. package/dist/src/core/internal.d.ts +58 -0
  70. package/dist/src/core/internal.js +58 -0
  71. package/dist/src/core/labels.d.ts +37 -0
  72. package/dist/src/core/labels.js +54 -0
  73. package/dist/src/core/layers.d.ts +594 -0
  74. package/dist/src/core/layers.js +2892 -0
  75. package/dist/src/core/load.d.ts +17 -0
  76. package/dist/src/core/load.js +356 -0
  77. package/dist/src/core/marginal.d.ts +65 -0
  78. package/dist/src/core/marginal.js +116 -0
  79. package/dist/src/core/mesh.d.ts +69 -0
  80. package/dist/src/core/mesh.js +237 -0
  81. package/dist/src/core/omission.d.ts +41 -0
  82. package/dist/src/core/omission.js +62 -0
  83. package/dist/src/core/palette-sets.d.ts +623 -0
  84. package/dist/src/core/palette-sets.js +1058 -0
  85. package/dist/src/core/palette.d.ts +871 -0
  86. package/dist/src/core/palette.js +511 -0
  87. package/dist/src/core/plot-data.d.ts +71 -0
  88. package/dist/src/core/plot-data.js +82 -0
  89. package/dist/src/core/predicate.d.ts +50 -0
  90. package/dist/src/core/predicate.js +20 -0
  91. package/dist/src/core/profile.d.ts +111 -0
  92. package/dist/src/core/profile.js +221 -0
  93. package/dist/src/core/readout.d.ts +108 -0
  94. package/dist/src/core/readout.js +215 -0
  95. package/dist/src/core/region.d.ts +56 -0
  96. package/dist/src/core/region.js +101 -0
  97. package/dist/src/core/rings.d.ts +96 -0
  98. package/dist/src/core/rings.js +171 -0
  99. package/dist/src/core/rules.d.ts +45 -0
  100. package/dist/src/core/rules.js +69 -0
  101. package/dist/src/core/sankey.d.ts +49 -0
  102. package/dist/src/core/sankey.js +96 -0
  103. package/dist/src/core/select.d.ts +52 -0
  104. package/dist/src/core/select.js +216 -0
  105. package/dist/src/core/side-track.d.ts +98 -0
  106. package/dist/src/core/side-track.js +197 -0
  107. package/dist/src/core/sizing.d.ts +54 -0
  108. package/dist/src/core/sizing.js +37 -0
  109. package/dist/src/core/spec-edit.d.ts +68 -0
  110. package/dist/src/core/spec-edit.js +105 -0
  111. package/dist/src/core/spec.d.ts +1111 -0
  112. package/dist/src/core/spec.js +39 -0
  113. package/dist/src/core/stats.d.ts +161 -0
  114. package/dist/src/core/stats.js +318 -0
  115. package/dist/src/core/tick-format.d.ts +21 -0
  116. package/dist/src/core/tick-format.js +87 -0
  117. package/dist/src/core/tokens.d.ts +47 -0
  118. package/dist/src/core/tokens.js +138 -0
  119. package/dist/src/core/transform.d.ts +21 -0
  120. package/dist/src/core/transform.js +19 -0
  121. package/dist/src/core/voxels.d.ts +53 -0
  122. package/dist/src/core/voxels.js +129 -0
  123. package/dist/src/core/zoom.d.ts +76 -0
  124. package/dist/src/core/zoom.js +103 -0
  125. package/dist/src/graph/GraphSurface.d.ts +127 -0
  126. package/dist/src/graph/GraphSurface.js +423 -0
  127. package/dist/src/graph/data.d.ts +103 -0
  128. package/dist/src/graph/data.js +140 -0
  129. package/dist/src/graph/index.d.ts +7 -0
  130. package/dist/src/graph/index.js +7 -0
  131. package/dist/src/mcp/data.d.ts +28 -0
  132. package/dist/src/mcp/data.js +131 -0
  133. package/dist/src/mcp/index.d.ts +7 -0
  134. package/dist/src/mcp/index.js +7 -0
  135. package/dist/src/mcp/paths.d.ts +12 -0
  136. package/dist/src/mcp/paths.js +30 -0
  137. package/dist/src/mcp/render.d.ts +67 -0
  138. package/dist/src/mcp/render.js +189 -0
  139. package/dist/src/mcp/server.d.ts +7 -0
  140. package/dist/src/mcp/server.js +25 -0
  141. package/dist/src/mcp/tools.d.ts +82 -0
  142. package/dist/src/mcp/tools.js +412 -0
  143. package/dist/src/react/BrushLayer.d.ts +20 -0
  144. package/dist/src/react/BrushLayer.js +98 -0
  145. package/dist/src/react/ColorLegend.d.ts +45 -0
  146. package/dist/src/react/ColorLegend.js +64 -0
  147. package/dist/src/react/Figure.d.ts +19 -0
  148. package/dist/src/react/Figure.js +6 -0
  149. package/dist/src/react/Frame.d.ts +87 -0
  150. package/dist/src/react/Frame.js +192 -0
  151. package/dist/src/react/MarkLegend.d.ts +32 -0
  152. package/dist/src/react/MarkLegend.js +24 -0
  153. package/dist/src/react/SeriesLegend.d.ts +38 -0
  154. package/dist/src/react/SeriesLegend.js +27 -0
  155. package/dist/src/react/SizeLegend.d.ts +24 -0
  156. package/dist/src/react/SizeLegend.js +25 -0
  157. package/dist/src/react/Toolbar.d.ts +109 -0
  158. package/dist/src/react/Toolbar.js +483 -0
  159. package/dist/src/react/Tooltip.d.ts +37 -0
  160. package/dist/src/react/Tooltip.js +59 -0
  161. package/dist/src/react/Viz.d.ts +112 -0
  162. package/dist/src/react/Viz.js +1311 -0
  163. package/dist/src/react/export.d.ts +32 -0
  164. package/dist/src/react/export.js +181 -0
  165. package/dist/src/react/geoms/Area.d.ts +38 -0
  166. package/dist/src/react/geoms/Area.js +48 -0
  167. package/dist/src/react/geoms/Bars.d.ts +130 -0
  168. package/dist/src/react/geoms/Bars.js +164 -0
  169. package/dist/src/react/geoms/Box.d.ts +50 -0
  170. package/dist/src/react/geoms/Box.js +32 -0
  171. package/dist/src/react/geoms/Chord.d.ts +60 -0
  172. package/dist/src/react/geoms/Chord.js +78 -0
  173. package/dist/src/react/geoms/Contour.d.ts +44 -0
  174. package/dist/src/react/geoms/Contour.js +78 -0
  175. package/dist/src/react/geoms/DensityCurve.d.ts +30 -0
  176. package/dist/src/react/geoms/DensityCurve.js +38 -0
  177. package/dist/src/react/geoms/FitCurve.d.ts +26 -0
  178. package/dist/src/react/geoms/FitCurve.js +52 -0
  179. package/dist/src/react/geoms/Freqpoly.d.ts +30 -0
  180. package/dist/src/react/geoms/Freqpoly.js +45 -0
  181. package/dist/src/react/geoms/Gauge.d.ts +42 -0
  182. package/dist/src/react/geoms/Gauge.js +90 -0
  183. package/dist/src/react/geoms/Heatmap.d.ts +79 -0
  184. package/dist/src/react/geoms/Heatmap.js +51 -0
  185. package/dist/src/react/geoms/Hexbin.d.ts +74 -0
  186. package/dist/src/react/geoms/Hexbin.js +89 -0
  187. package/dist/src/react/geoms/Icicle.d.ts +38 -0
  188. package/dist/src/react/geoms/Icicle.js +9 -0
  189. package/dist/src/react/geoms/Ideogram.d.ts +58 -0
  190. package/dist/src/react/geoms/Ideogram.js +77 -0
  191. package/dist/src/react/geoms/Interval.d.ts +30 -0
  192. package/dist/src/react/geoms/Interval.js +39 -0
  193. package/dist/src/react/geoms/Line.d.ts +39 -0
  194. package/dist/src/react/geoms/Line.js +52 -0
  195. package/dist/src/react/geoms/Parallel.d.ts +38 -0
  196. package/dist/src/react/geoms/Parallel.js +131 -0
  197. package/dist/src/react/geoms/Pie.d.ts +62 -0
  198. package/dist/src/react/geoms/Pie.js +59 -0
  199. package/dist/src/react/geoms/Points.d.ts +84 -0
  200. package/dist/src/react/geoms/Points.js +207 -0
  201. package/dist/src/react/geoms/Points3d.d.ts +49 -0
  202. package/dist/src/react/geoms/Points3d.js +58 -0
  203. package/dist/src/react/geoms/Radar.d.ts +39 -0
  204. package/dist/src/react/geoms/Radar.js +59 -0
  205. package/dist/src/react/geoms/Range.d.ts +31 -0
  206. package/dist/src/react/geoms/Range.js +20 -0
  207. package/dist/src/react/geoms/RingStack.d.ts +39 -0
  208. package/dist/src/react/geoms/RingStack.js +65 -0
  209. package/dist/src/react/geoms/Rule.d.ts +29 -0
  210. package/dist/src/react/geoms/Rule.js +51 -0
  211. package/dist/src/react/geoms/Sankey.d.ts +24 -0
  212. package/dist/src/react/geoms/Sankey.js +51 -0
  213. package/dist/src/react/geoms/Segment.d.ts +36 -0
  214. package/dist/src/react/geoms/Segment.js +39 -0
  215. package/dist/src/react/geoms/Sunburst.d.ts +46 -0
  216. package/dist/src/react/geoms/Sunburst.js +64 -0
  217. package/dist/src/react/geoms/Surface.d.ts +32 -0
  218. package/dist/src/react/geoms/Surface.js +49 -0
  219. package/dist/src/react/geoms/Text.d.ts +35 -0
  220. package/dist/src/react/geoms/Text.js +40 -0
  221. package/dist/src/react/geoms/Treemap.d.ts +39 -0
  222. package/dist/src/react/geoms/Treemap.js +16 -0
  223. package/dist/src/react/geoms/Violin.d.ts +56 -0
  224. package/dist/src/react/geoms/Violin.js +60 -0
  225. package/dist/src/react/geoms/Volume.d.ts +37 -0
  226. package/dist/src/react/geoms/Volume.js +40 -0
  227. package/dist/src/react/geoms/Waterfall.d.ts +43 -0
  228. package/dist/src/react/geoms/Waterfall.js +18 -0
  229. package/dist/src/react/geoms/cube-stage.d.ts +39 -0
  230. package/dist/src/react/geoms/cube-stage.js +85 -0
  231. package/dist/src/react/geoms/hierarchy-cells.d.ts +42 -0
  232. package/dist/src/react/geoms/hierarchy-cells.js +59 -0
  233. package/dist/src/react/geoms/sector-axis.d.ts +66 -0
  234. package/dist/src/react/geoms/sector-axis.js +99 -0
  235. package/dist/src/react/gl/GlMesh.d.ts +22 -0
  236. package/dist/src/react/gl/GlMesh.js +78 -0
  237. package/dist/src/react/gl/GlPoints.d.ts +45 -0
  238. package/dist/src/react/gl/GlPoints.js +117 -0
  239. package/dist/src/react/gl/GlVolume.d.ts +28 -0
  240. package/dist/src/react/gl/GlVolume.js +112 -0
  241. package/dist/src/react/gl/GlWalls.d.ts +24 -0
  242. package/dist/src/react/gl/GlWalls.js +55 -0
  243. package/dist/src/react/gl/context.d.ts +71 -0
  244. package/dist/src/react/gl/context.js +98 -0
  245. package/dist/src/react/gl/encode.d.ts +120 -0
  246. package/dist/src/react/gl/encode.js +215 -0
  247. package/dist/src/react/gl/index.d.ts +10 -0
  248. package/dist/src/react/gl/index.js +8 -0
  249. package/dist/src/react/gl/refresh.d.ts +7 -0
  250. package/dist/src/react/gl/refresh.js +19 -0
  251. package/dist/src/react/gl/renderer.d.ts +377 -0
  252. package/dist/src/react/gl/renderer.js +1081 -0
  253. package/dist/src/react/gl/shaders.d.ts +92 -0
  254. package/dist/src/react/gl/shaders.js +405 -0
  255. package/dist/src/react/gl/surface.d.ts +31 -0
  256. package/dist/src/react/gl/surface.js +73 -0
  257. package/dist/src/react/index.d.ts +12 -0
  258. package/dist/src/react/index.js +11 -0
  259. package/dist/src/react/orbit.d.ts +38 -0
  260. package/dist/src/react/orbit.js +81 -0
  261. package/dist/src/react/sides/DendrogramPanel.d.ts +32 -0
  262. package/dist/src/react/sides/DendrogramPanel.js +39 -0
  263. package/dist/src/react/sides/DensityPanel.d.ts +31 -0
  264. package/dist/src/react/sides/DensityPanel.js +37 -0
  265. package/dist/src/react/sides/HistogramPanel.d.ts +30 -0
  266. package/dist/src/react/sides/HistogramPanel.js +18 -0
  267. package/dist/src/react/sides/RugPanel.d.ts +28 -0
  268. package/dist/src/react/sides/RugPanel.js +21 -0
  269. package/dist/src/react/sides/TrackPanel.d.ts +37 -0
  270. package/dist/src/react/sides/TrackPanel.js +27 -0
  271. package/dist/src/react/theme.d.ts +48 -0
  272. package/dist/src/react/theme.js +148 -0
  273. package/dist/src/react/useFits.d.ts +26 -0
  274. package/dist/src/react/useFits.js +62 -0
  275. package/dist/src/react/useZoom.d.ts +50 -0
  276. package/dist/src/react/useZoom.js +141 -0
  277. package/package.json +164 -5
  278. package/theme/default.css +62 -0
@@ -0,0 +1,412 @@
1
+ /**
2
+ * Tools and handlers.
3
+ *
4
+ * Public for use by another source table. Calls are stateless. Any follow up turns edit the same produced source.
5
+ */
6
+ import { writeFile } from "node:fs/promises";
7
+ import { addLayer, bindAes, blocking, buildFrame, critique, isAesthetic, kindFacts, KINDS, loadSpec, plot, plotKinds, PLOTS, removeLayer, sideRoom, } from "../core/internal.js";
8
+ import { loadSource } from "./data.js";
9
+ import { confine } from "./paths.js";
10
+ import { MultiPanelFigure, panelSize, palettesForTheme, renderPng, renderSvg } from "./render.js";
11
+ /** Each field a patch may set or clear, with the JSON shape its value takes. */
12
+ const PATCHABLE = {
13
+ headline: "string",
14
+ subtitle: "string",
15
+ caption: "string",
16
+ facet: "object",
17
+ coord: "string",
18
+ scales: "object",
19
+ tooltip: "array",
20
+ annotations: "array",
21
+ legend: "object",
22
+ overrides: "array",
23
+ sides: "array",
24
+ width: "number",
25
+ height: "number",
26
+ aspect: "number",
27
+ ratio: "number",
28
+ sizing: "string",
29
+ };
30
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ /**
32
+ * A patch object over the held one, field by field to `depth` levels.
33
+ *
34
+ * A null clears its field. Past the last level a value replaces what it lands on.
35
+ */
36
+ function merged(held, patch, depth) {
37
+ const next = new Map(Object.entries(isPlain(held) ? held : {}));
38
+ for (const [key, value] of Object.entries(patch)) {
39
+ if (value === null)
40
+ next.delete(key);
41
+ else
42
+ next.set(key, depth > 1 && isPlain(value) ? merged(next.get(key), value, depth - 1) : value);
43
+ }
44
+ return Object.fromEntries(next);
45
+ }
46
+ const shapeOf = (value) => (Array.isArray(value) ? "array" : value === null ? "null" : typeof value);
47
+ /**
48
+ * One layer on a draft, through the builder's `layer(kind, options)`.
49
+ *
50
+ * A smooth assembles its `SmoothSpec`. A reference line reads a number flat as a position and a
51
+ * column through its aes.
52
+ */
53
+ function withLayer(draft, { kind, ...options }) {
54
+ return draft.layer(kind, options);
55
+ }
56
+ /**
57
+ * The aes a new layer inherits, off the first layer that reads the chart's rows and binds an x.
58
+ *
59
+ * A reference line and a layer holding rows of its own state their own aes.
60
+ */
61
+ function inherited(spec) {
62
+ const bindsX = (kind) => {
63
+ const { requires, accepts } = kindFacts(kind);
64
+ return [...requires, ...accepts].includes("x");
65
+ };
66
+ return spec.layers.find((layer) => !layer.data && bindsX(layer.kind))?.aes ?? {};
67
+ }
68
+ /**
69
+ * Applies one edit set to a chart, returning a new document.
70
+ *
71
+ * Layer ids, removal and binding go through the spec editors. An id no layer holds, or a removal of
72
+ * the last layer, throws where the editor hands the spec back.
73
+ */
74
+ export function applyEdits(spec, edits) {
75
+ let next = { ...spec };
76
+ const held = (id) => {
77
+ if (!next.layers.some((layer) => layer.id === id))
78
+ throw new Error(`edit_plot: no layer has the id ${id}`);
79
+ return id;
80
+ };
81
+ for (const [key, value] of Object.entries(edits.patch ?? {})) {
82
+ const shape = Object.hasOwn(PATCHABLE, key) ? PATCHABLE[key] : undefined;
83
+ if (!shape)
84
+ throw new Error(`edit_plot: ${key} is not a patchable field`);
85
+ const fields = next;
86
+ if (value === null)
87
+ delete fields[key];
88
+ else if (shapeOf(value) !== shape)
89
+ throw new Error(`edit_plot: ${key} takes a ${shape}`);
90
+ /* Scales merge per aesthetic and then per field. Legend and facet merge per field. */ else if (shape === "object")
91
+ fields[key] = merged(fields[key], value, key === "scales" ? 2 : 1);
92
+ else
93
+ fields[key] = value;
94
+ }
95
+ for (const id of edits.removeLayer ?? []) {
96
+ const kept = removeLayer(next, held(id));
97
+ if (kept === next)
98
+ throw new Error("edit_plot: a chart holds at least one layer");
99
+ next = kept;
100
+ }
101
+ for (const layer of edits.addLayer ?? []) {
102
+ if (!KINDS.includes(layer.kind))
103
+ throw new Error(`edit_plot: ${String(layer.kind)} is not a kind`);
104
+ const built = withLayer(plot([], inherited(next), next.id), layer).spec();
105
+ /* The editor's id for a new layer of this kind. The layer itself is the builder's, over the inherited aes. */
106
+ const { id } = addLayer(next, layer.kind).layers.at(-1);
107
+ next = { ...next, layers: [...next.layers, { ...built.layers.at(-1), id }] };
108
+ }
109
+ for (const binding of edits.bind ?? []) {
110
+ if (!isAesthetic(binding.aes))
111
+ throw new Error(`edit_plot: ${String(binding.aes)} is not an aesthetic`);
112
+ const target = held(binding.layer ?? next.layers[0].id);
113
+ next = bindAes(next, { layerId: target, aesthetic: binding.aes, field: binding.field ?? undefined });
114
+ }
115
+ return next;
116
+ }
117
+ /** Builds a one-layer chart from a kind and its bindings. */
118
+ export function buildSpec(input) {
119
+ const aes = { ...input.aes, ...input.layer?.aes };
120
+ let draft = withLayer(plot([], input.aes, input.id ?? "chart"), { ...input.layer, kind: input.kind, aes });
121
+ if (input.headline)
122
+ draft = draft.labs({ headline: input.headline });
123
+ return input.edits ? applyEdits(draft.spec(), input.edits) : draft.spec();
124
+ }
125
+ /** What a drawn file leaves on the page. The figure's chrome is HTML around the plot. */
126
+ const CHROME_NOTE = "The headline and footer are HTML around the chart and stay with the page.";
127
+ /**
128
+ * Whether any layer asks for a curve.
129
+ *
130
+ * The package ships no solver. A spec asking for a curve draws its geoms uncurved.
131
+ */
132
+ const asksForCurve = (spec) => spec.layers.some((series) => (series.kind === "smooth" ? series.smooth : series.fit) != null);
133
+ const CURVE_NOTE = "A curve was asked for and none is drawn. The package takes its solver from the host through Viz.fitter, and this server passes none.";
134
+ const findingLine = (finding) => `${finding.severity} [${finding.code}] ${finding.path}: ${finding.message}`;
135
+ /**
136
+ * Runs a drawing call.
137
+ *
138
+ * A figure the headless path cannot draw returns its spec and findings, with the reason in place of the image.
139
+ */
140
+ async function drawn(spec, source, theme, stated) {
141
+ const { fieldOverrides, rows, data } = await loadSource(source, stated);
142
+ /* The frame is a component of measure because the critic reads geometry. */
143
+ /* If a band is illegible or a figure extends past its container the critic will flag these violations. */
144
+ const built = buildFrame(spec, data, { palettes: palettesForTheme(theme) });
145
+ const frame = built.status === "ready" ? built : undefined;
146
+ const { width, height } = panelSize(spec);
147
+ /* The panel less its margin and its sides, the plot area Viz hands the critic. */
148
+ const room = sideRoom(spec.sides);
149
+ const area = frame
150
+ ? {
151
+ width: width - frame.margin.left - frame.margin.right - room.left - room.right,
152
+ height: height - frame.margin.top - frame.margin.bottom - room.top - room.bottom,
153
+ }
154
+ : undefined;
155
+ const findings = critique(spec, { frame, container: width, area });
156
+ const blocked = blocking(spec, findings).map((finding) => finding.code);
157
+ const report = {
158
+ spec,
159
+ findings: findings.map(findingLine),
160
+ /** Codes that would refuse this figure at a save gate. */
161
+ blocked,
162
+ };
163
+ let picture;
164
+ const notes = asksForCurve(spec) ? [CURVE_NOTE] : [];
165
+ try {
166
+ const drawn = renderPng({ spec, data: rows, fieldOverrides, theme });
167
+ picture = { type: "image", data: Buffer.from(drawn.png).toString("base64"), mimeType: "image/png" };
168
+ notes.push(drawn.legendDropped ? `${CHROME_NOTE} The shape, size, opacity and dash guides go with them.` : CHROME_NOTE);
169
+ }
170
+ catch (error) {
171
+ if (!(error instanceof MultiPanelFigure))
172
+ throw error;
173
+ picture = { type: "text", text: error.message };
174
+ }
175
+ return { content: [picture, { type: "text", text: JSON.stringify({ ...report, notes }, null, "\t") }] };
176
+ }
177
+ const SOURCE_SCHEMA = {
178
+ type: "object",
179
+ description: "Where the rows come from.",
180
+ oneOf: [
181
+ {
182
+ type: "object",
183
+ properties: { kind: { const: "inline" }, rows: { type: "array", items: { type: "object" } } },
184
+ required: ["kind", "rows"],
185
+ },
186
+ {
187
+ type: "object",
188
+ properties: {
189
+ kind: { const: "file" },
190
+ path: { type: "string", description: "A .json, .csv or .tsv file inside VIZ_MCP_ROOT." },
191
+ },
192
+ required: ["kind", "path"],
193
+ },
194
+ ],
195
+ };
196
+ const SPEC_SCHEMA = { type: "object", description: "A ChartSpec, as returned by a previous call." };
197
+ const THEME_SCHEMA = { type: "string", enum: ["light", "dark"], default: "light" };
198
+ /** The drawn-file themes, plus the one that leaves the choice to the page. */
199
+ const FILE_THEME_SCHEMA = {
200
+ type: "string",
201
+ enum: ["light", "dark", "tokens"],
202
+ default: "light",
203
+ description: '"tokens" leaves each --viz-* token as a reference to itself and paints no ground, so a page declaring them draws the figure in the reader\'s own light or dark setting. It needs format "svg": a png resolves no custom property.',
204
+ };
205
+ /** The aesthetics by name, off each kind's geom row. */
206
+ const AESTHETICS = [...new Set(KINDS.flatMap((kind) => [...kindFacts(kind).requires, ...kindFacts(kind).accepts]))];
207
+ /** Column id per aesthetic. */
208
+ const AES_SCHEMA = {
209
+ type: "object",
210
+ propertyNames: { enum: AESTHETICS },
211
+ additionalProperties: { type: ["string", "array"], items: { type: "string" } },
212
+ };
213
+ const EDITS_SCHEMA = {
214
+ type: "object",
215
+ description: "Changes applied in one pass: patch, then removeLayer, then addLayer, then bind.",
216
+ properties: {
217
+ patch: {
218
+ type: "object",
219
+ description: "Chart-level fields merged onto the spec. scales merges per aesthetic and then per field, so setting y.limits keeps y.title and x. legend and facet merge per field. An array or a scalar replaces. A null clears the field it sits on.",
220
+ properties: Object.fromEntries(Object.entries(PATCHABLE).map(([field, shape]) => [field, { type: [shape, "null"] }])),
221
+ additionalProperties: false,
222
+ },
223
+ addLayer: {
224
+ type: "array",
225
+ description: "Extra layers over the aes of the first layer that reads the chart's rows and binds an x, each stating a kind, an aes of its own, and flat constants such as color, linewidth or alpha. hline, vline and abline take numbers as their flat positions (yintercept, xintercept, slope, intercept), and a column binds through aes.",
226
+ items: {
227
+ type: "object",
228
+ properties: { kind: { type: "string", enum: KINDS }, aes: AES_SCHEMA },
229
+ required: ["kind"],
230
+ },
231
+ },
232
+ removeLayer: { type: "array", items: { type: "string" }, description: "Layer ids to drop." },
233
+ bind: {
234
+ type: "array",
235
+ description: "Aesthetic bindings. Omitting `layer` binds the first layer; a null field unbinds.",
236
+ items: {
237
+ type: "object",
238
+ properties: {
239
+ layer: { type: "string" },
240
+ aes: { type: "string", enum: AESTHETICS },
241
+ field: { type: ["string", "array", "null"], items: { type: "string" } },
242
+ },
243
+ required: ["aes"],
244
+ },
245
+ },
246
+ },
247
+ };
248
+ export const TOOLS = [
249
+ {
250
+ name: "describe_source",
251
+ description: "Columns in a table, what each one means, and which chart kinds it can draw. Call this before creating a plot: the column ids it returns are what an aes maps to each aesthetic.",
252
+ inputSchema: {
253
+ type: "object",
254
+ properties: { source: SOURCE_SCHEMA },
255
+ required: ["source"],
256
+ },
257
+ },
258
+ {
259
+ name: "create_plot",
260
+ description: "Draws a chart of one kind over a table and returns the picture, the ChartSpec behind it, and any critic findings. Pass the ChartSpec back to edit_plot to change it.",
261
+ inputSchema: {
262
+ type: "object",
263
+ properties: {
264
+ source: SOURCE_SCHEMA,
265
+ kind: { type: "string", enum: KINDS, description: "The chart type." },
266
+ aes: {
267
+ ...AES_SCHEMA,
268
+ description: "Column id per aesthetic, as describe_source lists them. For example {x: 'umap_1', y: 'umap_2'}.",
269
+ },
270
+ headline: { type: "string", description: "The claim the chart makes, as a sentence." },
271
+ layer: {
272
+ type: "object",
273
+ description: "Flat options for the layer: constants such as color, fill, linewidth or alpha, and settings such as aggregate, position or palette. A column binds through aes. hline, vline and abline take numbers as their positions here. palette names a map: a categorical one such as okabe-ito, dark2, paired or set2 colors each category with its own stops, and a sequential or diverging one such as magma, viridis, turbo, blues or rdbu steps along itself.",
274
+ },
275
+ edits: EDITS_SCHEMA,
276
+ theme: THEME_SCHEMA,
277
+ },
278
+ required: ["source", "kind", "aes"],
279
+ },
280
+ },
281
+ {
282
+ name: "edit_plot",
283
+ description: "Applies changes to a ChartSpec and redraws it. Faceting, flipping, log scales, headlines, extra layers and rebinding all go through here.",
284
+ inputSchema: {
285
+ type: "object",
286
+ properties: { source: SOURCE_SCHEMA, spec: SPEC_SCHEMA, edits: EDITS_SCHEMA, theme: THEME_SCHEMA },
287
+ required: ["source", "spec", "edits"],
288
+ },
289
+ },
290
+ {
291
+ name: "render_plot",
292
+ description: "Redraws a ChartSpec unchanged, at a different size, theme or format. Given a path, writes the file and returns where it landed.",
293
+ inputSchema: {
294
+ type: "object",
295
+ properties: {
296
+ source: SOURCE_SCHEMA,
297
+ spec: SPEC_SCHEMA,
298
+ theme: FILE_THEME_SCHEMA,
299
+ width: { type: "number" },
300
+ height: { type: "number" },
301
+ scale: { type: "number", description: "Pixel scale for the raster copy. Defaults to 2." },
302
+ format: { type: "string", enum: ["png", "svg"], default: "png" },
303
+ path: {
304
+ type: "string",
305
+ description: "Where to write the file, inside VIZ_MCP_ROOT. Omitted, a png comes back inline.",
306
+ },
307
+ },
308
+ required: ["source", "spec"],
309
+ },
310
+ },
311
+ ];
312
+ const asSource = (args) => args.source;
313
+ const asTheme = (args) => (args.theme === "dark" ? "dark" : args.theme === "tokens" ? "tokens" : "light");
314
+ /** Refuses arguments the tool's schema rules out: a missing required field, or a value outside an enum. */
315
+ function checkArgs(name, args) {
316
+ const tool = TOOLS.find((entry) => entry.name === name);
317
+ if (!tool)
318
+ throw new Error(`unknown tool ${name}`);
319
+ for (const field of tool.inputSchema.required) {
320
+ if (args[field] == null)
321
+ throw new Error(`${name}: ${field} is required`);
322
+ }
323
+ for (const [field, schema] of Object.entries(tool.inputSchema.properties)) {
324
+ const allowed = schema.enum;
325
+ if (allowed && args[field] !== undefined && !allowed.includes(args[field])) {
326
+ throw new Error(`${name}: ${field} takes one of ${allowed.join(", ")}`);
327
+ }
328
+ }
329
+ }
330
+ /** Runs one tool call by name. */
331
+ export async function callTool(name, args) {
332
+ checkArgs(name, args);
333
+ switch (name) {
334
+ case "describe_source":
335
+ return describeSource(asSource(args));
336
+ case "create_plot":
337
+ return drawn(buildSpec({
338
+ kind: args.kind,
339
+ aes: args.aes,
340
+ headline: args.headline,
341
+ layer: args.layer,
342
+ edits: args.edits,
343
+ }), asSource(args), asTheme(args));
344
+ case "edit_plot":
345
+ return drawn(applyEdits(loadSpec(args.spec), args.edits), asSource(args), asTheme(args));
346
+ case "render_plot":
347
+ return renderTool(args);
348
+ default:
349
+ throw new Error(`unknown tool ${name}`);
350
+ }
351
+ }
352
+ async function describeSource(source) {
353
+ const { data } = await loadSource(source);
354
+ const kinds = plotKinds(data.fields.map((field) => ({ role: field.role, numeric: field.numeric })));
355
+ const labelOf = new Map(PLOTS.map((capability) => [capability.kind, capability]));
356
+ return {
357
+ content: [
358
+ {
359
+ type: "text",
360
+ text: JSON.stringify({
361
+ rowCount: data.rowCount,
362
+ fields: data.fields.map((field) => ({
363
+ id: field.id,
364
+ label: field.label,
365
+ numeric: field.numeric,
366
+ role: field.role ?? (field.numeric ? "measure" : "dimension"),
367
+ unit: field.unit,
368
+ timeScale: field.timeScale,
369
+ })),
370
+ available: kinds
371
+ .filter((option) => option.available)
372
+ .map((option) => ({
373
+ kind: option.kind,
374
+ aesthetics: labelOf.get(option.kind)?.aesthetics.map((entry) => ({
375
+ aesthetic: entry.aesthetic,
376
+ roles: entry.roles,
377
+ required: entry.required,
378
+ })),
379
+ })),
380
+ unavailable: kinds
381
+ .filter((option) => !option.available)
382
+ .map((option) => ({ kind: option.kind, reason: option.reason })),
383
+ }, null, "\t"),
384
+ },
385
+ ],
386
+ };
387
+ }
388
+ async function renderTool(args) {
389
+ const source = asSource(args);
390
+ const { rows, fieldOverrides } = await loadSource(source);
391
+ const base = loadSpec(args.spec);
392
+ const spec = {
393
+ ...base,
394
+ ...(typeof args.width === "number" ? { width: args.width } : {}),
395
+ ...(typeof args.height === "number" ? { height: args.height } : {}),
396
+ };
397
+ const options = { spec, data: rows, fieldOverrides, theme: asTheme(args), scale: args.scale };
398
+ const svg = args.format === "svg";
399
+ const path = typeof args.path === "string" ? await confine(args.path, [svg ? ".svg" : ".png"]) : undefined;
400
+ if (svg) {
401
+ const markup = renderSvg(options);
402
+ if (!path)
403
+ return { content: [{ type: "text", text: markup }] };
404
+ await writeFile(path, `${markup}\n`, { encoding: "utf8", flag: "wx" });
405
+ return { content: [{ type: "text", text: `wrote ${path}` }] };
406
+ }
407
+ const { png } = renderPng(options);
408
+ if (!path)
409
+ return { content: [{ type: "image", data: Buffer.from(png).toString("base64"), mimeType: "image/png" }] };
410
+ await writeFile(path, png, { flag: "wx" });
411
+ return { content: [{ type: "text", text: `wrote ${path}` }] };
412
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A box or a lasso dragged over a scatter's plot area.
3
+ *
4
+ * The layer wraps the geoms and hears presses on their hover targets. A click clears the region.
5
+ */
6
+ import { type ReactNode } from "react";
7
+ import { type Brushed, type BrushShape, type ChartSpec, type FrameChildProps, type Pixel, type Trace } from "../core/internal.js";
8
+ export interface BrushLayerProps {
9
+ shape: BrushShape;
10
+ child: FrameChildProps;
11
+ traces: readonly Trace[];
12
+ spec: ChartSpec;
13
+ keyField?: string;
14
+ transposed?: boolean;
15
+ onBrush?: (brushed: Brushed | null) => void;
16
+ /** Receives a released box's two corners in plot-area pixels. A layer with it zooms and selects nothing. */
17
+ onRegion?: (corners: readonly [Pixel, Pixel]) => void;
18
+ children: ReactNode;
19
+ }
20
+ export declare function BrushLayer({ shape, child, traces, spec, keyField, transposed, onBrush, onRegion, children, }: BrushLayerProps): import("react").JSX.Element;
@@ -0,0 +1,98 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * A box or a lasso dragged over a scatter's plot area.
4
+ *
5
+ * The layer wraps the geoms and hears presses on their hover targets. A click clears the region.
6
+ */
7
+ import { useRef, useState } from "react";
8
+ import { brushedOf, } from "../core/internal.js";
9
+ /** Pointer travel that makes a press a drag and not a click, in pixels. */
10
+ const DRAG_FLOOR = 3;
11
+ /** Travel between two lasso vertices, in pixels. */
12
+ const VERTEX_GAP = 2;
13
+ /** The outline of a region through its pixels. A box takes its two corners. */
14
+ function outlineOf(shape, at) {
15
+ if (shape === "box") {
16
+ const [a, b] = at;
17
+ return a && b ? `M${a.x},${a.y}H${b.x}V${b.y}H${a.x}Z` : "";
18
+ }
19
+ return `${at.map((one, index) => `${index === 0 ? "M" : "L"}${one.x},${one.y}`).join("")}Z`;
20
+ }
21
+ export function BrushLayer({ shape, child, traces, spec, keyField, transposed = false, onBrush, onRegion, children, }) {
22
+ const area = useRef(null);
23
+ const start = useRef(null);
24
+ const dragged = useRef(false);
25
+ /* The vertices while the hand is down, in plot-area pixels. Read at release. */
26
+ const trail = useRef([]);
27
+ const [path, setPath] = useState(null);
28
+ /* The released region in data units. A zoom redraws it over the records it holds. */
29
+ const [held, setHeld] = useState(null);
30
+ const local = (event) => {
31
+ const box = area.current?.getBoundingClientRect();
32
+ const x = event.clientX - (box?.left ?? 0);
33
+ const y = event.clientY - (box?.top ?? 0);
34
+ return { x: Math.min(child.width, Math.max(0, x)), y: Math.min(child.height, Math.max(0, y)) };
35
+ };
36
+ const onPointerDown = (event) => {
37
+ if (event.button !== 0)
38
+ return;
39
+ start.current = local(event);
40
+ trail.current = [start.current];
41
+ dragged.current = false;
42
+ event.currentTarget.setPointerCapture?.(event.pointerId);
43
+ };
44
+ const onPointerMove = (event) => {
45
+ const from = start.current;
46
+ if (!from)
47
+ return;
48
+ const at = local(event);
49
+ if (!dragged.current && Math.hypot(at.x - from.x, at.y - from.y) < DRAG_FLOOR)
50
+ return;
51
+ dragged.current = true;
52
+ const last = trail.current[trail.current.length - 1] ?? from;
53
+ if (shape === "box")
54
+ trail.current = [from, at];
55
+ else if (Math.hypot(at.x - last.x, at.y - last.y) >= VERTEX_GAP)
56
+ trail.current = [...trail.current, at];
57
+ setPath(trail.current);
58
+ };
59
+ const onPointerUp = (event) => {
60
+ const from = start.current;
61
+ start.current = null;
62
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
63
+ if (!from)
64
+ return;
65
+ setPath(null);
66
+ if (!dragged.current) {
67
+ if (held) {
68
+ setHeld(null);
69
+ onBrush?.(null);
70
+ }
71
+ return;
72
+ }
73
+ /* The region ends where the hand lets go. */
74
+ const end = local(event);
75
+ if (onRegion) {
76
+ onRegion([from, end]);
77
+ return;
78
+ }
79
+ const region = shape === "box" ? [from, end] : [...trail.current, end];
80
+ const brushed = brushedOf(traces, shape, region, { scale: child.x, invert: child.xInvert, step: child.xStep }, { scale: child.y, invert: child.yInvert, step: child.yStep }, { spec, keyField, transposed });
81
+ setHeld(brushed.region);
82
+ onBrush?.(brushed);
83
+ };
84
+ /* A press the browser cancels, a touch scroll or a stolen pointer, leaves no region. */
85
+ const onPointerCancel = () => {
86
+ start.current = null;
87
+ setPath(null);
88
+ };
89
+ /* The click a drag ends on belongs to the drag. A geom under the hand does not take it. */
90
+ const swallow = (event) => {
91
+ if (dragged.current)
92
+ event.stopPropagation();
93
+ };
94
+ /* The held region, back through the scales the panel draws with now. */
95
+ const place = (at) => transposed ? { x: child.x(at.y), y: child.y(at.x) } : { x: child.x(at.x), y: child.y(at.y) };
96
+ const outline = path ?? held?.map(place) ?? null;
97
+ return (_jsxs("g", { "data-brush": onRegion ? "zoom" : shape, style: { cursor: "crosshair" }, onPointerDown: onPointerDown, onPointerMove: onPointerMove, onPointerUp: onPointerUp, onPointerCancel: onPointerCancel, onClickCapture: swallow, children: [_jsx("rect", { ref: area, width: child.width, height: child.height, fill: "transparent" }), children, outline && outline.length > 1 && (_jsx("path", { "data-brush-region": "", d: outlineOf(shape, outline), fill: "var(--viz-ink)", fillOpacity: 0.06, stroke: "var(--viz-ink)", strokeOpacity: 0.6, strokeDasharray: "4 3", pointerEvents: "none" }))] }));
98
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What a fill stands for.
3
+ *
4
+ * A bar and not a row of swatches, which is where this parts from `SizeLegend`. That one draws three
5
+ * circles because area is judged against a neighbor and cannot be read off a gradient. Color is the
6
+ * channel a reader does judge against a gradient, so the map draws continuously and the numbers sit
7
+ * under it.
8
+ *
9
+ * Cuts are the exception: an author who binned the map into steps drew a scale with edges, and a
10
+ * gradient would say the values between two cuts differ when the figure has drawn them alike.
11
+ *
12
+ * The ramp takes a value in its own units, the same contract `Trace.ramp` states, so this samples the
13
+ * figure's own mapping instead of reproducing it. A legend that recomputed the scale is a second
14
+ * answer to the question the geoms already answered.
15
+ *
16
+ * Which numbers get named is the author's where they say so. Absent that it is the two ends and the
17
+ * middle, or every cut on a binned map, which is what a reader needs to place a color and no more.
18
+ */
19
+ import type { ValueRamp } from "../core/internal.js";
20
+ export interface ColorLegendProps {
21
+ /** The measure's name, with its unit where it carries one. */
22
+ label: string;
23
+ /** The two ends the map runs between, in the measure's own units. */
24
+ domain: [number, number];
25
+ /** The figure's own mapping, taking a value in its own units. */
26
+ ramp: ValueRamp;
27
+ /** Where the map's neutral sits, drawn as a labeled tick. Absent on a one-armed map. */
28
+ center?: number;
29
+ /** Cuts that binned the map. Draws blocks and their edges in place of a gradient. */
30
+ breaks?: readonly number[];
31
+ /**
32
+ * Values named under the bar, each written as its own label or through `format`.
33
+ *
34
+ * Placed at the value's own position along the bar instead of spread evenly, which is what makes
35
+ * a named threshold sit where the color changes. Absent falls back to the ends and the middle, or
36
+ * to the cuts on a binned map.
37
+ */
38
+ ticks?: {
39
+ at: number;
40
+ label?: string;
41
+ }[];
42
+ /** Formats a value the way the axis and the readout do. */
43
+ format?: (value: number) => string;
44
+ }
45
+ export declare function ColorLegend({ label, domain, ramp, center, breaks, ticks, format }: ColorLegendProps): import("react").JSX.Element;
@@ -0,0 +1,64 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * What a fill stands for.
4
+ *
5
+ * A bar and not a row of swatches, which is where this parts from `SizeLegend`. That one draws three
6
+ * circles because area is judged against a neighbor and cannot be read off a gradient. Color is the
7
+ * channel a reader does judge against a gradient, so the map draws continuously and the numbers sit
8
+ * under it.
9
+ *
10
+ * Cuts are the exception: an author who binned the map into steps drew a scale with edges, and a
11
+ * gradient would say the values between two cuts differ when the figure has drawn them alike.
12
+ *
13
+ * The ramp takes a value in its own units, the same contract `Trace.ramp` states, so this samples the
14
+ * figure's own mapping instead of reproducing it. A legend that recomputed the scale is a second
15
+ * answer to the question the geoms already answered.
16
+ *
17
+ * Which numbers get named is the author's where they say so. Absent that it is the two ends and the
18
+ * middle, or every cut on a binned map, which is what a reader needs to place a color and no more.
19
+ */
20
+ import { useId } from "react";
21
+ /** Tabular figures, so a column of numbers lines up on the digit. */
22
+ const TABULAR = { fontVariantNumeric: "tabular-nums" };
23
+ /** Samples across the bar. Enough that no band of the map is wider than a pixel or two at this size. */
24
+ const STOPS = 24;
25
+ const BAR_W = 132;
26
+ const BAR_H = 10;
27
+ export function ColorLegend({ label, domain, ramp, center, breaks, ticks, format }) {
28
+ const gradientId = useId();
29
+ const [lo, hi] = domain;
30
+ const say = format ?? ((value) => value.toLocaleString(undefined, { maximumSignificantDigits: 3 }));
31
+ /* Where a value sits along the bar. A binned bar gives each block one width, and a value sits inside its own block. */
32
+ const placeOf = (at) => {
33
+ if (!breaks || breaks.length < 2)
34
+ return hi === lo ? 0.5 : (at - lo) / (hi - lo);
35
+ const bins = breaks.length - 1;
36
+ let bin = 0;
37
+ while (bin < bins - 1 && at > breaks[bin + 1])
38
+ bin += 1;
39
+ const [from, to] = [breaks[bin], breaks[bin + 1]];
40
+ return (bin + (to === from ? 0 : (at - from) / (to - from))) / bins;
41
+ };
42
+ /* Named values sit where their color does, so a threshold label lands on the step it names. */
43
+ const named = ticks && ticks.length > 0 ? (_jsx("span", { className: "relative block", style: { width: BAR_W, height: "1em" }, children: ticks.map(({ at, label: written }) => (_jsx("span", { className: "absolute text-2xs text-muted-foreground", style: {
44
+ fontVariantNumeric: "tabular-nums",
45
+ left: `${Math.min(100, Math.max(0, placeOf(at) * 100))}%`,
46
+ transform: "translateX(-50%)",
47
+ whiteSpace: "nowrap",
48
+ }, children: written ?? say(at) }, at))) })) : null;
49
+ if (breaks && breaks.length > 1) {
50
+ const bins = breaks.length - 1;
51
+ return (_jsxs("div", { className: "contents", children: [_jsx("span", { className: "text-xs text-muted-foreground", children: label }), _jsxs("span", { className: "flex min-w-0 flex-col gap-1", children: [_jsx("svg", { width: BAR_W, height: BAR_H, "aria-hidden": true, children: Array.from({ length: bins }, (_, bin) => {
52
+ const width = BAR_W / bins;
53
+ /* Sampled inside the bin, so the block draws the color the cells in it drew. */
54
+ const inside = (breaks[bin] + breaks[bin + 1]) / 2;
55
+ return _jsx("rect", { x: bin * width, y: 0, width: width, height: BAR_H, fill: ramp(inside) }, bin);
56
+ }) }), named ?? (_jsx("span", { className: "flex justify-between", style: { width: BAR_W }, children: breaks.map((cut) => (_jsx("span", { className: "text-2xs text-muted-foreground", style: TABULAR, children: say(cut) }, cut))) }))] })] }));
57
+ }
58
+ /* A neutral is the third number worth naming, and it sits where the map's own middle is. */
59
+ const geoms = center != null && center > lo && center < hi ? [lo, center, hi] : [lo, (lo + hi) / 2, hi];
60
+ return (_jsxs("div", { className: "contents", children: [_jsx("span", { className: "text-xs text-muted-foreground", children: label }), _jsxs("span", { className: "flex min-w-0 flex-col gap-1", children: [_jsxs("svg", { width: BAR_W, height: BAR_H, "aria-hidden": true, children: [_jsx("defs", { children: _jsx("linearGradient", { id: gradientId, x1: "0", x2: "1", y1: "0", y2: "0", children: Array.from({ length: STOPS }, (_, step) => {
61
+ const t = step / (STOPS - 1);
62
+ return _jsx("stop", { offset: t, stopColor: ramp(lo + (hi - lo) * t) }, step);
63
+ }) }) }), _jsx("rect", { x: 0, y: 0, width: BAR_W, height: BAR_H, fill: `url(#${gradientId})` })] }), named ?? (_jsx("span", { className: "flex justify-between", style: { width: BAR_W }, children: geoms.map((value, index) => (_jsx("span", { className: "text-2xs text-muted-foreground", style: TABULAR, children: say(value) }, `${index}-${value}`))) }))] })] }));
64
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Figure chrome: headline, subtitle, caption.
3
+ *
4
+ * Held apart from the axis frame because a sankey, a span track, and a treemap want the same
5
+ * chrome and no axes. The headline is a sentence stating the claim instead of a restatement of
6
+ * the axis labels, and the caption carries provenance plus any geom substitution, so a reader
7
+ * who thinks they are looking at individual records is corrected in place.
8
+ */
9
+ import type { ReactNode } from "react";
10
+ export interface FigureProps {
11
+ headline?: string;
12
+ subtitle?: string;
13
+ /** The footer line: provenance, and what the figure admits. */
14
+ caption?: string;
15
+ /** A control on the footer line, for what the note can state but not hold. */
16
+ aside?: ReactNode;
17
+ children: ReactNode;
18
+ }
19
+ export declare function Figure({ headline, subtitle, caption, aside, children }: FigureProps): import("react").JSX.Element;
@@ -0,0 +1,6 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /** The 6px rhythm the kit prebuilt sheet does not carry. */
3
+ const GAP_1_5 = { gap: 6 };
4
+ export function Figure({ headline, subtitle, caption, aside, children }) {
5
+ return (_jsxs("figure", { className: "m-0 flex flex-col gap-1", children: [headline && _jsx("figcaption", { className: "text-xl font-semibold", children: headline }), subtitle && _jsx("span", { className: "text-sm text-muted-foreground", children: subtitle }), children, (caption || aside) && (_jsxs("div", { className: "flex min-w-0 items-center", style: GAP_1_5, children: [caption && _jsx("span", { className: "text-2xs min-w-0 text-muted-foreground", children: caption }), aside] }))] }));
6
+ }