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

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 +28 -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,1432 @@
1
+ /**
2
+ * Turns built layers into the axes, scales and footer.
3
+ *
4
+ * Faceting partitions one plot into panels and each panel derives its own axes. The fit footer
5
+ * stays apart from the build.
6
+ */
7
+ import { boundsOf } from "./aggregate.js";
8
+ import { buildLayers, categoriesOf, colorDomainOf, colorScaleOf, drawsAxes, drawsOneColor, rampOptionsFor, sizeRadius, valueRamp, horizontalTransform, verticalTransform, rowsByValue, viewOf, } from "./layers.js";
9
+ import { OMITTED_KINDS, omit, omissionLine, omittedCount } from "./omission.js";
10
+ import { flooredCount, placeTraces } from "./bounds.js";
11
+ import { ruleSegment } from "./rules.js";
12
+ import { matrixFor, orderBand, reducedCells } from "./band-order.js";
13
+ import { transposed } from "./cluster.js";
14
+ import { trackFor, trackOverFields } from "./side-track.js";
15
+ import { marginalBins, valuesAlong, valuesByLevel } from "./marginal.js";
16
+ import { geomColor, paintAesthetic, paintColumn } from "./geom-table.js";
17
+ import { groundedGeoms } from "./grammar.js";
18
+ import { isLog, TRANSFORMS, transformOf } from "./transform.js";
19
+ import { REGULAR } from "./sizing.js";
20
+ import { anyRange, keptLines } from "./brush.js";
21
+ import { chooseLabels } from "./labels.js";
22
+ import { readOnce } from "./plot-data.js";
23
+ import { tickFormatter } from "./tick-format.js";
24
+ import { positionArgs, } from "./spec.js";
25
+ import { axisRoom, buildAxis, isBand, longestOf as longestLabel, TITLE_PAD, } from "./frame-geometry.js";
26
+ /** Series counts above this draw translucent, per chart-design rule 7. */
27
+ export const FADE_ABOVE = 1_500;
28
+ /**
29
+ * Where a scatter moves from SVG to the GPU.
30
+ *
31
+ * The path strings break first. A quarter of a million geoms is megabytes of string per recolor.
32
+ */
33
+ export const GL_ABOVE = 15_000;
34
+ /**
35
+ * Which of the three treatments a count asks for.
36
+ *
37
+ * One function. The renderer picking a treatment and the footer stating it read one threshold.
38
+ */
39
+ export const treatmentOf = (count) => count > GL_ABOVE ? "binned" : count > FADE_ABOVE ? "faded" : "points";
40
+ /**
41
+ * Records the frame is holding as individual geoms.
42
+ *
43
+ * Counted over point traces alone. A trace drawing a hexbin came from a density kind.
44
+ */
45
+ export const pointCount = (frame) => frame.traces.reduce((total, trace) => total + (trace.data.at === "records" && trace.data.geom === "point" ? trace.data.points.length : 0), 0);
46
+ /**
47
+ * Whether two reports say the same thing.
48
+ *
49
+ * A geom reports from an effect and the answer is a fresh object each firing. The comparison
50
+ * reads what was said.
51
+ */
52
+ export const sameSubstitution = (a, b) => a === b || (a != null && b != null && a.drew === b.drew && a.cells === b.cells && a.rows === b.rows);
53
+ /** Categories drawn before the labels stop fitting under the axis. */
54
+ export const CATEGORY_CAP = 60;
55
+ /**
56
+ * Categories a content-sized figure draws.
57
+ *
58
+ * A stated band size decides the plot area and the figure grows to hold it. What runs out is the
59
+ * document.
60
+ */
61
+ export const GROWN_CAP = 1000;
62
+ /**
63
+ * Categories this band draws.
64
+ *
65
+ * `CLUSTER_CAP` is what the clustering affords and runs lower. A band between the two draws its
66
+ * rows unordered.
67
+ */
68
+ const bandCap = (plot) => (plot.sizing === "content" ? GROWN_CAP : CATEGORY_CAP);
69
+ /**
70
+ * Both bands' orders, read off the traces' grid cells.
71
+ *
72
+ * One matrix serves both axes. Its rows are the vertical band and the horizontal order clusters
73
+ * the transpose.
74
+ */
75
+ function orderBands(plot, categories, stacked, traces, metrics) {
76
+ const cells = traces.flatMap((trace) => trace.data.at === "groups" && trace.data.geom === "heatmap" ? trace.data.cells : []);
77
+ const grid = () => matrixFor(cells, stacked, categories);
78
+ const down = orderBand(plot.scales?.y?.order, stacked, grid);
79
+ const across = orderBand(plot.scales?.x?.order, categories, down.reduced
80
+ ? () => null
81
+ : () => {
82
+ const built = grid();
83
+ return built ? transposed(built) : null;
84
+ });
85
+ const refused = [];
86
+ if (down.refused)
87
+ refused.push({ axis: "y", ...down.refused });
88
+ if (across.refused)
89
+ refused.push({ axis: "x", ...across.refused });
90
+ const reduced = down.reduced
91
+ ? { of: down.reduced, along: "y" }
92
+ : across.reduced
93
+ ? { of: across.reduced, along: "x" }
94
+ : undefined;
95
+ return { x: across, y: down, gapSize: metrics.gap, refused, reduced };
96
+ }
97
+ /** The grid traces rewritten onto the centroids a kmeans order produced. */
98
+ function reduceGrids(traces, reduced) {
99
+ return traces.map((trace) => trace.data.at === "groups" && trace.data.geom === "heatmap"
100
+ ? { ...trace, data: { ...trace.data, cells: reducedCells(trace.data.cells, reduced.of, reduced.along) } }
101
+ : trace);
102
+ }
103
+ /**
104
+ * Confidence bands drawn before they stop being readable.
105
+ *
106
+ * Translucent areas compound. Forty of them stack into a solid wash. Past this the curves draw
107
+ * alone and the footer reports it.
108
+ */
109
+ export const BAND_LIMIT = 12;
110
+ const ANCHOR = {
111
+ left: "start",
112
+ center: "middle",
113
+ right: "end",
114
+ };
115
+ export const axisLabel = (field) => field ? (field.unit ? `${field.label} (${field.unit})` : field.label) : undefined;
116
+ /**
117
+ * What the vertical scale measures once a fill has divided it.
118
+ *
119
+ * The geoms are shares of each band's total, stopping at one. A percentage is `scales.y.format`.
120
+ */
121
+ const shareLabel = (field) => field ? `Share of ${field.label}` : undefined;
122
+ /** Characters a number takes at the tick, for the margin a value scale needs before its ticks exist. */
123
+ const NUMBER_CHARS = 6;
124
+ /**
125
+ * How this axis draws itself -- what the author set, then the panel's size.
126
+ *
127
+ * The tick length and type size resolve here. `axisRoom` and `buildAxis` both read them.
128
+ */
129
+ const chromeOf = (axis, metrics) => ({
130
+ lineWidth: axis?.linewidth,
131
+ tickLength: axis?.tickLength ?? metrics.tickLength,
132
+ tickSide: axis?.tickSide,
133
+ tickAngle: axis?.tickAngle,
134
+ titleAlign: axis?.titleAlign,
135
+ fontSize: axis?.fontSize ?? metrics.axis,
136
+ ink: axis?.ink,
137
+ grid: axis?.grid,
138
+ minorGrid: axis?.minorGrid,
139
+ });
140
+ /* The drawn text. A renamed category is what the margin has to fit. */
141
+ const longestOf = (spec) => spec.values.reduce((most, value) => Math.max(most, (spec.names?.[value] ?? value).length), 0);
142
+ /* A value scale's ticks as drawn, where it names any. A number takes the nominal width. */
143
+ const valueLongest = (spec, ticks) => spec.names ? Math.max(NUMBER_CHARS, longestLabel(buildAxis(spec, [0, 1], ticks, "end"))) : NUMBER_CHARS;
144
+ /**
145
+ * Room one axis takes outside the plot area.
146
+ *
147
+ * The chrome decides it. A label turned ninety degrees reaches its own length. A value scale
148
+ * takes a nominal width.
149
+ */
150
+ const roomFor = (spec, axis, hasTitle, ticks) => axisRoom(spec, axis, isBand(spec) ? longestOf(spec) : valueLongest(spec, ticks), hasTitle);
151
+ /**
152
+ * Points a trace holds, for records on the frame's own pair of scales.
153
+ *
154
+ * A reduction holds groups. A parallel trace draws across its own rules. A band has two bounds.
155
+ */
156
+ export const pointsOf = (trace) => trace.data.at === "records" && "points" in trace.data ? trace.data.points : [];
157
+ /** Whether a value lies inside a domain, whichever way round the domain runs. */
158
+ const within = (value, [a, b]) => value >= Math.min(a, b) && value <= Math.max(a, b);
159
+ /** Splits an expansion into its two ends, the low end first. */
160
+ const ends = (value) => typeof value === "number" ? [value, value] : value;
161
+ /**
162
+ * Pads the data's reach at each end in transformed space. ggplot's `expand`.
163
+ *
164
+ * The default is a fifth each end on a log axis and a twentieth of the span elsewhere.
165
+ */
166
+ function pad(lo, hi, transform = "identity", expand) {
167
+ const log = isLog(transform);
168
+ if (log && !expand) {
169
+ const top = hi > 0 ? hi * 1.25 : 1;
170
+ /* A non-positive low has no place on a log axis. Three decades under the top is the floor,
171
+ which keeps the readings that do fit spread across it. */
172
+ return [lo > 0 ? lo * 0.8 : top / 1000, top];
173
+ }
174
+ const { forward, back } = TRANSFORMS[transform];
175
+ const a = forward(log && !(lo > 0) ? (hi > 0 ? hi : 1) / 1000 : lo);
176
+ const b = forward(log && !(hi > 0) ? 1 : hi);
177
+ const span = b - a;
178
+ // One distinct value would otherwise give a zero-width domain, mapping each geom to one pixel.
179
+ if (span === 0)
180
+ return [back(a - 1), back(b + 1)];
181
+ const [multLo, multHi] = ends(expand?.mult ?? 0.05);
182
+ const [addLo, addHi] = ends(expand?.add ?? 0);
183
+ return [back(a - span * multLo - addLo), back(b + span * multHi + addHi)];
184
+ }
185
+ /** A stated pair of ends as the axis holds it, a copy of the spec's own. */
186
+ const copied = (limits) => limits && [limits[0], limits[1]];
187
+ /** An extent widened to the values an axis must reach. ggplot's `expand_limits`. */
188
+ function reaching(extent, include, transform) {
189
+ const admitted = (include ?? []).filter(TRANSFORMS[transform].admits);
190
+ if (admitted.length === 0)
191
+ return extent;
192
+ const [lo, hi] = boundsOf(admitted);
193
+ return [Math.min(extent[0], lo), Math.max(extent[1], hi)];
194
+ }
195
+ /** Copies the stated scale arguments of an axis onto its spec. */
196
+ const scaleOf = (options) => Object.fromEntries(Object.entries({
197
+ transform: options?.transform,
198
+ reverse: options?.reverse,
199
+ breaks: options?.breaks,
200
+ minorBreaks: options?.minorBreaks,
201
+ names: options?.labels,
202
+ timezone: options?.timezone,
203
+ }).filter(([, value]) => value !== undefined));
204
+ /** What a stated `oob` asks of the scale. `keep` frees the clamp, and `squish` pins readings to the range. */
205
+ const oobOf = (options) => options?.oob === "keep"
206
+ ? { clamp: false }
207
+ : options?.oob === "squish" && options.limits
208
+ ? { squish: [options.limits[0], options.limits[1]] }
209
+ : {};
210
+ /** Vertical reach of one trace, whichever geom it draws. A transform reads the part it places. */
211
+ function verticalExtent(trace, transform = "identity") {
212
+ const { admits } = TRANSFORMS[transform];
213
+ let lo = Infinity;
214
+ let hi = -Infinity;
215
+ const see = (value) => {
216
+ if (!admits(value))
217
+ return;
218
+ if (value < lo)
219
+ lo = value;
220
+ if (value > hi)
221
+ hi = value;
222
+ };
223
+ if (trace.data.at === "records") {
224
+ // Each rule takes its own range. The frame has none to build.
225
+ if (trace.data.geom === "parcoords" || trace.data.geom === "radar")
226
+ return null;
227
+ // A band reaches both bounds, and the scale has to hold the whole region or it draws clipped.
228
+ if (trace.data.geom === "ribbon" || trace.data.geom === "range") {
229
+ for (const reading of trace.data.readings) {
230
+ see(reading.lo);
231
+ see(reading.hi);
232
+ }
233
+ }
234
+ else if (trace.data.geom === "segment") {
235
+ // A segment travels. The scale takes both ends.
236
+ for (const segment of trace.data.segments) {
237
+ see(segment.y);
238
+ see(segment.yEnd);
239
+ }
240
+ }
241
+ else if ("points" in trace.data) {
242
+ for (const point of trace.data.points)
243
+ see(point.y);
244
+ }
245
+ else {
246
+ /* A reference line leaves the scales alone, as ggplot's reference geoms do. */
247
+ return null;
248
+ }
249
+ }
250
+ else if (trace.data.geom === "boxplot") {
251
+ for (const box of trace.data.boxes) {
252
+ see(box.lo);
253
+ see(box.hi);
254
+ for (const outlier of box.outliers)
255
+ see(outlier);
256
+ }
257
+ }
258
+ else if (trace.data.geom === "violin") {
259
+ // The outline reaches the ends of the grid, which run past the whiskers a box would stop at.
260
+ for (const violin of trace.data.violins) {
261
+ see(violin.grid[0]);
262
+ see(violin.grid[violin.grid.length - 1]);
263
+ }
264
+ }
265
+ else if (trace.data.geom === "density") {
266
+ /* The curve reads a density from zero. The scale takes the baseline and the peak. */
267
+ see(0);
268
+ for (const value of trace.data.curve.weight)
269
+ see(value);
270
+ }
271
+ else if (trace.data.geom === "sankey" ||
272
+ trace.data.geom === "chord" ||
273
+ trace.data.geom === "ideogram" ||
274
+ trace.data.geom === "heatmap" ||
275
+ trace.data.geom === "treemap" ||
276
+ trace.data.geom === "icicle" ||
277
+ trace.data.geom === "sunburst" ||
278
+ trace.data.geom === "gauge" ||
279
+ "mesh" in trace.data ||
280
+ "field" in trace.data) {
281
+ // None reads the frame's vertical scale and none contributes a domain.
282
+ return null;
283
+ }
284
+ else {
285
+ // All four are read against the baseline. A domain starting higher overstates them.
286
+ if (trace.data.geom === "bar" ||
287
+ trace.data.geom === "waterfall" ||
288
+ trace.data.geom === "area" ||
289
+ trace.data.geom === "freqpoly") {
290
+ see(0);
291
+ }
292
+ for (const bar of trace.data.bars) {
293
+ // A stacked segment's reach is its own top, and its floor is where the one below it ended.
294
+ see(bar.value + (bar.floor ?? 0));
295
+ if (bar.floor != null)
296
+ see(bar.floor);
297
+ // A whisker reaches past its bar, and a scale stopping at the bar draws the top of it flat.
298
+ if (bar.error != null) {
299
+ see(bar.value + bar.error);
300
+ see(bar.value - bar.error);
301
+ }
302
+ }
303
+ }
304
+ return Number.isFinite(lo) ? [lo, hi] : null;
305
+ }
306
+ /**
307
+ * The plot's annotations, in the shapes `Frame` draws.
308
+ *
309
+ * An author names the data and a transpose swaps here.
310
+ */
311
+ function annotationLayers(annotations, swapped = false) {
312
+ const axisEnds = [];
313
+ const notes = [];
314
+ annotations.forEach((annotation, source) => {
315
+ const drawnOn = (axis) => (swapped ? (axis === "x" ? "y" : "x") : axis);
316
+ if (annotation.kind === "axis-end") {
317
+ axisEnds.push({ axis: drawnOn(annotation.axis), end: annotation.end, text: annotation.text });
318
+ }
319
+ else if (annotation.kind === "note") {
320
+ notes.push({
321
+ text: annotation.text,
322
+ at: swapped ? { x: annotation.at.y, y: annotation.at.x } : annotation.at,
323
+ toward: annotation.leader?.toward,
324
+ // The spec speaks in reading directions and SVG speaks in text anchors.
325
+ align: ANCHOR[annotation.align ?? "left"],
326
+ /* The kinds share one list. A note keeps its position there, and a drag writes to it. */
327
+ source,
328
+ });
329
+ }
330
+ });
331
+ return { axisEnds, notes };
332
+ }
333
+ /** A line trace's last reading, where a direct label would draw. Absent on any other trace. */
334
+ const lastReading = (trace) => trace.data.at === "records" && trace.data.geom === "line"
335
+ ? trace.data.points[trace.data.points.length - 1]?.y
336
+ : undefined;
337
+ /** The traces with the lines in the order their last readings stand, top first. The rest keep their places. */
338
+ function byLastReading(traces) {
339
+ const lines = traces.filter((trace) => lastReading(trace) != null);
340
+ const sorted = [...lines].sort((a, b) => lastReading(b) - lastReading(a));
341
+ let next = 0;
342
+ return traces.map((trace) => (lastReading(trace) != null ? sorted[next++] : trace));
343
+ }
344
+ /**
345
+ * What the legend names -- a split value, or a series.
346
+ *
347
+ * Two series over one split field draw the same color for one value. They share a row. `geoms`
348
+ * order reads the lines the way they end.
349
+ */
350
+ export function legendRows(traces, order = "authoring") {
351
+ const rows = new Map();
352
+ for (const trace of order === "geoms" ? byLastReading(traces) : traces) {
353
+ if (trace.showLegend === false)
354
+ continue;
355
+ /*
356
+ A bound identity channel names its categories.
357
+
358
+ Keyed on the field and the value, the key a split already uses. A figure that splits and
359
+ colors lists one value once.
360
+ */
361
+ if (trace.colorLevels && trace.colorField) {
362
+ for (const { value, code } of trace.colorLevels) {
363
+ const levelKey = `${trace.colorField.id}:${value}`;
364
+ if (rows.has(levelKey))
365
+ continue;
366
+ rows.set(levelKey, { key: levelKey, label: value, color: trace.ramp(code) });
367
+ }
368
+ continue;
369
+ }
370
+ /* A group names nothing a reader looks up. Its series takes one row. */
371
+ const whole = trace.splitValue == null || trace.grouped === true;
372
+ const key = trace.grouped ? trace.layerId : whole ? trace.id : `${trace.splitField?.id}:${trace.splitValue}`;
373
+ if (rows.has(key))
374
+ continue;
375
+ rows.set(key, {
376
+ key,
377
+ label: whole ? trace.name : (trace.splitValue ?? trace.name),
378
+ color: trace.color,
379
+ right: whole && trace.axis === "y2" ? true : undefined,
380
+ });
381
+ }
382
+ return [...rows.values()];
383
+ }
384
+ /**
385
+ * Curves belonging to one trace.
386
+ *
387
+ * A split fits per value and `curvesByGroup` names each curve after its value. An unsplit series
388
+ * takes them all.
389
+ */
390
+ export function fitsFor(trace, fitted, panel) {
391
+ const found = fitted.byLayer.get(trace.layerId);
392
+ if (!found)
393
+ return [];
394
+ /*
395
+ Two filters, each skipped where it has nothing to say. An unsplit trace takes whatever came
396
+ back for its series. A panel is matched where the caller named one.
397
+ */
398
+ return found.fits.filter((fit) => (panel === undefined || (fit.panel ?? "") === panel) && (trace.splitValue == null || fit.id === trace.splitValue));
399
+ }
400
+ /**
401
+ * Curves the frame will draw.
402
+ *
403
+ * The service fits per split value and the trace cap keeps two dozen. A count off the response
404
+ * says 41 where the reader sees 24.
405
+ */
406
+ export const drawnFits = (traces, fitted) => traces.flatMap((trace) => fitsFor(trace, fitted));
407
+ const empty = (title, reason) => ({ status: "empty", title, reason });
408
+ export function buildFrame(plot, data, { palettes: palette, metrics = REGULAR, pinned, facet }) {
409
+ const fieldAt = new Map(data.fields.map((field) => [field.id, field]));
410
+ const { traces: built, axisKind, xField, fields, unbuilt, omitted, } = buildLayers(plot, data, { palettes: palette, pinned, metrics, facet });
411
+ /* A layer's own columns join the lookup. A readout and the critic find their names there. */
412
+ for (const field of fields)
413
+ fieldAt.set(field.id, field);
414
+ /* A flow binds its own ends. An unbound X refuses the geoms that read one. */
415
+ const axisFree = built.length > 0 && built.every((trace) => !drawsAxes(trace.data.geom));
416
+ if (!xField && !axisFree) {
417
+ return empty("X not bound", "Pick a field for the horizontal axis.");
418
+ }
419
+ if (built.length === 0) {
420
+ if (unbuilt.length > 0) {
421
+ return empty(`${unbuilt[0]} is no kind this version draws`, "Pick one of the kinds in KINDS.");
422
+ }
423
+ return empty("Nothing to plot", "No series carries both a bound measure and rows to draw.");
424
+ }
425
+ // A shared axis takes the log setting of the first measure on it. The author picked the pair.
426
+ const leftField = (built.find((trace) => trace.axis !== "y2") ?? built[0]).field;
427
+ const rightField = built.find((trace) => trace.axis === "y2")?.field;
428
+ /*
429
+ A bar and an area read as a length from zero and the axis starts there. Neither takes a log
430
+ scale. The `proportional` column of `GRAMMAR` answers this.
431
+ */
432
+ const grounded = groundedGeoms(built.map((trace) => trace.data.geom));
433
+ const xTransform = horizontalTransform(plot, xField);
434
+ const yTransform = verticalTransform(plot.scales?.y?.transform, leftField?.logScale, grounded);
435
+ const rightTransform = verticalTransform(plot.scales?.y2?.transform, rightField?.logScale, grounded);
436
+ /* Each reading placed against the axes before any extent is read. The footer counts what dropped. */
437
+ const boundsOf = (options, transform) => ({
438
+ transform,
439
+ range: options?.limits,
440
+ oob: options?.oob ?? "censor",
441
+ });
442
+ const placed = placeTraces(built, axisKind === "continuous" ? boundsOf(plot.scales?.x, xTransform) : null, boundsOf(plot.scales?.y, yTransform), boundsOf(plot.scales?.y2, rightTransform));
443
+ const traces = placed.traces;
444
+ const left = traces.filter((trace) => trace.axis !== "y2");
445
+ const right = traces.filter((trace) => trace.axis === "y2");
446
+ const spanOf = (group, transform) => {
447
+ let lo = Infinity;
448
+ let hi = -Infinity;
449
+ for (const trace of group) {
450
+ const extent = verticalExtent(trace, transform);
451
+ if (!extent)
452
+ continue;
453
+ lo = Math.min(lo, extent[0]);
454
+ hi = Math.max(hi, extent[1]);
455
+ }
456
+ return Number.isFinite(lo) ? [lo, hi] : null;
457
+ };
458
+ /*
459
+ A frame with no vertical reach still needs a domain to hand `Frame`.
460
+
461
+ A flow reports no extent and the span comes back null. The unit interval stays undrawn.
462
+ */
463
+ const leftExtent = reaching(spanOf(left.length > 0 ? left : traces, yTransform) ?? [0, 1], plot.scales?.y?.include, yTransform);
464
+ const rightExtent = right.length > 0 ? spanOf(right, rightTransform) : null;
465
+ /*
466
+ Whether the geoms on the left scale are shares of their band.
467
+
468
+ Read over the traces on that axis. A fill adjusts the group that named it.
469
+ */
470
+ const leftShares = (left.length > 0 ? left : traces).length > 0 &&
471
+ (left.length > 0 ? left : traces).every((trace) => trace.data.at === "groups" && "bars" in trace.data && trace.data.shares === true);
472
+ const grouped = traces.filter((trace) => trace.data.at === "groups");
473
+ const categories = [];
474
+ let hiddenCategories = 0;
475
+ /*
476
+ Categories come from the banded traces, ordered by the first one's values.
477
+
478
+ Largest first. An unordered dimension has no order of its own.
479
+ */
480
+ /*
481
+ Nothing grouped means nothing to band. An empty category set is a different thing.
482
+
483
+ A parallel plot binds no X and the axis kind falls back to bands over records.
484
+ */
485
+ if (axisKind === "band" && traces.length > 0) {
486
+ /*
487
+ How far each band reaches, over each trace reaching into it.
488
+
489
+ `floor + value` is the top of a segment. A stack takes the total.
490
+ */
491
+ const tops = new Map();
492
+ for (const trace of grouped) {
493
+ if (trace.data.at !== "groups")
494
+ continue;
495
+ if (trace.data.geom !== "bar")
496
+ continue;
497
+ for (const bar of trace.data.bars) {
498
+ const top = (bar.floor ?? 0) + bar.value;
499
+ tops.set(bar.category, Math.max(tops.get(bar.category) ?? -Infinity, top));
500
+ }
501
+ }
502
+ /* Each trace. A record geom names its band the way a reduction names its groups. */
503
+ const ranked = [];
504
+ const seen = new Set();
505
+ for (const trace of traces) {
506
+ for (const category of categoriesOf(trace)) {
507
+ if (seen.has(category))
508
+ continue;
509
+ seen.add(category);
510
+ ranked.push(category);
511
+ }
512
+ }
513
+ /*
514
+ A distribution has no single value to rank by and keeps its read order. A line and a running
515
+ total read as a sequence. The sort is stable.
516
+ */
517
+ const running = grouped.some((trace) => "bars" in trace.data && trace.data.cumulative === true);
518
+ /* A wiggle baseline walks the read order. The band keeps that order. */
519
+ const wiggled = plot.layers.some((layer) => positionArgs(layer.position).offset === "wiggle");
520
+ if (tops.size > 0 && !running && !wiggled)
521
+ ranked.sort((a, b) => (tops.get(b) ?? -Infinity) - (tops.get(a) ?? -Infinity));
522
+ categories.push(...ranked.slice(0, bandCap(plot)));
523
+ hiddenCategories = ranked.length - categories.length;
524
+ }
525
+ if (axisKind === "band" && categories.length === 0 && xField) {
526
+ return empty("No categories", `Nothing in these rows carries a value for ${xField.label}.`);
527
+ }
528
+ /* A binned bar reaches half a bin past its center. The domain covers the geom. */
529
+ const horizontalExtent = () => {
530
+ let lo = Infinity;
531
+ let hi = -Infinity;
532
+ const see = (value) => {
533
+ if (!TRANSFORMS[xTransform].admits(value))
534
+ return;
535
+ if (value < lo)
536
+ lo = value;
537
+ if (value > hi)
538
+ hi = value;
539
+ };
540
+ for (const trace of traces) {
541
+ for (const point of pointsOf(trace))
542
+ see(point.x);
543
+ if (trace.data.geom === "bar" || trace.data.geom === "area" || trace.data.geom === "freqpoly") {
544
+ const half = (trace.data.binWidth ?? 0) / 2;
545
+ for (const bar of trace.data.bars) {
546
+ if (bar.at == null)
547
+ continue;
548
+ see(bar.at - half);
549
+ see(bar.at + half);
550
+ }
551
+ }
552
+ /* A curve reaching past the data needs the whole grid, or the tails draw clipped. */
553
+ if (trace.data.geom === "density") {
554
+ for (const at of trace.data.curve.grid)
555
+ see(at);
556
+ }
557
+ /* A band has no `LayerPoint`. Its readings hold the horizontal reach. */
558
+ if (trace.data.geom === "ribbon") {
559
+ for (const reading of trace.data.readings) {
560
+ if (typeof reading.x === "number")
561
+ see(reading.x);
562
+ }
563
+ }
564
+ /* And a segment carries none either, with a reach that runs to its far end. */
565
+ if (trace.data.geom === "segment") {
566
+ for (const segment of trace.data.segments) {
567
+ /* A pair inside a band names its category and takes no room on a value scale. */
568
+ if (typeof segment.x !== "number" || typeof segment.xEnd !== "number")
569
+ continue;
570
+ see(segment.x);
571
+ see(segment.xEnd);
572
+ }
573
+ }
574
+ }
575
+ return Number.isFinite(lo) ? [lo, hi] : [0, 1];
576
+ };
577
+ const xExtent = reaching(horizontalExtent(), plot.scales?.x?.include, xTransform);
578
+ const xChrome = chromeOf(plot.scales?.x, metrics);
579
+ const yChrome = chromeOf(plot.scales?.y, metrics);
580
+ /*
581
+ A grid's bands tile, where a bar's are set apart.
582
+
583
+ Band padding puts air between two bars. A grid has none. The geometry decides this.
584
+ */
585
+ const tiles = traces.some((trace) => trace.data.at === "groups" && trace.data.geom === "heatmap");
586
+ const bandPadding = tiles ? 0 : undefined;
587
+ const x = axisKind === "band" || !xField
588
+ ? {
589
+ ...xChrome,
590
+ values: categories,
591
+ names: plot.scales?.x?.labels,
592
+ label: plot.scales?.x?.title ?? xField?.label,
593
+ padding: bandPadding,
594
+ }
595
+ : {
596
+ ...xChrome,
597
+ domain: copied(plot.scales?.x?.limits) ?? pad(xExtent[0], xExtent[1], xTransform, plot.scales?.x?.expand),
598
+ transform: xTransform,
599
+ ...scaleOf(plot.scales?.x),
600
+ ...oobOf(plot.scales?.x),
601
+ time: plot.scales?.x?.time ?? xField.timeScale,
602
+ label: plot.scales?.x?.title ?? axisLabel(xField),
603
+ tickStep: plot.scales?.x?.breakWidth,
604
+ minorTicks: plot.scales?.x?.minorTicks,
605
+ format: plot.scales?.x?.format ? tickFormatter(plot.scales.x.format, plot.scales.x.decimals) : undefined,
606
+ };
607
+ /*
608
+ The measures a grid spreads across its horizontal band.
609
+
610
+ A gate grid draws its measures across the top and the column's values down the side.
611
+ */
612
+ const spread = plot.layers.flatMap((series) => {
613
+ if (series.kind !== "heatmap")
614
+ return [];
615
+ const bound = series.aes.dimensions;
616
+ const ids = Array.isArray(bound) ? bound : bound ? [bound] : [];
617
+ return ids.map((id) => fieldAt.get(id)).filter((field) => field != null);
618
+ });
619
+ /*
620
+ Both axes name categories where a heatmap draws.
621
+
622
+ The vertical axis takes the field bound to it. A spread grid takes the field bound to x.
623
+ */
624
+ const rowFieldOf = (series) => {
625
+ if (typeof series.aes.y === "string")
626
+ return fieldAt.get(series.aes.y);
627
+ const bound = series.aes.dimensions;
628
+ const spreads = Array.isArray(bound) ? bound.length > 0 : bound != null;
629
+ return spreads && typeof series.aes.x === "string" ? fieldAt.get(series.aes.x) : undefined;
630
+ };
631
+ const stackedField = traces.some((trace) => trace.data.at === "groups" && trace.data.geom === "heatmap")
632
+ ? plot.layers.map(rowFieldOf).find((field) => field != null)
633
+ : undefined;
634
+ /*
635
+ Rows are capped like columns and ranked by what passes through them.
636
+
637
+ Ranking by the rows behind each one keeps the populated end of the grid.
638
+ */
639
+ const weight = new Map();
640
+ for (const trace of traces) {
641
+ if (trace.data.at !== "groups" || trace.data.geom !== "heatmap")
642
+ continue;
643
+ for (const cell of trace.data.cells) {
644
+ weight.set(cell.y, (weight.get(cell.y) ?? 0) + cell.n);
645
+ }
646
+ }
647
+ const stacked = [...weight]
648
+ .sort((a, b) => b[1] - a[1])
649
+ .slice(0, bandCap(plot))
650
+ .map(([row]) => row);
651
+ hiddenCategories += weight.size - stacked.length;
652
+ /*
653
+ Cells outside either cap are dropped.
654
+
655
+ A band scale answers with nothing for a category it lacks, and the geom reads that as zero.
656
+ */
657
+ const drawn = stacked.length > 0
658
+ ? traces.map((trace) => {
659
+ if (trace.data.at !== "groups" || trace.data.geom !== "heatmap")
660
+ return trace;
661
+ const rows = new Set(stacked);
662
+ const columns = new Set(categories);
663
+ const cells = trace.data.cells.filter((cell) => rows.has(cell.y) && columns.has(cell.x));
664
+ return cells.length === trace.data.cells.length ? trace : { ...trace, data: { ...trace.data, cells } };
665
+ })
666
+ : traces;
667
+ /*
668
+ The author's order, resolved after the caps and before either band is written.
669
+
670
+ Clustering rows a cap will drop wastes the quadratic term.
671
+ */
672
+ const ordered = orderBands(plot, categories, stacked, drawn, metrics);
673
+ const reordered = ordered.reduced ? reduceGrids(drawn, ordered.reduced) : drawn;
674
+ /* Only geoms that occupy a slot divide the band. A line or an area over the groups draws across them. */
675
+ const slotted = reordered.filter((trace) => trace.data.at === "groups" && trace.data.geom !== "line" && trace.data.geom !== "area");
676
+ const hasBars = traces.some((trace) => trace.data.geom === "bar");
677
+ const y = ordered.y.values.length > 0
678
+ ? {
679
+ ...yChrome,
680
+ values: ordered.y.values,
681
+ gaps: ordered.y.gaps,
682
+ gapSize: metrics.gap,
683
+ padding: bandPadding,
684
+ names: plot.scales?.y?.labels,
685
+ label: plot.scales?.y?.title ?? stackedField?.label,
686
+ }
687
+ : {
688
+ ...yChrome,
689
+ domain: copied(plot.scales?.y?.limits) ??
690
+ (grounded && !isLog(yTransform)
691
+ ? plot.scales?.y?.expand
692
+ ? pad(Math.min(0, leftExtent[0]), leftExtent[1], yTransform, plot.scales.y.expand)
693
+ : [Math.min(0, leftExtent[0]), leftExtent[1] * 1.08 || 1]
694
+ : pad(leftExtent[0], leftExtent[1], yTransform, plot.scales?.y?.expand)),
695
+ transform: yTransform,
696
+ ...scaleOf(plot.scales?.y),
697
+ ...oobOf(plot.scales?.y),
698
+ time: plot.scales?.y?.time ?? leftField?.timeScale,
699
+ label: plot.scales?.y?.title ??
700
+ (leftShares ? shareLabel(leftField) : axisLabel(leftField)) ??
701
+ (hasBars ? "records" : undefined),
702
+ tickStep: plot.scales?.y?.breakWidth,
703
+ minorTicks: plot.scales?.y?.minorTicks,
704
+ format: plot.scales?.y?.format ? tickFormatter(plot.scales.y.format, plot.scales.y.decimals) : undefined,
705
+ };
706
+ /* A permutation keeps the same labels and the margin is unmoved. A kmeans order renames them. */
707
+ const xBand = isBand(x)
708
+ ? { ...x, values: ordered.x.values, gaps: ordered.x.gaps, gapSize: ordered.gapSize }
709
+ : x;
710
+ /*
711
+ Whether the pair draws with its roles swapped, decided once here.
712
+
713
+ Refused where no geom reads the shared pair. A parallel plot has an axis per measure.
714
+ */
715
+ const swapped = plot.coord === "flip" && !axisFree && drawn.some((trace) => drawsAxes(trace.data.geom));
716
+ /*
717
+ The two specs as the screen takes them.
718
+
719
+ Above this line everything reads in the data's own terms. Below it everything draws.
720
+ */
721
+ const horizontal = swapped ? y : xBand;
722
+ const upright = swapped ? xBand : y;
723
+ /* A top side panel takes the room a vertical title captions from. The title turns along its rule. */
724
+ const topSide = (plot.sides ?? []).some((panel) => panel.position === "top");
725
+ const vertical = topSide && upright.titleAlign == null ? { ...upright, titleAlign: "center" } : upright;
726
+ const rightDomain = rightExtent
727
+ ? (copied(plot.scales?.y2?.limits) ?? pad(rightExtent[0], rightExtent[1], rightTransform))
728
+ : null;
729
+ const rightAxis = rightDomain
730
+ ? { transform: rightTransform, ...scaleOf(plot.scales?.y2), ...oobOf(plot.scales?.y2) }
731
+ : null;
732
+ /* Direct labels apply to points. A reduction has no record to name. */
733
+ const labeled = traces.map((trace) => {
734
+ const rule = plot.layers.find((series) => series.id === trace.layerId)?.directLabels;
735
+ const points = pointsOf(trace);
736
+ if (!rule || points.length === 0)
737
+ return { trace, indices: [], dropped: 0 };
738
+ const chosen = chooseLabels(points, rule.when);
739
+ return { trace, indices: chosen.indices, dropped: chosen.dropped };
740
+ });
741
+ const labelRule = (() => {
742
+ const withRule = plot.layers.find((series) => series.directLabels && traces.some((trace) => trace.layerId === series.id));
743
+ const rule = withRule?.directLabels?.when;
744
+ if (!rule || !xField)
745
+ return null;
746
+ const measure = traces.find((trace) => trace.layerId === withRule.id)?.field?.label;
747
+ if (rule.kind === "all")
748
+ return "labeling all points";
749
+ if (rule.kind === "top") {
750
+ const on = rule.on === "x" ? xField.label : (measure ?? rule.on);
751
+ return `labeling the ${rule.end === "high" ? "top" : "bottom"} ${rule.count} by ${on}`;
752
+ }
753
+ const on = rule.on === "x" ? xField.label : (measure ?? rule.on);
754
+ return `labeling ${on} ${rule.op} ${rule.value}`;
755
+ })();
756
+ /*
757
+ The declared tracks, resolved against the bands as drawn.
758
+
759
+ After the caps and the order. `stackedField` is the vertical band's column and `xField` the
760
+ horizontal one's.
761
+ */
762
+ /* Each row's own label to the centroid it draws under, where a kmeans order reduced a band. */
763
+ const reducedTo = ordered.reduced ? new Map(ordered.reduced.of.map((one) => [one.of, one.to])) : undefined;
764
+ const tracks = (plot.sides ?? []).flatMap((panel) => {
765
+ if (panel.content.kind !== "track")
766
+ return [];
767
+ /* The edge is the screen and the grouping is the role. A transpose parts them. */
768
+ const across = (panel.position === "top" || panel.position === "bottom") !== swapped;
769
+ /* A band of measures has no rows behind it. The track reads their declarations. */
770
+ if (across && spread.length > 0) {
771
+ const overFields = trackOverFields({
772
+ field: panel.content.field,
773
+ axis: "x",
774
+ categories,
775
+ measures: spread,
776
+ palette: panel.content.palette,
777
+ pinned: pinned?.[panel.content.field],
778
+ dropLevels: panel.content.dropLevels,
779
+ });
780
+ return overFields ? [overFields] : [];
781
+ }
782
+ const keyField = across ? xField : stackedField;
783
+ if (!keyField)
784
+ return [];
785
+ const resolved = trackFor({
786
+ field: panel.content.field,
787
+ axis: across ? "x" : "y",
788
+ /* The band as drawn. The axis beside the strip reads the same list. */
789
+ categories: across ? ordered.x.values : ordered.y.values,
790
+ alias: reducedTo && ordered.reduced?.along === (across ? "x" : "y") ? reducedTo : undefined,
791
+ keyField: keyField.id,
792
+ data,
793
+ fieldAt,
794
+ palette: panel.content.palette,
795
+ pinned: pinned?.[panel.content.field],
796
+ dropLevels: panel.content.dropLevels,
797
+ });
798
+ return resolved ? [resolved] : [];
799
+ });
800
+ /*
801
+ The marginals, read off the points the geoms drew.
802
+
803
+ A marginal states the distribution of the cloud in the figure. One walk per axis.
804
+ */
805
+ const readings = new Map();
806
+ const marginals = (plot.sides ?? []).flatMap((panel) => {
807
+ const wanted = panel.content.kind;
808
+ if (wanted !== "histogram" && wanted !== "rug" && wanted !== "density")
809
+ return [];
810
+ /*
811
+ The edge says where the panel draws and the role says what it reads.
812
+
813
+ `axis` stays the screen one and the walk of the geoms reads the role behind it.
814
+ */
815
+ const axis = panel.position === "top" || panel.position === "bottom" ? "x" : "y";
816
+ const role = swapped ? (axis === "x" ? "y" : "x") : axis;
817
+ let values = readings.get(role);
818
+ if (!values) {
819
+ values = valuesAlong(reordered, role);
820
+ readings.set(role, values);
821
+ }
822
+ if (values.length === 0)
823
+ return [];
824
+ if (wanted === "rug")
825
+ return [{ axis, kind: "rug", values }];
826
+ if (wanted === "density") {
827
+ /* Split where the panel asked and the color channel can answer, pooled otherwise. */
828
+ const curves = panel.content.by === "color" ? valuesByLevel(reordered, role) : valuesByLevel(stripLevels(reordered), role);
829
+ return curves.length === 0 ? [] : [{ axis, kind: "density", values, curves }];
830
+ }
831
+ /* The scale the panel reads, after the transpose has decided which role runs across. */
832
+ const along = axis === "x" ? horizontal : vertical;
833
+ /* Cut in the axis's transformed space. The intervals are even where the reader looks. */
834
+ const transform = isBand(along) ? "identity" : transformOf(along);
835
+ return [{ axis, kind: "histogram", values, ...marginalBins(values, panel.content.binwidth ?? "auto", transform) }];
836
+ });
837
+ /* The build's caps, joined by the ones the frame itself applies. */
838
+ const ledger = [...omitted];
839
+ omit(ledger, "categories", hiddenCategories);
840
+ /* A bin along a transformed axis leaves out the readings the transform refuses. */
841
+ const offBins = traces.reduce((sum, trace) => sum + (trace.data.at === "groups" && "offScale" in trace.data ? (trace.data.offScale ?? 0) : 0), 0);
842
+ omit(ledger, "off-log", placed.offLog + (isLog(xTransform) ? offBins : 0));
843
+ omit(ledger, "off-root", placed.offRoot + (xTransform === "sqrt" ? offBins : 0));
844
+ omit(ledger, "off-range", placed.offRange);
845
+ omit(ledger, "floored", flooredCount(traces, yTransform));
846
+ /* A reference past its axis draws nothing. The author wrote it, so the footer says where it went. */
847
+ const ruleAxis = (spec) => (isBand(spec) ? null : spec);
848
+ omit(ledger, "references", reordered.reduce((sum, trace) => sum +
849
+ ("rules" in trace.data
850
+ ? trace.data.rules.filter((rule) => ruleSegment(rule, ruleAxis(xBand), ruleAxis(y)) == null).length
851
+ : 0), 0));
852
+ omit(ledger, "labels", labeled.reduce((sum, entry) => sum + entry.dropped, 0));
853
+ return {
854
+ status: "ready",
855
+ traces: reordered,
856
+ axisKind,
857
+ xField,
858
+ unbuilt,
859
+ slotted,
860
+ axisFree,
861
+ x: horizontal,
862
+ y: vertical,
863
+ transposed: swapped,
864
+ /* A stated range can leave a geom past the frame. The plot area holds it in. */
865
+ clip: (axisKind === "continuous" && plot.scales?.x?.limits != null) || plot.scales?.y?.limits != null,
866
+ margin: {
867
+ top: 14,
868
+ right: rightExtent ? 52 : 14,
869
+ /* A vertical title moved along its rule takes a column; left above the axis it takes none. */
870
+ bottom: roomFor(horizontal, "x", horizontal.label != null, metrics.ticks) +
871
+ (horizontal.label != null ? 0 : TITLE_PAD / 2),
872
+ /* The chrome of whichever options configure the vertical axis, which a transpose moves across. */
873
+ left: roomFor(vertical, "y", vertical.label != null && (vertical.titleAlign ?? "end") !== "end", metrics.ticks),
874
+ },
875
+ rightDomain,
876
+ rightAxis,
877
+ annotations: annotationLayers(plot.annotations ?? [], swapped),
878
+ labeled,
879
+ labelRule,
880
+ clusterRefused: ordered.refused,
881
+ clusterTrees: { x: ordered.x.clustered ?? null, y: ordered.y.clustered ?? null },
882
+ tracks,
883
+ marginals,
884
+ omitted: ledger,
885
+ legend: legendRows(reordered, plot.legend?.order),
886
+ fieldAt,
887
+ metrics,
888
+ };
889
+ }
890
+ /**
891
+ * Panels a facet draws.
892
+ *
893
+ * Twelve is where a small multiple stops reading at a tile's width. Chart-design rule 6 names it.
894
+ */
895
+ export const FACET_CAP = 12;
896
+ /** The right-hand scale, built per render. It reads the plot area's height and the frame's `rightAxis`. */
897
+ export const rightScaleFor = (domain, innerHeight, axis) => (domain ? buildAxis({ ...axis, domain }, [innerHeight, 0], 5, "end").scale : null);
898
+ const spanOver = (values) => [
899
+ boundsOf(values.map((v) => v[0]))[0],
900
+ boundsOf(values.map((v) => v[1]))[1],
901
+ ];
902
+ /**
903
+ * One domain across the panels.
904
+ *
905
+ * Two panels drawn at the same height would say the same thing about different numbers. There is
906
+ * no option for free scales.
907
+ */
908
+ function shareScales(panels, palette, plot,
909
+ /* The author's orders. The union is a wider set than one panel resolved against. */
910
+ orders) {
911
+ if (panels.length < 2)
912
+ return panels;
913
+ const frames = panels.map((panel) => panel.frame);
914
+ /*
915
+ Color and size span the way position does.
916
+
917
+ Each panel builds against its own rows. Spanned per trace id.
918
+ */
919
+ /* The extent. A stated range should not stand in for what the panels measured. */
920
+ const colorSpans = spanById(frames, (trace) => trace.colorExtent);
921
+ const sizeSpans = spanById(frames, (trace) => trace.sizeDomain);
922
+ const fills = fillsById(frames);
923
+ const yDomains = frames.map((frame) => ("domain" in frame.y ? frame.y.domain : null));
924
+ const y = yDomains.every((domain) => domain != null) ? spanOver(yDomains) : null;
925
+ const rights = frames.map((frame) => frame.rightDomain).filter((d) => d != null);
926
+ const rightDomain = rights.length > 0 ? spanOver(rights) : null;
927
+ /* Every edge, not the right one alone. A panel reserving panel zero's room overruns its own. */
928
+ const margin = {
929
+ top: boundsOf(frames.map((f) => f.margin.top))[1],
930
+ right: boundsOf(frames.map((f) => f.margin.right))[1],
931
+ bottom: boundsOf(frames.map((f) => f.margin.bottom))[1],
932
+ left: boundsOf(frames.map((f) => f.margin.left))[1],
933
+ };
934
+ /*
935
+ Bands take the union in the panels' own order. A category holds one slot.
936
+
937
+ Both axes. A grid bands both. Panel zero's order leads.
938
+ */
939
+ const unionOf = (read) => {
940
+ const values = [];
941
+ const seen = new Set();
942
+ for (const frame of frames) {
943
+ const axis = read(frame);
944
+ if (!isBand(axis))
945
+ continue;
946
+ for (const value of axis.values) {
947
+ if (seen.has(value))
948
+ continue;
949
+ seen.add(value);
950
+ values.push(value);
951
+ }
952
+ }
953
+ return values;
954
+ };
955
+ /*
956
+ A stated list is re-resolved against the union. No panel saw the whole set.
957
+
958
+ Re-running the list over the union costs a filter. A cluster order cannot re-run here.
959
+ */
960
+ const aligned = (axis, order, values) => {
961
+ if (order?.kind !== "list")
962
+ return { values, gaps: isBand(axis) ? axis.gaps : undefined };
963
+ const out = orderBand(order, values, () => null);
964
+ return { values: out.values, gaps: out.gaps };
965
+ };
966
+ const xDomains = frames.map((frame) => ("domain" in frame.x ? frame.x.domain : null));
967
+ const x = xDomains.every((domain) => domain != null)
968
+ ? { ...frames[0].x, domain: spanOver(xDomains) }
969
+ : {
970
+ ...frames[0].x,
971
+ ...aligned(frames[0].x, orders?.x, unionOf((frame) => frame.x)),
972
+ };
973
+ const yBand = frames.every((frame) => isBand(frame.y))
974
+ ? {
975
+ ...frames[0].y,
976
+ ...aligned(frames[0].y, orders?.y, unionOf((frame) => frame.y)),
977
+ }
978
+ : null;
979
+ const rescale = (trace) => {
980
+ let out = trace;
981
+ const colorExtent = colorSpans.get(trace.id);
982
+ const sizeDomain = sizeSpans.get(trace.id);
983
+ if (colorExtent && trace.colorExtent) {
984
+ /* Through the same helpers the build used. An author's center and cuts survive the span. */
985
+ /* The trace's own map and options where the series named them. A span keeps its palette. */
986
+ const options = rampOptionsFor(trace.data.geom, traceScale(plot.scales, plot.layers, trace));
987
+ const maps = trace.sequential ? { ...palette, sequential: trace.sequential } : palette;
988
+ out = {
989
+ ...out,
990
+ ...colorScaleOf(colorExtent, options),
991
+ ramp: valueRamp(colorExtent, maps, options),
992
+ };
993
+ }
994
+ const fill = fills.get(trace.id);
995
+ if (fill)
996
+ out = { ...out, colorLevels: fill.levels };
997
+ const data = out.data;
998
+ if (sizeDomain &&
999
+ trace.sizeDomain &&
1000
+ trace.sizeRadii &&
1001
+ data.at === "records" &&
1002
+ data.geom !== "parcoords" &&
1003
+ data.geom !== "radar" &&
1004
+ data.geom !== "ribbon" &&
1005
+ data.geom !== "range" &&
1006
+ data.geom !== "segment" &&
1007
+ "points" in data) {
1008
+ const [lo, hi] = sizeDomain;
1009
+ const radii = trace.sizeRadii;
1010
+ out = {
1011
+ ...out,
1012
+ sizeDomain,
1013
+ data: {
1014
+ ...data,
1015
+ points: data.points.map((point) => point.sizeValue == null ? point : { ...point, size: sizeRadius(point.sizeValue, lo, hi, radii) }),
1016
+ },
1017
+ };
1018
+ }
1019
+ return out;
1020
+ };
1021
+ /*
1022
+ A categorical fill's swatches and one-ink count, over the categories any panel's cells take.
1023
+
1024
+ A keyed map's misses join the count. Each category counts once across the panels.
1025
+ */
1026
+ const unmapped = [...fills.values()].reduce((sum, fill) => sum + fill.unmapped, 0);
1027
+ const offMap = new Set(frames.flatMap((frame) => frame.omitted.flatMap((one) => one.levels ?? [])));
1028
+ const filled = (frame) => {
1029
+ if (fills.size === 0 && offMap.size === 0)
1030
+ return frame;
1031
+ const omitted = frame.omitted.filter((one) => one.of !== "fills");
1032
+ omit(omitted, "fills", unmapped + offMap.size);
1033
+ return { ...frame, omitted, legend: legendRows(frame.traces, plot.legend?.order) };
1034
+ };
1035
+ return panels.map((panel) => ({
1036
+ ...panel,
1037
+ frame: {
1038
+ ...filled(rewriteTraces(panel.frame, rescale)),
1039
+ x: x,
1040
+ y: y ? { ...panel.frame.y, domain: y } : (yBand ?? panel.frame.y),
1041
+ rightDomain,
1042
+ margin,
1043
+ },
1044
+ }));
1045
+ }
1046
+ /** A categorical fill's levels and its count of categories past the map, per trace id across the panels. */
1047
+ function fillsById(frames) {
1048
+ const held = new Map();
1049
+ for (const frame of frames) {
1050
+ for (const trace of frame.traces) {
1051
+ const data = trace.data;
1052
+ if (!trace.colorLevels || data.at !== "groups" || data.geom !== "heatmap")
1053
+ continue;
1054
+ const drawn = data.cells.flatMap((cell) => (cell.category == null ? [] : [cell.category]));
1055
+ if (drawn.length === 0)
1056
+ continue;
1057
+ let fill = held.get(trace.id);
1058
+ if (!fill) {
1059
+ fill = { levels: new Map(), drawn: new Set() };
1060
+ held.set(trace.id, fill);
1061
+ }
1062
+ for (const { value, code } of trace.colorLevels)
1063
+ fill.levels.set(value, code);
1064
+ for (const value of drawn)
1065
+ fill.drawn.add(value);
1066
+ }
1067
+ }
1068
+ return new Map([...held].map(([id, { levels, drawn }]) => [
1069
+ id,
1070
+ {
1071
+ levels: [...levels].map(([value, code]) => ({ value, code })).sort((a, b) => a.code - b.code),
1072
+ unmapped: [...drawn].filter((value) => !levels.has(value)).length,
1073
+ },
1074
+ ]));
1075
+ }
1076
+ /** One span per trace id, across the panels that hold it. */
1077
+ function spanById(frames, read) {
1078
+ const seen = new Map();
1079
+ for (const frame of frames) {
1080
+ for (const trace of frame.traces) {
1081
+ const domain = read(trace);
1082
+ if (!domain)
1083
+ continue;
1084
+ const held = seen.get(trace.id);
1085
+ if (held)
1086
+ held.push(domain);
1087
+ else
1088
+ seen.set(trace.id, [domain]);
1089
+ }
1090
+ }
1091
+ return new Map([...seen].map(([id, domains]) => [id, spanOver(domains)]));
1092
+ }
1093
+ /**
1094
+ * Which rows belong to which panel.
1095
+ *
1096
+ * The expensive half, apart from the build. Re-cutting the rows into panels needs the facet
1097
+ * field or the table to change.
1098
+ */
1099
+ export function partitionOf(plot, data) {
1100
+ const by = plot.facet?.by;
1101
+ const field = by ? data.fields.find((candidate) => candidate.id === by) : undefined;
1102
+ if (!field)
1103
+ return { groups: [] };
1104
+ return {
1105
+ field,
1106
+ groups: [...rowsByValue(data, field.id)].sort((a, b) => b[1].length - a[1].length),
1107
+ };
1108
+ }
1109
+ /**
1110
+ * The spec as far as the build reads it.
1111
+ *
1112
+ * Written as everything-but. `style.fill`, `style.color`, `updatedAt` and most of `scales.color`
1113
+ * come out. `scale` stays.
1114
+ */
1115
+ export const shapeOf = (plot) => JSON.stringify({
1116
+ ...plot,
1117
+ layers: plot.layers.map((series) => ({ ...series, style: buildStyle(series.style) })),
1118
+ scales: { ...plot.scales, color: buildColorScale(plot.scales?.color), fill: buildColorScale(plot.scales?.fill) },
1119
+ }, (key, value) => (key === "updatedAt" ? undefined : value));
1120
+ /** A series' style as the build reads it: everything but the paints laid over afterwards. */
1121
+ function buildStyle(style) {
1122
+ if (!style)
1123
+ return undefined;
1124
+ const { fill: _interior, color: _edge, ...read } = style;
1125
+ return read;
1126
+ }
1127
+ /**
1128
+ * The color scale as the build reads it -- the z-score direction and the keyed map.
1129
+ *
1130
+ * Absent where the author set neither. Written as everything-but.
1131
+ */
1132
+ function buildColorScale(options) {
1133
+ if (!options?.standardize && !options?.values)
1134
+ return undefined;
1135
+ return { standardize: options.standardize, values: options.values };
1136
+ }
1137
+ /**
1138
+ * What `paint` reads -- the colors the author picked and the ramp settings they dragged.
1139
+ *
1140
+ * The ramp goes in whole. A setting added to `ColorScale` reaches `paint` through the spread.
1141
+ */
1142
+ export const colorsOf = (plot) => [
1143
+ plot.layers.map((series) => `${series.id}:${geomColor(series.style, series.kind) ?? ""}`).join("|"),
1144
+ JSON.stringify(plot.scales?.color ?? null),
1145
+ JSON.stringify(plot.scales?.fill ?? null),
1146
+ ].join("|");
1147
+ /**
1148
+ * The color scale a trace's ramp closes on: the layer's own from the build, else the chart's current
1149
+ * one on the layer's paint aesthetic.
1150
+ */
1151
+ function traceScale(scales, layers, trace) {
1152
+ if (trace.colorOptions)
1153
+ return trace.colorOptions;
1154
+ const layer = layers.find((one) => one.id === trace.layerId);
1155
+ return layer ? scales?.[paintAesthetic(layer)] : undefined;
1156
+ }
1157
+ /**
1158
+ * The author's colors laid over the palette's.
1159
+ *
1160
+ * This walks the traces. A series' own color reaches four places, and a scaled channel repaints
1161
+ * over `Trace.colorExtent`.
1162
+ */
1163
+ export function paint(built, series, palettes, scales) {
1164
+ const picked = new Map(series.flatMap((one) => {
1165
+ const color = drawsOneColor(one) ? geomColor(one.style, one.kind) : undefined;
1166
+ return color ? [[one.id, color]] : [];
1167
+ }));
1168
+ if (built.status === "empty")
1169
+ return built;
1170
+ const scaled = built.panels.some((panel) => panel.frame.traces.some((trace) => trace.colorExtent));
1171
+ if (picked.size === 0 && !scaled)
1172
+ return built;
1173
+ const recolor = (trace) => {
1174
+ let out = trace;
1175
+ if (trace.colorExtent) {
1176
+ /* Read the way `shareScales` reads them. A recolor keeps a series' own map. */
1177
+ const options = rampOptionsFor(trace.data.geom, traceScale(scales, series, trace));
1178
+ const maps = trace.sequential ? { ...palettes, sequential: trace.sequential } : palettes;
1179
+ out = {
1180
+ ...out,
1181
+ colorDomain: colorDomainOf(trace.colorExtent, options),
1182
+ ramp: valueRamp(trace.colorExtent, maps, options),
1183
+ };
1184
+ }
1185
+ const color = picked.get(trace.layerId);
1186
+ if (!color)
1187
+ return out;
1188
+ return {
1189
+ ...out,
1190
+ color: color,
1191
+ ramp: () => color,
1192
+ data: trace.data.geom === "sankey"
1193
+ ? { ...trace.data, links: trace.data.links.map((link) => ({ ...link, color: color })) }
1194
+ : trace.data,
1195
+ };
1196
+ };
1197
+ return {
1198
+ ...built,
1199
+ panels: built.panels.map((panel) => ({ ...panel, frame: rewriteTraces(panel.frame, recolor) })),
1200
+ };
1201
+ }
1202
+ /**
1203
+ * A finished frame with its traces rewritten.
1204
+ *
1205
+ * A frame holds a trace in four places and a pass puts its rewrite back in all four.
1206
+ */
1207
+ function rewriteTraces(frame, rewrite) {
1208
+ const traces = frame.traces.map(rewrite);
1209
+ const at = new Map(traces.map((trace) => [trace.id, trace]));
1210
+ return {
1211
+ ...frame,
1212
+ traces,
1213
+ slotted: frame.slotted.map((trace) => at.get(trace.id) ?? trace),
1214
+ labeled: frame.labeled.map((entry) => ({ ...entry, trace: at.get(entry.trace.id) ?? entry.trace })),
1215
+ /* A row of an unsplit series is keyed by its trace. A rewrite reaches that kind alone. */
1216
+ legend: frame.legend.map((row) => {
1217
+ const trace = at.get(row.key) ?? traces.find((one) => one.grouped && one.layerId === row.key);
1218
+ return trace ? { ...row, color: trace.color } : row;
1219
+ }),
1220
+ };
1221
+ }
1222
+ /**
1223
+ * The build with the reader's ranges laid over it.
1224
+ *
1225
+ * A third pass beside `paint`. A dragged range changes which records draw.
1226
+ */
1227
+ export function narrow(built, ranges) {
1228
+ if (built.status === "empty" || !anyRange(ranges))
1229
+ return { panels: built, kept: null };
1230
+ let within = 0;
1231
+ let of = 0;
1232
+ const keep = (trace) => {
1233
+ if (trace.data.at !== "records" || trace.data.geom !== "parcoords")
1234
+ return trace;
1235
+ const lines = keptLines(trace.data.lines, trace.data.axes.map((axis) => axis.id), ranges);
1236
+ within += lines.length;
1237
+ of += trace.data.lines.length;
1238
+ return { ...trace, data: { ...trace.data, lines } };
1239
+ };
1240
+ const panels = built.panels.map((panel) => ({ ...panel, frame: rewriteTraces(panel.frame, keep) }));
1241
+ return { panels: { ...built, panels }, kept: of > 0 ? { within, of } : null };
1242
+ }
1243
+ /**
1244
+ * The plot as one frame, or as a panel per value of the facet field.
1245
+ */
1246
+ /**
1247
+ * The traces with their identity levels taken off. A marginal pools.
1248
+ *
1249
+ * A pooled density is the default. A point takes its category's index as its weight.
1250
+ */
1251
+ const stripLevels = (traces) => traces.map((trace) => (trace.colorLevels ? { ...trace, colorLevels: undefined } : trace));
1252
+ /**
1253
+ * The categorical assignment a facet's panels share, off the whole table.
1254
+ *
1255
+ * Read once here and pinned onto each panel. A field the caller pinned is left alone.
1256
+ */
1257
+ function facetAssignments(plot, data, pinned) {
1258
+ const fields = new Map(data.fields.map((field) => [field.id, field]));
1259
+ const shared = {};
1260
+ for (const series of plot.layers) {
1261
+ const id = paintColumn(series);
1262
+ /* A measure runs a scale and `shareScales` already spans that; only identity needs an index. */
1263
+ if (!id || fields.get(id)?.numeric !== false)
1264
+ continue;
1265
+ if (pinned?.[id])
1266
+ continue;
1267
+ const codes = {};
1268
+ let next = 0;
1269
+ for (const value of rowsByValue(data, id).keys()) {
1270
+ codes[value] = next;
1271
+ next += 1;
1272
+ }
1273
+ shared[id] = codes;
1274
+ }
1275
+ if (Object.keys(shared).length === 0)
1276
+ return pinned;
1277
+ return { ...shared, ...pinned };
1278
+ }
1279
+ export function buildPanels(plot, data, { palettes: palette, partition, metrics = REGULAR, pinned }) {
1280
+ const table = readOnce(data);
1281
+ if (!partition.field) {
1282
+ const frame = buildFrame(plot, table, { palettes: palette, metrics, pinned });
1283
+ return frame.status === "empty"
1284
+ ? frame
1285
+ : { status: "ready", panels: [{ value: "", count: data.rowCount, frame }], facetDropped: 0 };
1286
+ }
1287
+ const panels = [];
1288
+ let firstEmpty = null;
1289
+ let emptied = 0;
1290
+ const shared = facetAssignments(plot, data, pinned);
1291
+ for (const [value, rows] of partition.groups.slice(0, FACET_CAP)) {
1292
+ const frame = buildFrame(panelSpec(plot, partition.field.id, value), viewOf(table, rows), {
1293
+ palettes: palette,
1294
+ metrics,
1295
+ pinned: shared,
1296
+ facet: { field: partition.field, value },
1297
+ });
1298
+ // A panel with nothing in it is dropped. A blank one reads as a broken axis.
1299
+ if (frame.status === "empty") {
1300
+ firstEmpty ??= frame;
1301
+ emptied += 1;
1302
+ }
1303
+ else
1304
+ panels.push({ value, count: rows.length, frame });
1305
+ }
1306
+ if (panels.length === 0) {
1307
+ return (firstEmpty ?? {
1308
+ status: "empty",
1309
+ title: "No panels",
1310
+ reason: `Nothing in these rows carries a value for ${partition.field.label}.`,
1311
+ });
1312
+ }
1313
+ return {
1314
+ status: "ready",
1315
+ panels: shareScales(panels, palette, plot, { x: plot.scales?.x?.order, y: plot.scales?.y?.order }),
1316
+ facetField: partition.field,
1317
+ /* The cap's overflow and the groups whose rows drew nothing. The footer counts both. */
1318
+ facetDropped: Math.max(0, partition.groups.length - FACET_CAP) + emptied,
1319
+ };
1320
+ }
1321
+ /**
1322
+ * The spec one panel draws. A layer's rows naming the facet column keep that panel's rows.
1323
+ *
1324
+ * Rows without it repeat in each panel, as in ggplot.
1325
+ */
1326
+ function panelSpec(plot, facet, value) {
1327
+ if (!plot.layers.some((series) => series.data?.some((row) => facet in row)))
1328
+ return plot;
1329
+ return {
1330
+ ...plot,
1331
+ layers: plot.layers.map((series) => series.data?.some((row) => facet in row)
1332
+ ? { ...series, data: series.data.filter((row) => row[facet] != null && String(row[facet]) === value) }
1333
+ : series),
1334
+ };
1335
+ }
1336
+ /**
1337
+ * Counts of the curves a fit drew and the ones it failed on.
1338
+ *
1339
+ * A failed curve leaves no geom on the chart. Both counts are stated.
1340
+ */
1341
+ export function fitNote(fitted, all) {
1342
+ if (fitted.problem)
1343
+ return [fitted.problem];
1344
+ if (fitted.pending)
1345
+ return ["fitting"];
1346
+ if (all.length === 0)
1347
+ return [];
1348
+ const ok = all.filter((fit) => fit.success).length;
1349
+ const dropped = [...fitted.byLayer.values()].reduce((sum, entry) => sum + entry.dropped, 0);
1350
+ // Counted over the plot. The areas compound on one frame.
1351
+ const banded = all.length > BAND_LIMIT && all.some((fit) => fit.band);
1352
+ return [
1353
+ all.length === 1
1354
+ ? ok === 1
1355
+ ? `fit r² ${(all[0].r2 ?? 0).toFixed(3)}`
1356
+ : `fit failed: ${all[0].reason ?? "unknown"}`
1357
+ : `${ok.toLocaleString()} of ${all.length.toLocaleString()} curves fitted`,
1358
+ ...(dropped > 0 ? [`${dropped.toLocaleString()} groups past the cap`] : []),
1359
+ // A band that was computed and not drawn should not read as a band that was not asked for.
1360
+ ...(banded ? [`bands hidden above ${BAND_LIMIT} curves`] : []),
1361
+ ];
1362
+ }
1363
+ export function footerOf(frame, { fitted, facetDropped = 0, held = [], substituted }) {
1364
+ /*
1365
+ Rule 7's third row, stated. This line appears where the caller substituted.
1366
+
1367
+ Nothing appears where the caller drew raw points past the switch. The critic reports that.
1368
+ */
1369
+ const substitution = substituted
1370
+ ? [
1371
+ `${substituted.rows.toLocaleString()} records drawn as a ${substituted.drew} of ${substituted.cells.toLocaleString()} cells`,
1372
+ ]
1373
+ : [];
1374
+ /*
1375
+ Which interval the whiskers stand for, named once for the figure.
1376
+
1377
+ Read off the traces. Two series disagreeing both get named.
1378
+ */
1379
+ const intervals = [
1380
+ ...new Set(frame.traces.flatMap((trace) => trace.data.at === "groups" && "error" in trace.data && trace.data.error ? [trace.data.error] : [])),
1381
+ ].map((kind) => (kind === "sem" ? "whiskers are one standard error" : "whiskers are one standard deviation"));
1382
+ /*
1383
+ The bandwidth a kernel smoothed at, named once for the figure.
1384
+
1385
+ No reader recovers the number from the curve. One clause whether the figure holds one kernel
1386
+ or twenty.
1387
+ */
1388
+ const smoothing = [
1389
+ ...new Set(frame.traces.flatMap((trace) => {
1390
+ if (trace.data.at !== "groups")
1391
+ return [];
1392
+ if (trace.data.geom === "density")
1393
+ return [trace.data.curve.bandwidth];
1394
+ if (trace.data.geom === "violin")
1395
+ return trace.data.violins.map((violin) => violin.bandwidth);
1396
+ return [];
1397
+ })),
1398
+ ]
1399
+ .filter((width) => width > 0)
1400
+ .sort((a, b) => a - b);
1401
+ const round = (width) => Number(width.toPrecision(3));
1402
+ const bandwidth = smoothing.length === 0
1403
+ ? []
1404
+ : smoothing.length === 1
1405
+ ? [`smoothed at a bandwidth of ${round(smoothing[0])}`]
1406
+ : [`smoothed at bandwidths of ${round(smoothing[0])} to ${round(smoothing[smoothing.length - 1])}`];
1407
+ /*
1408
+ The one cap the frame lacks, joined to the ledger it has.
1409
+
1410
+ A facet's dropped panels reach here as an argument. `buildLayers` records the replicate and
1411
+ flow caps itself.
1412
+ */
1413
+ const ledger = [...frame.omitted];
1414
+ omit(ledger, "panels", facetDropped);
1415
+ /*
1416
+ Walked in the order the wording table declares. Where a clause falls is that table's business.
1417
+ */
1418
+ const counted = OMITTED_KINDS.flatMap((of) => {
1419
+ const count = omittedCount(ledger, of);
1420
+ return count > 0 ? [omissionLine(of, count)] : [];
1421
+ });
1422
+ return ([
1423
+ ...held,
1424
+ ...intervals,
1425
+ ...bandwidth,
1426
+ ...substitution,
1427
+ ...counted,
1428
+ ...(frame.labelRule ? ["overlapping labels hidden"] : []),
1429
+ ...(frame.unbuilt.length > 0 ? [`${frame.unbuilt.join(" and ")} unknown to this version`] : []),
1430
+ ...fitNote(fitted, drawnFits(frame.traces, fitted)),
1431
+ ].join(", ") || undefined);
1432
+ }