@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,2892 @@
1
+ /**
2
+ * What a plot draws, resolved to a flat list of traces before anything renders.
3
+ *
4
+ * A series names a chart kind. This resolves it to a geom and a reduction.
5
+ */
6
+ import { binBreaks, binIndex, binOptionsOf, intervalsOf, keptUnder, padded, } from "./binning.js";
7
+ import { groupRows } from "./plot-data.js";
8
+ import { toPlotData } from "./adapters.js";
9
+ import { pinnedOver } from "./figure-set.js";
10
+ import { GRAMMAR, isAxial, geomGrammar } from "./grammar.js";
11
+ import { scaledCells } from "./cluster.js";
12
+ import { gateCells, modeCells, occupancyCells } from "./heat-reductions.js";
13
+ import { orderBand } from "./band-order.js";
14
+ import { kindFacts, layerScale, paintAesthetic, paintColumn } from "./geom-table.js";
15
+ import { LINETYPES, positionArgs, positionKind, } from "./spec.js";
16
+ import { REGULAR } from "./sizing.js";
17
+ import { meshOfRelief, meshOfRows, relief } from "./mesh.js";
18
+ import { field3d } from "./voxels.js";
19
+ import { boxStats, kde, quantileOf } from "./stats.js";
20
+ import { POINT_SHAPES } from "./geom-types.js";
21
+ import { chordLayout } from "./chord.js";
22
+ import { ringReading } from "./rings.js";
23
+ import { groupsOf, icicleLayout, treemapLayout } from "./hierarchy.js";
24
+ import { accumulate, accumulateAlong, boundsOf, NEEDS_VALUES, reduceBucket, spreadOf, } from "./aggregate.js";
25
+ import { flag, omit } from "./omission.js";
26
+ import { isLog, TRANSFORMS } from "./transform.js";
27
+ /**
28
+ * Whether a geom draws against the frame's axes.
29
+ *
30
+ * A treemap positions by nesting and a sankey by flow. Read off `GRAMMAR`'s coordinate column.
31
+ */
32
+ export const drawsAxes = (geom) => {
33
+ const grammar = geomGrammar(geom);
34
+ return grammar ? isAxial(grammar.coord) : true;
35
+ };
36
+ /**
37
+ * The geometry a kind draws with. A kind this version does not know answers undefined.
38
+ *
39
+ * Reads the geometry column of `GRAMMAR`.
40
+ */
41
+ export const geomFor = (kind) => GRAMMAR[kind]?.geom;
42
+ /**
43
+ * The radii a bound size channel spans, in pixels.
44
+ *
45
+ * Derived from the panel's own point radius. Half that radius to two and a half times it.
46
+ */
47
+ export const sizeRadiiFor = (metrics) => [
48
+ metrics.pointRadius * 0.5,
49
+ metrics.pointRadius * 2.5,
50
+ ];
51
+ /**
52
+ * Radius a value takes on the size channel, in pixels.
53
+ *
54
+ * Area stands for quantity per chart-design rule 11. The radius is the square root of it.
55
+ */
56
+ export function sizeRadius(value, lo, hi, radii) {
57
+ const [rMin, rMax] = radii;
58
+ const span = hi - lo;
59
+ const t = span > 0 ? Math.min(1, Math.max(0, (value - lo) / span)) : 0;
60
+ return Math.sqrt(rMin * rMin + t * (rMax * rMax - rMin * rMin));
61
+ }
62
+ /**
63
+ * A value's position in the magnitude map, over 0..1.
64
+ *
65
+ * Without a center the domain maps straight on. With one the scale is symmetric about it.
66
+ */
67
+ export function rampPosition(value, lo, hi, center) {
68
+ if (center == null)
69
+ return (value - lo) / (hi - lo || 1);
70
+ const reach = Math.max(Math.abs(hi - center), Math.abs(center - lo)) || 1;
71
+ return 0.5 + (value - center) / (2 * reach);
72
+ }
73
+ /**
74
+ * The ends the map runs between. The author's setting comes ahead of the data's.
75
+ *
76
+ * Cuts state their own ends. A value outside them has no bin to fall in.
77
+ */
78
+ export function colorDomainOf(derived, options) {
79
+ if (options?.limits)
80
+ return [options.limits[0], options.limits[1]];
81
+ const cuts = options?.bins;
82
+ if (cuts && cuts.length > 1)
83
+ return [cuts[0], cuts[cuts.length - 1]];
84
+ return derived;
85
+ }
86
+ /** A scaled color channel carries the data's extent and the ends the author set. */
87
+ export const colorScaleOf = (derived, options) => ({
88
+ colorExtent: derived,
89
+ colorDomain: colorDomainOf(derived, options),
90
+ });
91
+ /**
92
+ * The ramp settings a geom reads, with a z-scored grid's neutral filled in.
93
+ *
94
+ * Centering each row on its mean gives the cells a zero. `paint` closes ramps through this too.
95
+ */
96
+ export function rampOptionsFor(geom, options) {
97
+ if (geom !== "heatmap" || (options?.standardize ?? "none") === "none")
98
+ return options;
99
+ return { ...options, center: options?.center ?? 0 };
100
+ }
101
+ /**
102
+ * A value's color, in the units the value carries.
103
+ *
104
+ * The contract `Trace.ramp` states. n cuts make n-1 bins. Without cuts the map is continuous.
105
+ */
106
+ export function valueRamp(domain, palettes, options) {
107
+ const cuts = options?.bins;
108
+ if (cuts && cuts.length > 1) {
109
+ const bins = cuts.length - 1;
110
+ return (value) => {
111
+ let bin = 0;
112
+ while (bin < bins - 1 && value >= cuts[bin + 1])
113
+ bin += 1;
114
+ return palettes.sequential(bins === 1 ? 0.5 : bin / (bins - 1));
115
+ };
116
+ }
117
+ const [lo, hi] = colorDomainOf(domain, options);
118
+ const center = options?.center ?? palettes.center;
119
+ const transform = options?.transform ?? "identity";
120
+ if (transform !== "identity") {
121
+ const { forward, admits } = TRANSFORMS[transform];
122
+ /* A low end with no place sits at zero, or three decades under the top on a log map. */
123
+ const floor = admits(lo) ? lo : isLog(transform) ? (hi > 0 ? hi : 1) / 1000 : 0;
124
+ const place = (value) => forward(admits(value) ? value : floor);
125
+ return (value) => palettes.sequential(rampPosition(place(value), place(floor), place(hi)));
126
+ }
127
+ return (value) => palettes.sequential(rampPosition(value, lo, hi, center));
128
+ }
129
+ /**
130
+ * Which scale the horizontal axis runs.
131
+ *
132
+ * The author's choice wins. Otherwise a numeric field gets a value scale and the rest get bands.
133
+ */
134
+ export function axisKindFor(plot, xField) {
135
+ const declared = plot.scales?.x?.kind;
136
+ if (declared)
137
+ return declared;
138
+ return xField?.numeric ? "continuous" : "band";
139
+ }
140
+ /** The horizontal axis's transform. A stated `transform` wins over the field's log default. */
141
+ export const horizontalTransform = (plot, xField) => plot.scales?.x?.transform ?? (xField?.logScale ? "log10" : "identity");
142
+ /**
143
+ * The vertical axis's transform. A stated `transform` wins over the field's log default.
144
+ *
145
+ * A bar is read as a length from zero and a log scale has no zero. A grounded geom drops the
146
+ * measure's preference.
147
+ */
148
+ export function verticalTransform(declared, fieldLog, grounded) {
149
+ if (declared != null)
150
+ return declared;
151
+ return !grounded && fieldLog ? "log10" : "identity";
152
+ }
153
+ /**
154
+ * Bars an automatic width may draw.
155
+ *
156
+ * Freedman-Diaconis reads the middle half of the data and bounds no interval count.
157
+ */
158
+ export const BIN_CAP = 60;
159
+ /**
160
+ * Bin width by the Freedman-Diaconis rule.
161
+ *
162
+ * Scales with the interquartile range. Falls back to Sturges where the IQR is zero.
163
+ */
164
+ export function autoBinWidth(values) {
165
+ const stats = boxStats(values);
166
+ const n = values.length;
167
+ if (!stats || n < 2)
168
+ return 1;
169
+ const iqr = stats.q3 - stats.q1;
170
+ if (iqr > 0)
171
+ return (2 * iqr) / Math.cbrt(n);
172
+ const [lo, hi] = boundsOf(values);
173
+ const span = hi - lo;
174
+ return span > 0 ? span / Math.ceil(Math.log2(n) + 1) : 1;
175
+ }
176
+ /** Points a violin's outline is drawn with. A vertex count and no claim about the data. */
177
+ const VIOLIN_OUTLINE = 49;
178
+ /** Probabilities a violin marks where the author names none, which is the box's own three. */
179
+ const QUARTILES = [0.25, 0.5, 0.75];
180
+ /**
181
+ * The violins with their widths divided the way `scale` asks.
182
+ *
183
+ * `width` passes through. `area` divides by the tallest density. `count` weights by group size.
184
+ */
185
+ function heldAcross(violins, scale) {
186
+ if (scale === "width")
187
+ return violins;
188
+ let peak = 0;
189
+ let mostReadings = 0;
190
+ for (const violin of violins) {
191
+ for (const value of violin.weight)
192
+ if (value > peak)
193
+ peak = value;
194
+ if (violin.n > mostReadings)
195
+ mostReadings = violin.n;
196
+ }
197
+ if (!(peak > 0))
198
+ return violins;
199
+ return violins.map((violin) => {
200
+ const share = scale === "count" && mostReadings > 0 ? violin.n / mostReadings : 1;
201
+ return { ...violin, weight: violin.weight.map((value) => (value / peak) * share) };
202
+ });
203
+ }
204
+ /** Values of one measure, grouped by a category. What a box needs and an aggregate does not. */
205
+ function valuesByCategory(data, keyField, valueField) {
206
+ const out = new Map();
207
+ for (let row = 0; row < data.rowCount; row += 1) {
208
+ const key = data.text(row, keyField);
209
+ const value = data.number(row, valueField);
210
+ if (key == null || value == null)
211
+ continue;
212
+ const held = out.get(key);
213
+ if (held)
214
+ held.push(value);
215
+ else
216
+ out.set(key, [value]);
217
+ }
218
+ return out;
219
+ }
220
+ /**
221
+ * The binning a series states in `statParams`.
222
+ *
223
+ * None stated answers `auto`, the Freedman-Diaconis width.
224
+ */
225
+ export function binOf(series) {
226
+ const { binwidth, bins, center, boundary, closed, pad, breaks, dropEmpty } = series.statParams ?? {};
227
+ const stated = { binwidth, bins, center, boundary, closed, pad, breaks, dropEmpty };
228
+ return Object.values(stated).every((value) => value == null) ? "auto" : stated;
229
+ }
230
+ /**
231
+ * One bar per distinct reading of a measure on x, each reducing the rows at that reading.
232
+ *
233
+ * The width is the smallest gap between two readings, which is the room a bar has.
234
+ */
235
+ function distinctBars(data, xId, yId, aggregate, transform, halfWidth) {
236
+ const { admits } = TRANSFORMS[transform];
237
+ const buckets = new Map();
238
+ const collected = NEEDS_VALUES.includes(aggregate) ? new Map() : null;
239
+ let offScale = 0;
240
+ for (let row = 0; row < data.rowCount; row += 1) {
241
+ const x = data.number(row, xId);
242
+ if (x == null)
243
+ continue;
244
+ if (!admits(x)) {
245
+ offScale += 1;
246
+ continue;
247
+ }
248
+ const value = yId ? data.number(row, yId) : 1;
249
+ if (value == null)
250
+ continue;
251
+ let bucket = buckets.get(x);
252
+ if (!bucket) {
253
+ bucket = { n: 0, sum: 0, sumSq: 0, min: Infinity, max: -Infinity };
254
+ buckets.set(x, bucket);
255
+ }
256
+ bucket.n += 1;
257
+ bucket.sum += value;
258
+ bucket.sumSq += value * value;
259
+ bucket.min = Math.min(bucket.min, value);
260
+ bucket.max = Math.max(bucket.max, value);
261
+ if (collected)
262
+ collected.set(x, [...(collected.get(x) ?? []), value]);
263
+ }
264
+ const bars = [...buckets]
265
+ .sort(([a], [b]) => a - b)
266
+ .map(([at, bucket]) => ({
267
+ category: String(at),
268
+ at,
269
+ value: reduceBucket(bucket, aggregate, collected?.get(at)),
270
+ n: bucket.n,
271
+ error: halfWidth?.(spreadOf(bucket)),
272
+ }))
273
+ .filter((bar) => Number.isFinite(bar.value));
274
+ return { bars, width: resolutionOf(bars.map((bar) => bar.at)), offScale };
275
+ }
276
+ /**
277
+ * A measure cut into intervals, reduced per interval.
278
+ *
279
+ * The bar draws at the bin's center. A transformed axis is cut in its own space.
280
+ */
281
+ export function binnedBars(data, xId, yId, aggregate, bin, transform = "identity",
282
+ /** Half-width of the interval a bin draws, given its spread. Absent draws none. */
283
+ halfWidth) {
284
+ const { forward: cut, back, admits } = TRANSFORMS[transform];
285
+ const plain = transform === "identity";
286
+ // A log axis has no place for a reading at or below zero, and the scale would map it to NaN.
287
+ const usable = (value) => value != null && admits(value);
288
+ const xs = [];
289
+ let offScale = 0;
290
+ for (let row = 0; row < data.rowCount; row += 1) {
291
+ const value = data.number(row, xId);
292
+ if (usable(value))
293
+ xs.push(cut(value));
294
+ else if (value != null)
295
+ offScale += 1;
296
+ }
297
+ if (xs.length === 0)
298
+ return { bars: [], width: 1, offScale };
299
+ const stated = binOptionsOf(bin, () => autoBinWidth(xs));
300
+ /* A width the rule chose, which is the only one the cap below is allowed to widen. */
301
+ const authored = typeof bin === "number" || (typeof bin === "object" && bin.binwidth != null);
302
+ const chosen = !authored && typeof stated.binwidth === "number" ? stated.binwidth : undefined;
303
+ const range = boundsOf(xs);
304
+ const collects = NEEDS_VALUES.includes(aggregate);
305
+ const cutInto = (edges) => {
306
+ const running = new Map();
307
+ const collected = collects ? new Map() : null;
308
+ for (let row = 0; row < data.rowCount; row += 1) {
309
+ const x = data.number(row, xId);
310
+ if (!usable(x))
311
+ continue;
312
+ const value = yId ? data.number(row, yId) : 1;
313
+ if (value == null)
314
+ continue;
315
+ const index = binIndex(cut(x), edges);
316
+ if (index < 0)
317
+ continue;
318
+ let bucket = running.get(index);
319
+ if (!bucket) {
320
+ bucket = { n: 0, sum: 0, sumSq: 0, min: Infinity, max: -Infinity };
321
+ running.set(index, bucket);
322
+ }
323
+ bucket.n += 1;
324
+ bucket.sum += value;
325
+ bucket.sumSq += value * value;
326
+ bucket.min = Math.min(bucket.min, value);
327
+ bucket.max = Math.max(bucket.max, value);
328
+ if (collected) {
329
+ const held = collected.get(index);
330
+ if (held)
331
+ held.push(value);
332
+ else
333
+ collected.set(index, [value]);
334
+ }
335
+ }
336
+ return { running, collected };
337
+ };
338
+ let edges = binBreaks(range, stated);
339
+ if (!edges)
340
+ return { bars: [], width: 1, offScale };
341
+ let { running, collected } = cutInto(edges);
342
+ /*
343
+ An automatic width that draws hundreds of bars is widened until it draws dozens.
344
+
345
+ Counted on the intervals holding rows. An author who names a width keeps it.
346
+ */
347
+ if (chosen != null && running.size > BIN_CAP) {
348
+ const wider = binBreaks(range, { ...stated, binwidth: (chosen * running.size) / BIN_CAP });
349
+ if (wider) {
350
+ edges = wider;
351
+ ({ running, collected } = cutInto(edges));
352
+ }
353
+ }
354
+ const intervals = stated.pad ? padded(intervalsOf(edges)) : intervalsOf(edges);
355
+ const offset = stated.pad ? 1 : 0;
356
+ const first = intervals[offset]?.width ?? 1;
357
+ const digits = first < 1 ? Math.min(4, Math.ceil(-Math.log10(first)) + 1) : 0;
358
+ const edge = (value) => (plain ? value.toFixed(digits) : back(value).toPrecision(3));
359
+ const empty = { n: 0, sum: 0, sumSq: 0, min: Infinity, max: -Infinity };
360
+ const last = intervals.length - 2 * offset - 1;
361
+ const drawn = intervals.map((interval, at) => {
362
+ const index = at - offset;
363
+ const bucket = running.get(index) ?? empty;
364
+ /* An edge reading lands on the side `closed` names. The outermost interval also holds its outer edge. */
365
+ const fromHeld = edges.rightClosed ? index === 0 : index <= last;
366
+ const toHeld = edges.rightClosed ? index >= 0 : index === last;
367
+ const closed = fromHeld && toHeld ? "both" : fromHeld ? "left" : toHeld ? "right" : "neither";
368
+ return {
369
+ interval,
370
+ bar: {
371
+ // The label names the interval. A reader taking a count wants its edges.
372
+ category: `${edge(interval.from)} to ${edge(interval.to)}`,
373
+ // The center of the interval, which on a log axis is the geometric middle of its ends.
374
+ at: back(interval.at),
375
+ bin: {
376
+ from: back(interval.from),
377
+ to: back(interval.to),
378
+ closed,
379
+ },
380
+ value: reduceBucket(bucket, aggregate, collected?.get(at - offset)),
381
+ n: bucket.n,
382
+ error: halfWidth?.(spreadOf(bucket)),
383
+ },
384
+ };
385
+ });
386
+ /*
387
+ An interval nothing landed in counts zero and has no mean.
388
+
389
+ A reduction with no answer for an empty interval leaves it out whatever the drop says.
390
+ */
391
+ const answerable = drawn.filter((held) => Number.isFinite(held.bar.value));
392
+ const bars = keptUnder(answerable, (held) => held.bar.n > 0, stated.dropEmpty ?? "none").map((held) => held.bar);
393
+ // In the measure's own units. The caller draws a single bar from it.
394
+ return { bars, width: plain ? first : back(range[0] + first) - back(range[0]), offScale };
395
+ }
396
+ /**
397
+ * Every distinct value of a category, in first-seen order over the table.
398
+ *
399
+ * Built before any narrowing, which keeps a value's color stable.
400
+ */
401
+ function codesOf(data, field) {
402
+ const read = textReader(data, field);
403
+ const codes = new Map();
404
+ for (let row = 0; row < data.rowCount; row += 1) {
405
+ const value = read(row);
406
+ if (value != null && !codes.has(value))
407
+ codes.set(value, codes.size);
408
+ }
409
+ return codes;
410
+ }
411
+ /**
412
+ * Rows of the table under each value of a field, in first-seen order.
413
+ *
414
+ * Row indices. Splitting 250k rows costs one pass and one array of numbers per group.
415
+ */
416
+ export function rowsByValue(data, field) {
417
+ const read = textReader(data, field);
418
+ const out = new Map();
419
+ for (let row = 0; row < data.rowCount; row += 1) {
420
+ const value = read(row);
421
+ if (value == null)
422
+ continue;
423
+ const held = out.get(value);
424
+ if (held)
425
+ held.push(row);
426
+ else
427
+ out.set(value, [row]);
428
+ }
429
+ return out;
430
+ }
431
+ /**
432
+ * The table narrowed to some of its rows.
433
+ *
434
+ * A split trace reads one group. Narrowing here keeps a per-group count honest.
435
+ */
436
+ export function viewOf(data, rows) {
437
+ const numbers = data.numbers?.bind(data);
438
+ const texts = data.texts?.bind(data);
439
+ const outer = viewRows.get(data);
440
+ const view = {
441
+ fields: data.fields,
442
+ rowCount: rows.length,
443
+ number: (row, field) => data.number(rows[row], field),
444
+ text: (row, field) => data.text(rows[row], field),
445
+ rowIndex: (row) => data.rowIndex(rows[row]),
446
+ keyField: data.keyField,
447
+ /* The parent's columns, gathered to this view's rows. */
448
+ numbers: numbers &&
449
+ ((field) => {
450
+ const column = numbers(field);
451
+ return column && Float64Array.from(rows, (row) => column[row] ?? NaN);
452
+ }),
453
+ texts: texts &&
454
+ ((field) => {
455
+ const column = texts(field);
456
+ return column && rows.map((row) => column[row] ?? null);
457
+ }),
458
+ };
459
+ viewRows.set(view, outer ? rows.map((row) => outer[row]) : rows);
460
+ return view;
461
+ }
462
+ /** Each view's rows in the table the figure read, composed through a view of a view. */
463
+ const viewRows = new WeakMap();
464
+ /** Reads a numeric field by row, from the whole column where the table offers one. */
465
+ function numberReader(data, field) {
466
+ const column = data.numbers?.(field);
467
+ if (!column)
468
+ return (row) => data.number(row, field);
469
+ return (row) => {
470
+ const value = column[row];
471
+ return value === undefined || Number.isNaN(value) ? null : value;
472
+ };
473
+ }
474
+ /** Reads a field's display text by row, from the whole column where the table offers one. */
475
+ function textReader(data, field) {
476
+ const column = data.texts?.(field);
477
+ if (!column)
478
+ return (row) => data.text(row, field);
479
+ return (row) => column[row] ?? null;
480
+ }
481
+ /** Range of a numeric field over the whole table, for a color ramp that holds across traces. */
482
+ function rangeOf(data, field) {
483
+ const read = numberReader(data, field);
484
+ let lo = Infinity;
485
+ let hi = -Infinity;
486
+ for (let row = 0; row < data.rowCount; row += 1) {
487
+ const value = read(row);
488
+ if (value == null)
489
+ continue;
490
+ if (value < lo)
491
+ lo = value;
492
+ if (value > hi)
493
+ hi = value;
494
+ }
495
+ return Number.isFinite(lo) ? [lo, hi] : null;
496
+ }
497
+ /** The two ends a bound opacity runs between. The low end clears the page. */
498
+ export const ALPHA_RANGE = [0.2, 1];
499
+ /** One level per value, in the order the codes handed them out, for the guide to draw. */
500
+ const levelsOf = (channel) => [...channel.codes]
501
+ .sort((a, b) => a[1] - b[1])
502
+ .map(([value, code]) => ({ value, at: channel.levels[code % channel.levels.length] }));
503
+ /** Where one reading falls between the two ends of a bound opacity. */
504
+ const opacityAt = (value, [lo, hi]) => {
505
+ const [low, high] = ALPHA_RANGE;
506
+ const span = hi - lo;
507
+ return span === 0 ? high : low + Math.min(1, Math.max(0, (value - lo) / span)) * (high - low);
508
+ };
509
+ function pointsOf(data, xId, yId, labelField, colorField, codes, size, zField,
510
+ /** First-seen code per category, where the horizontal axis runs bands. Absent reads a value scale. */
511
+ bands = null,
512
+ /** What a jitter position stated, in data units. Absent moves nothing. */
513
+ along,
514
+ /** A fixed offset, where the series asked for a nudge. */
515
+ shift,
516
+ /** Glyph per level, where the shape channel is bound. */
517
+ shapes = null,
518
+ /** Opacity per level or across a range, where the opacity channel is bound. */
519
+ opacities = null) {
520
+ const points = [];
521
+ const readX = numberReader(data, xId);
522
+ const readY = numberReader(data, yId);
523
+ const readZ = zField ? numberReader(data, zField.id) : null;
524
+ const readWeight = colorField?.numeric ? numberReader(data, colorField.id) : null;
525
+ const readSize = size ? numberReader(data, size.field.id) : null;
526
+ const readOpacity = opacities?.domain ? numberReader(data, opacities.field.id) : null;
527
+ const readCategory = bands ? textReader(data, xId) : null;
528
+ const readColor = colorField && !colorField.numeric && codes ? textReader(data, colorField.id) : null;
529
+ const readShape = shapes ? textReader(data, shapes.field.id) : null;
530
+ const readLevel = opacities?.codes ? textReader(data, opacities.field.id) : null;
531
+ const readKey = data.keyField ? textReader(data, data.keyField) : null;
532
+ const readLabel = labelField ? textReader(data, labelField.id) : null;
533
+ const outer = viewRows.get(data);
534
+ for (let row = 0; row < data.rowCount; row += 1) {
535
+ /* On a band the reading is the name, and the index beside it is what the numeric readers take. */
536
+ const category = readCategory ? readCategory(row) : null;
537
+ const x = bands ? (category == null ? null : (bands.get(category) ?? null)) : readX(row);
538
+ const y = readY(row);
539
+ // A row missing either channel drops out. An unmeasured endpoint is no reading of zero.
540
+ if (x == null || y == null)
541
+ continue;
542
+ /* A cube drops a row missing its third reading for the reason the pair are dropped: a geom on
543
+ the floor claims a measurement of zero somebody did not take. */
544
+ let z;
545
+ if (readZ) {
546
+ const value = readZ(row);
547
+ if (value == null)
548
+ continue;
549
+ z = value;
550
+ }
551
+ let weight;
552
+ if (readWeight) {
553
+ const value = readWeight(row);
554
+ if (value != null)
555
+ weight = value;
556
+ }
557
+ else if (readColor && codes) {
558
+ const value = readColor(row);
559
+ if (value != null)
560
+ weight = codes.get(value);
561
+ }
562
+ /* A row with no reading on the size field draws at the layer's own radius, which is the geom
563
+ the chart shows for everything else it cannot size. */
564
+ let radius;
565
+ let sizeValue;
566
+ if (size && readSize) {
567
+ const value = readSize(row);
568
+ if (value != null) {
569
+ sizeValue = value;
570
+ radius = sizeRadius(value, size.domain[0], size.domain[1], size.radii);
571
+ }
572
+ }
573
+ /*
574
+ A row with no reading on either channel draws what the layer draws.
575
+
576
+ A glyph reads its level off the category's own code. An opacity takes the same route.
577
+ */
578
+ let shape;
579
+ if (shapes && readShape) {
580
+ const value = readShape(row);
581
+ const code = value == null ? undefined : shapes.codes.get(value);
582
+ if (code != null)
583
+ shape = shapes.levels[code % shapes.levels.length];
584
+ }
585
+ let opacity;
586
+ if (opacities?.domain && readOpacity) {
587
+ const value = readOpacity(row);
588
+ if (value != null)
589
+ opacity = opacityAt(value, opacities.domain);
590
+ }
591
+ else if (opacities?.codes && readLevel) {
592
+ const value = readLevel(row);
593
+ const code = value == null ? undefined : opacities.codes.get(value);
594
+ const steps = Math.max(1, opacities.codes.size - 1);
595
+ if (code != null)
596
+ opacity = opacityAt(code, [0, steps]);
597
+ }
598
+ /* A fixed key set, absent values included. The points share one hidden class. */
599
+ points.push({
600
+ x,
601
+ category: category ?? undefined,
602
+ y,
603
+ z,
604
+ weight,
605
+ size: radius,
606
+ sizeValue,
607
+ shape,
608
+ opacity,
609
+ key: readKey ? (readKey(row) ?? undefined) : undefined,
610
+ text: readLabel ? (readLabel(row) ?? undefined) : undefined,
611
+ row: data.rowIndex(row),
612
+ plotRow: outer ? outer[row] : row,
613
+ });
614
+ }
615
+ if (along)
616
+ nudge(points, along, bands != null, readColor && codes ? codes.size : 1);
617
+ if (shift)
618
+ shove(points, shift);
619
+ return points;
620
+ }
621
+ /**
622
+ * A column's recording resolution. The smallest gap between two readings that differ.
623
+ *
624
+ * What a jitter is measured against, ggplot's `resolution()`. A column of one reading has
625
+ * resolution 1.
626
+ */
627
+ function resolutionOf(values) {
628
+ const sorted = [...new Set(values)].sort((a, b) => a - b);
629
+ let gap = Infinity;
630
+ for (let i = 1; i < sorted.length; i += 1) {
631
+ const step = sorted[i] - sorted[i - 1];
632
+ if (step > 0 && step < gap)
633
+ gap = step;
634
+ }
635
+ return Number.isFinite(gap) ? gap : 1;
636
+ }
637
+ /** The share of an axis's resolution a jitter spreads over where the position states no amount. ggplot's 0.4. */
638
+ const JITTER_SHARE = 0.4;
639
+ /** Width a jitterdodge's dodged set spans where the position states none, in data units. ggplot's 0.75. */
640
+ const DODGE_WIDTH = 0.75;
641
+ /**
642
+ * Nudges each geom off its reading, deterministically. ggplot's `position_jitter` and
643
+ * `position_jitterdodge`.
644
+ *
645
+ * The offset is uniform in plus or minus the stated amount, in data units. An unstated axis takes
646
+ * 0.4 times its resolution, and a band axis has resolution 1. The row index seeds the offset.
647
+ *
648
+ * A dodge moves each color level into its own slot first. Its jitter is ggplot's: across, the width
649
+ * over the level count plus two, and along y, none unless stated.
650
+ */
651
+ function nudge(points, along, band, levels) {
652
+ const resolutionX = band ? 1 : resolutionOf(points.map((point) => point.x));
653
+ const spanX = (along.x ?? JITTER_SHARE * resolutionX) / (along.dodge == null ? 1 : levels + 2);
654
+ const spanY = along.y ?? (along.dodge == null ? JITTER_SHARE * resolutionOf(points.map((point) => point.y)) : 0);
655
+ /* ggplot's `pos_dodge`: the set spans the dodge width, and each level takes the slot its code names. */
656
+ const { dodge } = along;
657
+ if (dodge != null)
658
+ for (const point of points)
659
+ point.dx = (((point.weight ?? 0) + 0.5) / levels - 0.5) * dodge;
660
+ if (spanX === 0 && spanY === 0)
661
+ return;
662
+ /*
663
+ A seed shifts the hash. The offsets come off the row and one spec draws one picture.
664
+ */
665
+ const seed = along.seed ?? 0;
666
+ for (let i = 0; i < points.length; i += 1) {
667
+ const point = points[i];
668
+ /* Two decorrelated streams off one index. No geom is nudged along the diagonal. */
669
+ const a = Math.sin((point.row + seed) * 12.9898) * 43758.5453;
670
+ const b = Math.sin((point.row + seed) * 78.233) * 12345.6789;
671
+ if (spanX > 0)
672
+ point.dx = (point.dx ?? 0) + (2 * (a - Math.floor(a)) - 1) * spanX;
673
+ if (spanY > 0)
674
+ point.dy = (2 * (b - Math.floor(b)) - 1) * spanY;
675
+ }
676
+ }
677
+ /** Moves a geom a fixed distance in the axes' own units. ggplot's `position_nudge`. */
678
+ function shove(points, by) {
679
+ for (const point of points) {
680
+ if (by.x)
681
+ point.dx = (point.dx ?? 0) + by.x;
682
+ if (by.y)
683
+ point.dy = (point.dy ?? 0) + by.y;
684
+ }
685
+ }
686
+ /**
687
+ * Traces one split may produce.
688
+ *
689
+ * Past two dozen the palette repeats itself. The largest groups are kept and the footer counts
690
+ * the rest.
691
+ */
692
+ export const SPLIT_CAP = 24;
693
+ /**
694
+ * Whether the color a series draws is the author's to pick.
695
+ *
696
+ * A bound color channel paints from a column. A `group` split keeps the one color.
697
+ */
698
+ export const drawsOneColor = (series) => !paintColumn(series);
699
+ /**
700
+ * Geometries that draw one mark over the whole trace.
701
+ *
702
+ * A dimension on the color channel cuts these into a trace per value. A point geometry paints
703
+ * mark by mark.
704
+ */
705
+ const MERGED_GEOMS = [
706
+ "line",
707
+ "smooth",
708
+ "area",
709
+ "freqpoly",
710
+ "density",
711
+ "bar",
712
+ "ribbon",
713
+ "range",
714
+ "segment",
715
+ "hline",
716
+ "vline",
717
+ "abline",
718
+ "text",
719
+ ];
720
+ /** The kinds that stack their groups where the layer states no position, ggplot's `position = "stack"`. */
721
+ const STACKED_KINDS = ["bar", "histogram", "area"];
722
+ /** The reference geoms, which place their own lines and read no shared X. */
723
+ const RULE_GEOMS = ["hline", "vline", "abline"];
724
+ /** The shared X a reference line is handed where the chart binds none. It reads no field. */
725
+ const NO_FIELD = { id: "", label: "", numeric: true };
726
+ export function buildLayers(plot, data, { palettes, pinned, metrics = REGULAR, facet }) {
727
+ const fieldAt = new Map(data.fields.map((field) => [field.id, field]));
728
+ const visible = plot.layers.filter((series) => series.visible !== false);
729
+ /* Each layer's own rows, read once. ggplot's `data` per layer. */
730
+ const tables = new Map();
731
+ for (const series of visible)
732
+ if (series.data)
733
+ tables.set(series.id, ownTable(series.data, fieldAt));
734
+ const tableOf = (series) => tables.get(series.id) ?? data;
735
+ const fieldMaps = new Map([[data, fieldAt]]);
736
+ const fieldsOf = (table) => {
737
+ let held = fieldMaps.get(table);
738
+ if (!held) {
739
+ held = new Map(table.fields.map((field) => [field.id, field]));
740
+ fieldMaps.set(table, held);
741
+ }
742
+ return held;
743
+ };
744
+ /* The axis reads the first layer binding an x over the chart's rows, then any layer. Each places its own. */
745
+ const bindsX = (series) => typeof series.aes.x === "string";
746
+ const xSeries = visible.find((series) => bindsX(series) && !series.data) ?? visible.find(bindsX);
747
+ const xId = xSeries?.aes.x;
748
+ const xField = xSeries && xId ? fieldsOf(tableOf(xSeries)).get(xId) : undefined;
749
+ const axisKind = axisKindFor(plot, xField);
750
+ const traces = [];
751
+ const unbuilt = [];
752
+ const omitted = [];
753
+ /* Each category a keyed map misses, per paint column. The footer counts it once across the layers. */
754
+ const offMap = new Set();
755
+ /*
756
+ Both color maps are read off the whole table and cached. A trace sees one group.
757
+
758
+ A figure set's assignments displace the ordering here.
759
+ */
760
+ const codeCache = new Map();
761
+ const codesFor = (fieldId) => {
762
+ let codes = codeCache.get(fieldId);
763
+ if (!codes) {
764
+ /* The chart's table first, then each layer's. A value two tables share takes one code. */
765
+ const seen = codesOf(data, fieldId);
766
+ for (const table of tables.values()) {
767
+ for (const value of codesOf(table, fieldId).keys())
768
+ if (!seen.has(value))
769
+ seen.set(value, seen.size);
770
+ }
771
+ codes = pinnedOver(seen, pinned?.[fieldId]);
772
+ codeCache.set(fieldId, codes);
773
+ }
774
+ return codes;
775
+ };
776
+ const rangeCache = new Map();
777
+ const rangeFor = (fieldId) => {
778
+ if (!rangeCache.has(fieldId)) {
779
+ const ends = [data, ...tables.values()].flatMap((table) => rangeOf(table, fieldId) ?? []);
780
+ rangeCache.set(fieldId, ends.length === 0 ? null : boundsOf(ends));
781
+ }
782
+ return rangeCache.get(fieldId);
783
+ };
784
+ visible.forEach((series, index) => {
785
+ const geom = geomFor(series.kind);
786
+ if (!geom) {
787
+ unbuilt.push(series.kind);
788
+ return;
789
+ }
790
+ /* The rows this layer reads, and a trace that says where they came from. */
791
+ const table = tableOf(series);
792
+ const fields = fieldsOf(table);
793
+ /* A reference line mapping neither color nor dash names nothing a legend could key, as in ggplot. */
794
+ const rule = RULE_GEOMS.includes(geom);
795
+ const unkeyed = (rule && series.showLegend !== true && !paintColumn(series) && !series.aes.linetype) ||
796
+ (geom === "text" && series.showLegend !== true);
797
+ const push = (trace) => traces.push({
798
+ ...trace,
799
+ ...(table === data ? {} : { table }),
800
+ ...(series.showLegend === false || unkeyed ? { showLegend: false } : {}),
801
+ ...(facet && fields.has(facet.field.id) ? { facetField: facet.field, facetValue: facet.value } : {}),
802
+ });
803
+ /* A categorical map the series named, which colors its categories by position. */
804
+ const identity = series.palette ? palettes.categoricalFor?.(series.palette) : undefined;
805
+ /*
806
+ The palette's color. `paint` applies the author's after the build.
807
+ */
808
+ const color = (identity ?? palettes).categorical(index);
809
+ /* The magnitude map, where the series named one of its own. Every ramped geom reads it. */
810
+ const sequential = series.palette ? palettes.sequentialFor?.(series.palette) : undefined;
811
+ const painted = { ...palettes, ...(sequential ? { sequential } : {}), ...identity };
812
+ if (geom === "sankey") {
813
+ const built = flowTrace(series, table, fields, color);
814
+ if (built) {
815
+ push(built.trace);
816
+ omit(omitted, "flows", built.dropped);
817
+ }
818
+ return;
819
+ }
820
+ /* A genome round a circle. The sectors come off the rows and carry their own ranges. */
821
+ if (geom === "ideogram") {
822
+ const built = ideogramTrace(series, table, fields, color);
823
+ if (built) {
824
+ push(sequential ? { ...built.trace, sequential } : built.trace);
825
+ omit(omitted, "categories", built.dropped);
826
+ omit(omitted, "links", built.offSector);
827
+ omit(omitted, "colors", flattened(built.hued, palettes.categoricalSize, series.style?.fill));
828
+ }
829
+ return;
830
+ }
831
+ /* The same pairs, closed into a circle. The sectors come off the links the flow builds. */
832
+ if (geom === "chord") {
833
+ const built = chordTrace(series, table, fields, color);
834
+ if (built) {
835
+ push(sequential ? { ...built.trace, sequential } : built.trace);
836
+ omit(omitted, "flows", built.dropped);
837
+ omit(omitted, "colors", flattened(built.hued, palettes.categoricalSize, series.style?.fill));
838
+ }
839
+ return;
840
+ }
841
+ if (geom === "treemap" || geom === "icicle" || geom === "sunburst") {
842
+ const built = hierarchyTrace(series, geom, table, fields, color, painted.categorical);
843
+ if (built) {
844
+ push(built.trace);
845
+ omit(omitted, "categories", built.dropped);
846
+ omit(omitted, "colors", flattened(built.hued, painted.categoricalSize, series.style?.fill));
847
+ }
848
+ return;
849
+ }
850
+ /* One rule per measure, laid out along a row or round a center. The payload is the same either way. */
851
+ if (geom === "parcoords" || geom === "radar") {
852
+ const built = parallelTrace(series, geom, table, fields, color, painted, codesFor, rangeFor, layerScale(plot, series));
853
+ if (built) {
854
+ /* The series' own map, held on the trace. `paint` rebuilds the ramp off it. */
855
+ push(sequential ? { ...built.trace, sequential } : built.trace);
856
+ omit(omitted, "rows-sampled", built.skipped);
857
+ omit(omitted, "rows-incomplete", built.incomplete);
858
+ omit(omitted, "measures", built.axesDropped);
859
+ }
860
+ return;
861
+ }
862
+ /* A dial binds one magnitude and reads its ends off the vertical axis. No shared X. */
863
+ if (geom === "gauge") {
864
+ const built = gaugeTrace(series, table, fields, color, rangeFor, plot.scales?.y?.limits);
865
+ if (built)
866
+ push(sequential ? { ...built, sequential } : built);
867
+ return;
868
+ }
869
+ /* A layer places its own x where it binds one, which is ggplot's mapping per layer. */
870
+ const ownX = typeof series.aes.x === "string" ? series.aes.x : xId;
871
+ const ownXField = ownX ? fields.get(ownX) : undefined;
872
+ if (!rule && (!ownX || !ownXField))
873
+ return;
874
+ /*
875
+ A series states its own color scale over the chart's, field by field, on its paint aesthetic.
876
+
877
+ Merged. A series naming a title alone keeps the chart's range under it.
878
+ */
879
+ const colorOptions = layerScale(plot, series);
880
+ const shared = {
881
+ fieldAt: fields,
882
+ xId: ownX ?? "",
883
+ xField: ownXField ?? NO_FIELD,
884
+ axisKind,
885
+ xTransform: horizontalTransform(plot, xField),
886
+ palettes: painted,
887
+ codesFor,
888
+ rangeFor,
889
+ metrics,
890
+ colorOptions,
891
+ omitted,
892
+ };
893
+ /*
894
+ A dash belongs to a path. Binding it cuts the series.
895
+
896
+ A series naming both fields splits on the author's and reads the dash off each trace.
897
+ */
898
+ const dashId = typeof series.aes.linetype === "string" &&
899
+ kindFacts(series.kind).accepts.includes("linetype")
900
+ ? series.aes.linetype
901
+ : undefined;
902
+ const dashField = dashId ? fields.get(dashId) : undefined;
903
+ const dashes = dashField && !dashField.numeric ? dashField : undefined;
904
+ /*
905
+ A dimension on the color channel, where the geom draws one mark over its records.
906
+
907
+ A merged geom has no per-record mark to paint. A fit draws a curve per color, as ggplot's does.
908
+ */
909
+ const colorId = paintColumn(series);
910
+ /* The host's keyed map on the paint column. The footer counts the categories it misses, and a grid counts its own cells. */
911
+ const keyed = colorOptions?.values;
912
+ const paintField = colorId ? fields.get(colorId) : undefined;
913
+ const missKeyed = (column, levels) => {
914
+ for (const level of levels)
915
+ if (keyed && !Object.hasOwn(keyed, level))
916
+ offMap.add(`${column}\u0000${level}`);
917
+ };
918
+ const colorSplit = colorId && (MERGED_GEOMS.includes(geom) || series.fit) ? fields.get(colorId) : undefined;
919
+ /* ggplot's `group` cuts the paths and leaves their color and dash to the channels that name them. */
920
+ const groupId = typeof series.aes.group === "string" ? series.aes.group : undefined;
921
+ const splitId = groupId ?? (colorSplit?.numeric === false ? colorSplit.id : undefined) ?? dashes?.id;
922
+ const splitField = splitId ? fields.get(splitId) : undefined;
923
+ /* The pattern a trace draws, read off the value its own rows hold on the dash column. */
924
+ const dashCodes = dashes ? codesFor(dashes.id) : null;
925
+ const dashFor = (value) => {
926
+ if (!dashes || !dashCodes || value == null)
927
+ return undefined;
928
+ const code = dashCodes.get(value) ?? 0;
929
+ return { field: dashes, at: LINETYPES[code % LINETYPES.length], value };
930
+ };
931
+ /* What the series painted with. A later rebuild reads it back. */
932
+ const own = {
933
+ ...(sequential ? { sequential } : {}),
934
+ ...(series.scales?.[paintAesthetic(series)] ? { colorOptions } : {}),
935
+ };
936
+ if (!splitField) {
937
+ const built = traceOf(series, geom, { ...shared, data: table, color });
938
+ if (built) {
939
+ /* A geom that paints by value, such as a box, takes no category and draws none muted. */
940
+ if (paintField && !paintField.numeric && built.colorLevels && geom !== "heatmap") {
941
+ missKeyed(paintField.id, pointLevels(built) ?? rowsByValue(table, paintField.id).keys());
942
+ }
943
+ push({ ...built, ...own });
944
+ }
945
+ return;
946
+ }
947
+ /*
948
+ The split value owns the color and the series owns the geom. An explicit series color is
949
+ dropped here.
950
+ */
951
+ const codes = codesFor(splitField.id);
952
+ const groups = [...rowsByValue(table, splitField.id)].sort((a, b) => b[1].length - a[1].length);
953
+ omit(omitted, "splits", Math.max(0, groups.length - SPLIT_CAP));
954
+ /* A split naming a sequential map steps along it in code order, where no other color column paints it. */
955
+ const steps = sequential && !identity && (colorId == null || colorId === splitField.id) ? Math.max(1, codes.size - 1) : 0;
956
+ const splitColor = (value) => keyed && splitField.id === colorId
957
+ ? keyedInk(keyed, value)
958
+ : steps > 0
959
+ ? sequential((codes.get(value) ?? 0) / steps)
960
+ : painted.categorical(codes.get(value) ?? 0);
961
+ /* A color column apart from the split paints each group by its own value, which is ggplot's color beside group. */
962
+ const colorField = colorId ? fields.get(colorId) : undefined;
963
+ const tinted = colorField && !colorField.numeric && colorField.id !== splitField.id ? colorField : undefined;
964
+ const tints = tinted ? codesFor(tinted.id) : null;
965
+ const tintLevels = tints
966
+ ? [...tints].map(([level, code]) => ({ value: level, code })).sort((a, b) => a.code - b.code)
967
+ : undefined;
968
+ const groupColor = (value, first) => {
969
+ if (tinted && tints) {
970
+ const level = first == null ? null : table.text(first, tinted.id);
971
+ if (keyed)
972
+ return keyedInk(keyed, level);
973
+ return painted.categorical(level == null ? 0 : (tints.get(level) ?? 0));
974
+ }
975
+ return groupId && !(keyed && splitField.id === colorId) ? color : splitColor(value);
976
+ };
977
+ /* A color split beside its own dash column cuts each group again at each dash value. ggplot's default group crosses both. */
978
+ const crossed = groupId == null && dashes != null && dashes.id !== splitField.id;
979
+ /* One group's rows, parted by the value each holds on a column. A missing value parts on its own. */
980
+ const partedBy = (rows, fieldId) => {
981
+ const parts = new Map();
982
+ for (const row of rows) {
983
+ const level = table.text(row, fieldId);
984
+ const part = parts.get(level);
985
+ if (part)
986
+ part.push(row);
987
+ else
988
+ parts.set(level, [row]);
989
+ }
990
+ return [...parts];
991
+ };
992
+ const paths = groups
993
+ .slice(0, SPLIT_CAP)
994
+ .flatMap(([value, rows]) => crossed && dashes
995
+ ? partedBy(rows, dashes.id).map(([level, part]) => [value, part, level])
996
+ : [[value, rows, undefined]]);
997
+ /* Groups over several dash values. One path draws one pattern, its first row's. */
998
+ let mixedDashes = 0;
999
+ for (const [value, rows, level] of paths) {
1000
+ const drawn = groupColor(value, rows[0]);
1001
+ const built = traceOf(series, geom, {
1002
+ ...shared,
1003
+ data: viewOf(table, rows),
1004
+ color: drawn,
1005
+ });
1006
+ if (!built)
1007
+ continue;
1008
+ /* A point paints each record's category, and a path its first row's. */
1009
+ if (tinted) {
1010
+ const first = rows[0] == null ? null : table.text(rows[0], tinted.id);
1011
+ missKeyed(tinted.id, pointLevels(built, tintLevels) ?? (first == null ? [] : [first]));
1012
+ }
1013
+ else if (splitField.id === colorId)
1014
+ missKeyed(splitField.id, [value]);
1015
+ const held = dashes ? rows.flatMap((row) => table.text(row, dashes.id) ?? []) : [];
1016
+ if (new Set(held).size > 1)
1017
+ mixedDashes += 1;
1018
+ const dash = dashFor(held[0]);
1019
+ push({
1020
+ ...built,
1021
+ ...own,
1022
+ id: level === undefined ? `${series.id}:${value}` : `${series.id}:${value}:${level ?? ""}`,
1023
+ name: groupId ? built.name : value,
1024
+ splitValue: value,
1025
+ splitField,
1026
+ ...(groupId ? { grouped: true } : {}),
1027
+ ...(tinted && tints && tintLevels
1028
+ ? {
1029
+ color: drawn,
1030
+ colorField: tinted,
1031
+ colorLevels: tintLevels,
1032
+ ramp: keyed
1033
+ ? codeRamp(series, tints, painted, colorOptions)
1034
+ : ((code) => painted.categorical(Math.round(code))),
1035
+ }
1036
+ : {}),
1037
+ ...(dash ? { linetypeChannel: dash } : {}),
1038
+ });
1039
+ }
1040
+ omit(omitted, "dashes", mixedDashes);
1041
+ });
1042
+ if (offMap.size > 0)
1043
+ omitted.push({ of: "fills", count: offMap.size, levels: [...offMap] });
1044
+ const order = plot.scales?.x?.order;
1045
+ const accrued = stepped(accumulated(traces, axisKind === "band", order, visible), order);
1046
+ const along = axisKind === "band" ? orderBand(order, [...new Set(accrued.flatMap(categoriesOf))], () => null).values : undefined;
1047
+ const positioned = adjusted(accrued, visible, along);
1048
+ flag(omitted, "stack", positioned.negativeStack);
1049
+ const fields = [...tables.values()].flatMap((table) => table.fields).filter((field) => !fieldAt.has(field.id));
1050
+ return { traces: positioned.traces, axisKind, xField, fields, unbuilt, omitted };
1051
+ }
1052
+ /**
1053
+ * A layer's rows as a table.
1054
+ *
1055
+ * A column the chart's table also holds takes that field's label, unit, digits and scale flags.
1056
+ */
1057
+ function ownTable(rows, fieldAt) {
1058
+ const shared = {};
1059
+ for (const row of rows) {
1060
+ for (const key of Object.keys(row)) {
1061
+ const field = fieldAt.get(key);
1062
+ if (!field || key in shared)
1063
+ continue;
1064
+ const { label, unit, digits, logScale, timeScale } = field;
1065
+ shared[key] = Object.fromEntries(Object.entries({ label, unit, digits, logScale, timeScale }).filter(([, value]) => value !== undefined));
1066
+ }
1067
+ }
1068
+ return toPlotData(rows, { fieldOverrides: shared });
1069
+ }
1070
+ /**
1071
+ * Position adjustment -- what happens where two geoms share a band.
1072
+ *
1073
+ * Runs over the built traces. A floor per geom, and geoms naming one adjustment adjust together.
1074
+ */
1075
+ function adjusted(traces, series, along) {
1076
+ /*
1077
+ A grouped bar, histogram or area stacks where the author states no position, as ggplot's do.
1078
+
1079
+ The default stacks a layer's own groups and none of another layer's. A layer drawing one trace
1080
+ has nothing to stack.
1081
+ */
1082
+ const tracesOf = new Map();
1083
+ for (const trace of traces)
1084
+ tracesOf.set(trace.layerId, (tracesOf.get(trace.layerId) ?? 0) + 1);
1085
+ const defaulted = new Set(series
1086
+ .filter((one) => one.position == null && STACKED_KINDS.includes(one.kind) && (tracesOf.get(one.id) ?? 0) > 1)
1087
+ .map((one) => one.id));
1088
+ const asked = new Map(series.map((one) => [one.id, one.position ?? (defaulted.has(one.id) ? "stack" : "identity")]));
1089
+ /*
1090
+ `"bars" in data` is the arm's discriminator, the way `"mesh" in data` picks out a cube's.
1091
+
1092
+ A waterfall shares that payload and comes out. `stepped` resolved its floors.
1093
+ */
1094
+ const barsOf = (trace) => trace.data.at === "groups" && "bars" in trace.data && trace.data.geom !== "waterfall" ? trace.data : null;
1095
+ /*
1096
+ Grouped by the adjustment's name. Two layers naming one of them adjust together, and a default
1097
+ stack keeps to its own layer.
1098
+
1099
+ The parameters travel beside it. The first statement wins and the group keeps it.
1100
+ */
1101
+ const groups = new Map();
1102
+ traces.forEach((trace, index) => {
1103
+ const position = asked.get(trace.layerId);
1104
+ const kind = positionKind(position);
1105
+ /* `jitter` and `nudge` offset the mark itself. `jitterOf` and `shoveOf` carry them. */
1106
+ if (kind === "identity" || kind === "jitter" || kind === "nudge" || !barsOf(trace))
1107
+ return;
1108
+ const key = defaulted.has(trace.layerId) ? `${kind}:${trace.layerId}` : kind;
1109
+ const held = groups.get(key);
1110
+ if (held)
1111
+ held.members.push(index);
1112
+ else
1113
+ groups.set(key, { position: kind, members: [index], args: positionArgs(position) });
1114
+ });
1115
+ if (groups.size === 0)
1116
+ return { traces, negativeStack: false };
1117
+ const out = [...traces];
1118
+ let negativeStack = false;
1119
+ for (const { position, members: asWritten, args } of groups.values()) {
1120
+ /* ggplot's `reverse`, which hands the slots out the other way round. */
1121
+ const members = args.reverse ? [...asWritten].reverse() : asWritten;
1122
+ /*
1123
+ A dodge, and `dodge2` with it. Both divide the band one way.
1124
+
1125
+ `preserve` decides the slot count. `total` is the default, as in ggplot: each band divides by
1126
+ the bars it holds, and each bar takes its rank among them. `single` counts the traces.
1127
+ */
1128
+ if (position === "dodge" || position === "dodge2" || position === "jitterdodge") {
1129
+ const total = args.preserve !== "single";
1130
+ const present = new Map();
1131
+ const rank = new Map();
1132
+ if (total) {
1133
+ for (const at of members) {
1134
+ const ranks = new Map();
1135
+ for (const one of barsOf(out[at])?.bars ?? []) {
1136
+ ranks.set(one.category, present.get(one.category) ?? 0);
1137
+ present.set(one.category, (present.get(one.category) ?? 0) + 1);
1138
+ }
1139
+ rank.set(at, ranks);
1140
+ }
1141
+ }
1142
+ /* A jitterdodge's set spans its `dodgeWidth`. Its `width` is the jitter's. */
1143
+ const width = position === "jitterdodge" ? (args.dodgeWidth ?? DODGE_WIDTH) : args.width;
1144
+ members.forEach((at, index) => {
1145
+ const data = barsOf(out[at]);
1146
+ if (!data)
1147
+ return;
1148
+ const bars = total
1149
+ ? data.bars.map((one) => ({
1150
+ ...one,
1151
+ slotOf: present.get(one.category) ?? members.length,
1152
+ slotAt: rank.get(at)?.get(one.category) ?? index,
1153
+ }))
1154
+ : data.bars;
1155
+ out[at] = {
1156
+ ...out[at],
1157
+ data: {
1158
+ ...data,
1159
+ bars,
1160
+ slot: { index, of: members.length, ...(width == null ? {} : { width }) },
1161
+ },
1162
+ };
1163
+ });
1164
+ continue;
1165
+ }
1166
+ /*
1167
+ A streamgraph's offset floor has no side for a negative segment to hang below.
1168
+
1169
+ Dropped for the whole group. The footer states it.
1170
+ */
1171
+ const offset = position === "stack" && args.offset && args.offset !== "zero" ? args.offset : undefined;
1172
+ if (offset && members.some((at) => (barsOf(out[at])?.bars ?? []).some((one) => one.value < 0))) {
1173
+ negativeStack = true;
1174
+ continue;
1175
+ }
1176
+ /*
1177
+ ggplot's `vjust` -- where a geom falls inside its stack segment.
1178
+
1179
+ One is the far end and the default. Zero is the floor. It moves the reading.
1180
+ */
1181
+ const { vjust } = args;
1182
+ /*
1183
+ ggplot's `position_stack`. A positive reading stacks up from zero and a negative one down from
1184
+ it, each sign on a running total of its own. A fill divides each sign by its own sum.
1185
+ */
1186
+ const sideOf = (value) => (value < 0 ? "below" : "above");
1187
+ const totals = { above: new Map(), below: new Map() };
1188
+ for (const at of members) {
1189
+ for (const one of barsOf(out[at])?.bars ?? []) {
1190
+ const sums = totals[sideOf(one.value)];
1191
+ sums.set(one.category, (sums.get(one.category) ?? 0) + one.value);
1192
+ }
1193
+ }
1194
+ const running = {
1195
+ above: offset
1196
+ ? baselineOf(members.map((at) => barsOf(out[at])?.bars ?? []), offset, along)
1197
+ : new Map(),
1198
+ below: new Map(),
1199
+ };
1200
+ for (const at of members) {
1201
+ const data = barsOf(out[at]);
1202
+ if (!data)
1203
+ continue;
1204
+ const bars = data.bars.map((one) => {
1205
+ const side = sideOf(one.value);
1206
+ const floor = running[side].get(one.category) ?? 0;
1207
+ running[side].set(one.category, floor + one.value);
1208
+ const stacked = position !== "fill"
1209
+ ? { ...one, floor }
1210
+ : /* A category summing to zero has no shares to take. It keeps its zeros. */
1211
+ ((total) => total > 0 ? { ...one, floor: floor / total, value: one.value / total } : { ...one, floor: 0, value: 0 })(Math.abs(totals[side].get(one.category) ?? 0));
1212
+ return vjust == null ? stacked : justified(stacked, vjust);
1213
+ });
1214
+ /* A fill leaves shares behind it, which the axis title and the readout both have to know. */
1215
+ out[at] = { ...out[at], data: { ...data, bars, ...(position === "fill" ? { shares: true } : {}) } };
1216
+ }
1217
+ }
1218
+ /*
1219
+ A text layer under a dodge takes the slot of the bar it names, matched by split value.
1220
+
1221
+ The bar's thickness comes along.
1222
+ */
1223
+ const dodges = new Set(["dodge", "dodge2", "jitterdodge"]);
1224
+ const thickness = new Map(series.map((one) => [one.id, one.style?.thickness]));
1225
+ for (let at = 0; at < out.length; at += 1) {
1226
+ const trace = out[at];
1227
+ if (trace.data.geom !== "text" || trace.data.at !== "records")
1228
+ continue;
1229
+ const kind = positionKind(asked.get(trace.layerId));
1230
+ if (!dodges.has(kind))
1231
+ continue;
1232
+ const named = out.find((one) => {
1233
+ const bars = barsOf(one);
1234
+ return bars?.slot != null && one.splitValue === trace.splitValue && positionKind(asked.get(one.layerId)) === kind;
1235
+ });
1236
+ const bars = named ? barsOf(named) : null;
1237
+ if (!bars?.slot)
1238
+ continue;
1239
+ const cap = thickness.get(named.layerId);
1240
+ /* ggplot's `preserve = "total"` divides each band by what it holds. The label divides the same way. */
1241
+ const counted = bars.bars.filter((bar) => bar.slotOf != null);
1242
+ const ofBand = counted.length > 0 ? Object.fromEntries(counted.map((bar) => [bar.category, bar.slotOf])) : null;
1243
+ out[at] = {
1244
+ ...trace,
1245
+ data: { ...trace.data, slot: { ...bars.slot, ...(cap == null ? {} : { cap }), ...(ofBand ? { ofBand } : {}) } },
1246
+ };
1247
+ }
1248
+ /*
1249
+ A text layer under a stack runs its own total per category, ggplot's `position_stack` on `geom_text`.
1250
+
1251
+ A fill divides by that total. A negative reading leaves the labels unstacked.
1252
+ */
1253
+ for (const kind of ["stack", "fill"]) {
1254
+ const texts = out.flatMap((trace, at) => trace.data.geom === "text" && positionKind(asked.get(trace.layerId)) === kind ? [at] : []);
1255
+ if (texts.length === 0)
1256
+ continue;
1257
+ const args = positionArgs(asked.get(out[texts[0]].layerId));
1258
+ const pointsAt = (at) => {
1259
+ const data = out[at].data;
1260
+ return data.geom === "text" && data.at === "records" ? data.points : [];
1261
+ };
1262
+ if (texts.some((at) => pointsAt(at).some((point) => point.y < 0)))
1263
+ continue;
1264
+ const keyOf = (point) => point.category ?? String(point.x);
1265
+ const totals = new Map();
1266
+ for (const at of texts) {
1267
+ for (const point of pointsAt(at))
1268
+ totals.set(keyOf(point), (totals.get(keyOf(point)) ?? 0) + point.y);
1269
+ }
1270
+ const running = new Map();
1271
+ for (const at of args.reverse ? [...texts].reverse() : texts) {
1272
+ const data = out[at].data;
1273
+ if (data.geom !== "text" || data.at !== "records")
1274
+ continue;
1275
+ const points = data.points.map((point) => {
1276
+ const floor = running.get(keyOf(point)) ?? 0;
1277
+ running.set(keyOf(point), floor + point.y);
1278
+ const top = floor + point.y * Math.min(1, Math.max(0, args.vjust ?? 1));
1279
+ const total = totals.get(keyOf(point)) ?? 0;
1280
+ return { ...point, y: kind === "stack" ? top : total > 0 ? top / total : 0 };
1281
+ });
1282
+ out[at] = { ...out[at], data: { ...data, points } };
1283
+ }
1284
+ }
1285
+ return { traces: out, negativeStack };
1286
+ }
1287
+ /** Whether a series asks for a running total its kind draws. `GEOMS` lists `cumulative` under those. */
1288
+ const runs = (series) => series.cumulative === true && kindFacts(series.kind).layer.includes("cumulative");
1289
+ /**
1290
+ * Turns each cumulative series into a running total.
1291
+ *
1292
+ * Traces on a band share its order. A value scale keeps each trace's own bins. An accumulated
1293
+ * series reports no interval.
1294
+ */
1295
+ function accumulated(traces, banded, order, series) {
1296
+ const byId = new Map(series.map((one) => [one.id, one]));
1297
+ let band;
1298
+ const along = () => (band ??= orderBand(order, [...new Set(traces.flatMap(categoriesOf))], () => null).values);
1299
+ return traces.map((trace) => {
1300
+ const data = trace.data;
1301
+ const own = byId.get(trace.layerId);
1302
+ if (!own || data.at !== "groups" || !("bars" in data) || !runs(own))
1303
+ return trace;
1304
+ const held = new Map(data.bars.map((bar) => [bar.category, bar]));
1305
+ const ordered = banded ? along().flatMap((category) => held.get(category) ?? []) : data.bars;
1306
+ return { ...trace, data: { ...data, bars: accumulate(ordered), error: undefined, cumulative: true } };
1307
+ });
1308
+ }
1309
+ /** Categories a trace occupies, in the order it produced them. */
1310
+ export function categoriesOf(trace) {
1311
+ /*
1312
+ A record geom names its band the way a reduction names its groups.
1313
+
1314
+ An interval and a segment write the category on the reading.
1315
+ */
1316
+ if (trace.data.at === "records") {
1317
+ if (trace.data.geom === "ribbon" || trace.data.geom === "range") {
1318
+ return trace.data.readings.map((reading) => reading.x).filter((at) => typeof at === "string");
1319
+ }
1320
+ if (trace.data.geom === "segment") {
1321
+ return trace.data.segments.map((segment) => segment.x).filter((at) => typeof at === "string");
1322
+ }
1323
+ if (trace.data.geom === "point" || trace.data.geom === "text") {
1324
+ return trace.data.points.map((point) => point.category).filter((at) => at != null);
1325
+ }
1326
+ return [];
1327
+ }
1328
+ if (trace.data.at !== "groups")
1329
+ return [];
1330
+ if (trace.data.geom === "boxplot")
1331
+ return trace.data.boxes.map((box) => box.category);
1332
+ if (trace.data.geom === "violin")
1333
+ return trace.data.violins.map((violin) => violin.category);
1334
+ // A grid has a cell per pair. A column appears once per row.
1335
+ if (trace.data.geom === "heatmap")
1336
+ return [...new Set(trace.data.cells.map((cell) => cell.x))];
1337
+ // A flow names nodes. It takes no slot on a band.
1338
+ if (trace.data.geom === "sankey" || trace.data.geom === "chord" || trace.data.geom === "ideogram")
1339
+ return [];
1340
+ // A hierarchy positions its cells by nesting. No slot on a band.
1341
+ if (trace.data.geom === "treemap" || trace.data.geom === "icicle" || trace.data.geom === "sunburst")
1342
+ return [];
1343
+ // A density curve stands on a value scale. No slot on a band.
1344
+ if (trace.data.geom === "density")
1345
+ return [];
1346
+ // A cube positions itself and names nothing on the frame's band.
1347
+ if ("mesh" in trace.data || "field" in trace.data)
1348
+ return [];
1349
+ /* A dial takes one number and no category. No slot on the band. */
1350
+ if (trace.data.geom === "gauge")
1351
+ return [];
1352
+ return trace.data.bars.map((bar) => bar.category);
1353
+ }
1354
+ /**
1355
+ * Where a stack's floor runs under each category, for the two offsets that move it off zero.
1356
+ *
1357
+ * `silhouette` centers the total on zero. `wiggle` sets each step against the last to keep the
1358
+ * layers' slopes small, the streamgraph's baseline. Categories run in axis order.
1359
+ */
1360
+ function baselineOf(layers, offset, along) {
1361
+ const positions = new Map();
1362
+ for (const layer of layers)
1363
+ for (const one of layer)
1364
+ if (!positions.has(one.category))
1365
+ positions.set(one.category, one.at ?? positions.size);
1366
+ const categories = along
1367
+ ? along.filter((category) => positions.has(category))
1368
+ : [...positions].sort((a, b) => a[1] - b[1]).map(([category]) => category);
1369
+ const valueIn = layers.map((layer) => new Map(layer.map((one) => [one.category, one.value])));
1370
+ const at = (i, j) => valueIn[i].get(categories[j]) ?? 0;
1371
+ const floor = new Map();
1372
+ let base = 0;
1373
+ categories.forEach((category, j) => {
1374
+ if (offset === "silhouette") {
1375
+ base = -layers.reduce((sum, _, i) => sum + at(i, j), 0) / 2;
1376
+ }
1377
+ else if (j > 0) {
1378
+ let total = 0;
1379
+ let moment = 0;
1380
+ let below = 0;
1381
+ for (let i = 0; i < layers.length; i += 1) {
1382
+ const rise = at(i, j) - at(i, j - 1);
1383
+ moment += at(i, j) * (below + rise / 2);
1384
+ total += at(i, j);
1385
+ below += rise;
1386
+ }
1387
+ if (total > 0)
1388
+ base -= moment / total;
1389
+ }
1390
+ floor.set(category, base);
1391
+ });
1392
+ return floor;
1393
+ }
1394
+ /**
1395
+ * Stacks each waterfall step on the steps before it, and orders a ring's slices.
1396
+ *
1397
+ * A step's floor is the height the ones before it reached. Both read `scales.x.order`.
1398
+ */
1399
+ function stepped(traces, order) {
1400
+ return traces.map((trace) => {
1401
+ const data = trace.data;
1402
+ if (data.at !== "groups" || !("bars" in data))
1403
+ return trace;
1404
+ const ring = data.geom === "pie";
1405
+ if (data.geom !== "waterfall" && !(ring && order))
1406
+ return trace;
1407
+ const held = new Map(data.bars.map((step) => [step.category, step]));
1408
+ const { values } = orderBand(order, [...held.keys()], () => null);
1409
+ if (ring)
1410
+ return { ...trace, data: { ...data, bars: values.map((category) => held.get(category)) } };
1411
+ let running = 0;
1412
+ const bars = values.map((category) => {
1413
+ const step = held.get(category);
1414
+ const floor = running;
1415
+ running += step.value;
1416
+ return { ...step, floor };
1417
+ });
1418
+ return { ...trace, data: { ...data, bars } };
1419
+ });
1420
+ }
1421
+ /**
1422
+ * Moves a stacked geom inside its own segment, for a caller that stated a `vjust`.
1423
+ *
1424
+ * The floor stays where the stack put it and the reading moves toward it.
1425
+ */
1426
+ const justified = (bar, vjust) => ({
1427
+ ...bar,
1428
+ value: bar.value * Math.min(1, Math.max(0, vjust)),
1429
+ });
1430
+ /** What a jitter position asks for, where the series stated one. Each axis apart, in data units. */
1431
+ const jitterOf = (series) => {
1432
+ const kind = positionKind(series.position);
1433
+ if (kind !== "jitter" && kind !== "jitterdodge")
1434
+ return undefined;
1435
+ const { width, height, seed, dodgeWidth } = positionArgs(series.position);
1436
+ return {
1437
+ ...(width == null ? {} : { x: width }),
1438
+ ...(height == null ? {} : { y: height }),
1439
+ ...(seed == null ? {} : { seed }),
1440
+ ...(kind === "jitterdodge" ? { dodge: dodgeWidth ?? DODGE_WIDTH } : {}),
1441
+ };
1442
+ };
1443
+ /** The fixed offset a nudge asks for, in the axes' own units. */
1444
+ const shoveOf = (series) => {
1445
+ if (positionKind(series.position) !== "nudge")
1446
+ return undefined;
1447
+ const { x, y } = positionArgs(series.position);
1448
+ return { ...(x == null ? {} : { x }), ...(y == null ? {} : { y }) };
1449
+ };
1450
+ /** Rows a stride passed over. The reader is owed this where lines were sampled. */
1451
+ const skipped = (rowCount, step) => rowCount - Math.ceil(rowCount / step);
1452
+ /**
1453
+ * A reduction over two categories at once.
1454
+ *
1455
+ * The bar path groups by one field. A heatmap groups by a pair and `groupRows` has one key.
1456
+ */
1457
+ function cellsOf(data, xId, yId, measure, aggregate) {
1458
+ const running = new Map();
1459
+ const collect = NEEDS_VALUES.includes(aggregate);
1460
+ for (let row = 0; row < data.rowCount; row += 1) {
1461
+ const x = data.text(row, xId);
1462
+ const y = data.text(row, yId);
1463
+ if (x == null || y == null)
1464
+ continue;
1465
+ const value = measure ? data.number(row, measure) : 1;
1466
+ if (value == null)
1467
+ continue;
1468
+ const key = `${x}\u0000${y}`;
1469
+ let cell = running.get(key);
1470
+ if (!cell) {
1471
+ cell = {
1472
+ x,
1473
+ y,
1474
+ bucket: { n: 0, sum: 0, sumSq: 0, min: Infinity, max: -Infinity },
1475
+ values: collect ? [] : null,
1476
+ };
1477
+ running.set(key, cell);
1478
+ }
1479
+ cell.bucket.n += 1;
1480
+ cell.bucket.sum += value;
1481
+ cell.bucket.sumSq += value * value;
1482
+ cell.bucket.min = Math.min(cell.bucket.min, value);
1483
+ cell.bucket.max = Math.max(cell.bucket.max, value);
1484
+ cell.values?.push(value);
1485
+ }
1486
+ return [...running.values()].map((cell) => ({
1487
+ x: cell.x,
1488
+ y: cell.y,
1489
+ value: reduceBucket(cell.bucket, aggregate, cell.values ?? undefined),
1490
+ n: cell.bucket.n,
1491
+ }));
1492
+ }
1493
+ /** Links a flow draws before the ribbons stop being separable. */
1494
+ export const LINK_CAP = 80;
1495
+ /**
1496
+ * Nodes a flow draws in one column.
1497
+ *
1498
+ * Sixty links out of two thousand plates draw a comb of hairlines. Bounding the nodes keeps the
1499
+ * survivors readable.
1500
+ */
1501
+ export const NODE_CAP = 20;
1502
+ /**
1503
+ * Lines a parallel plot draws.
1504
+ *
1505
+ * A line crossing four axes covers far more panel than a dot. The footer says how many rows the
1506
+ * sample passed over.
1507
+ */
1508
+ export const LINE_CAP = 2_000;
1509
+ /**
1510
+ * Readings a group can show behind its geom.
1511
+ *
1512
+ * The dots spread across the bar's own width. Past the cap a group shows none and the footer
1513
+ * counts them.
1514
+ */
1515
+ export const REPLICATE_CAP = 40;
1516
+ /**
1517
+ * Measures a parallel plot spans.
1518
+ *
1519
+ * Each axis takes a column of the panel. Past the cap the measures are dropped and the footer
1520
+ * states it.
1521
+ */
1522
+ export const AXIS_CAP = 8;
1523
+ /**
1524
+ * A flow that runs between two named fields, holding one row per link.
1525
+ *
1526
+ * Columns come from the graph. A node draws one column right of the furthest node reaching it.
1527
+ */
1528
+ function flowOf(data, sourceId, targetId, valueId, align = "left") {
1529
+ /* Held per pair. A stage name may hold any separator. */
1530
+ const totals = new Map();
1531
+ for (let row = 0; row < data.rowCount; row += 1) {
1532
+ const from = data.text(row, sourceId);
1533
+ const to = data.text(row, targetId);
1534
+ // A row pointing at itself is a stage that did not move, and it draws as nothing.
1535
+ if (from == null || to == null || from === to)
1536
+ continue;
1537
+ const value = valueId ? data.number(row, valueId) : 1;
1538
+ if (value == null || !(value > 0))
1539
+ continue;
1540
+ const outgoing = totals.get(from) ?? new Map();
1541
+ outgoing.set(to, (outgoing.get(to) ?? 0) + value);
1542
+ totals.set(from, outgoing);
1543
+ }
1544
+ const ranked = [];
1545
+ for (const [source, outgoing] of totals) {
1546
+ for (const [target, value] of outgoing)
1547
+ ranked.push({ source, target, value });
1548
+ }
1549
+ if (ranked.length === 0)
1550
+ return null;
1551
+ ranked.sort((a, b) => b.value - a.value);
1552
+ /*
1553
+ The biggest nodes of each column are kept and the links between them follow.
1554
+
1555
+ Ranking nodes by what passes through them keeps the flow the population takes.
1556
+ */
1557
+ const through = new Map();
1558
+ const carry = (name, value) => through.set(name, (through.get(name) ?? 0) + value);
1559
+ for (const link of ranked) {
1560
+ carry(link.source, link.value);
1561
+ carry(link.target, link.value);
1562
+ }
1563
+ const placed = align === "justify" ? justifiedColumns(columnsOf(ranked), ranked) : columnsOf(ranked);
1564
+ const kept = new Set();
1565
+ for (const at of new Set(placed.values())) {
1566
+ const members = [...through].filter(([name]) => placed.get(name) === at).sort((a, b) => b[1] - a[1]);
1567
+ for (const [name] of members.slice(0, NODE_CAP))
1568
+ kept.add(name);
1569
+ }
1570
+ const between = ranked.filter((link) => kept.has(link.source) && kept.has(link.target));
1571
+ const links = between.slice(0, LINK_CAP);
1572
+ const names = new Set();
1573
+ for (const link of links) {
1574
+ names.add(link.source);
1575
+ names.add(link.target);
1576
+ }
1577
+ const column = columnsOf(links);
1578
+ /* The exits read the columns the flow reached, before a justify moves its end nodes. */
1579
+ const exits = exitsOf(links, column);
1580
+ if (align === "justify")
1581
+ justifiedColumns(column, links);
1582
+ const nodes = [...names].map((name) => ({
1583
+ id: name,
1584
+ label: name,
1585
+ column: column.get(name) ?? 0,
1586
+ kind: exits.has(name) ? "exit" : "survivor",
1587
+ }));
1588
+ const kinded = links.map((link) => ({
1589
+ ...link,
1590
+ kind: exits.has(link.target) ? "exit" : "survivor",
1591
+ }));
1592
+ return { nodes, links: kinded, dropped: ranked.length - links.length };
1593
+ }
1594
+ /** Moves each node no link leaves into the last column. The cap reads the columns this returns. */
1595
+ function justifiedColumns(column, links) {
1596
+ const last = Math.max(0, boundsOf([...column.values()])[1]);
1597
+ const onward = new Set(links.map((link) => link.source));
1598
+ for (const name of column.keys())
1599
+ if (!onward.has(name))
1600
+ column.set(name, last);
1601
+ return column;
1602
+ }
1603
+ /** Places each node one column right of the furthest node reaching it. */
1604
+ function columnsOf(links) {
1605
+ const column = new Map();
1606
+ for (const link of links) {
1607
+ column.set(link.source, 0);
1608
+ column.set(link.target, 0);
1609
+ }
1610
+ for (let pass = 0; pass < column.size; pass += 1) {
1611
+ let moved = false;
1612
+ for (const link of links) {
1613
+ const reach = (column.get(link.source) ?? 0) + 1;
1614
+ if (reach > (column.get(link.target) ?? 0)) {
1615
+ column.set(link.target, reach);
1616
+ moved = true;
1617
+ }
1618
+ }
1619
+ if (!moved)
1620
+ break;
1621
+ }
1622
+ return column;
1623
+ }
1624
+ /**
1625
+ * The nodes a flow exits at.
1626
+ *
1627
+ * A terminal node before the last stage exits. A last-stage gate keeps its smallest outcome and exits
1628
+ * the rest.
1629
+ */
1630
+ function exitsOf(links, column) {
1631
+ const onward = new Set(links.map((link) => link.source));
1632
+ const last = Math.max(0, boundsOf([...column.values()])[1]);
1633
+ const exits = new Set();
1634
+ const sourcesOf = new Map();
1635
+ for (const link of links) {
1636
+ if (onward.has(link.target))
1637
+ continue;
1638
+ if ((column.get(link.target) ?? 0) < last)
1639
+ exits.add(link.target);
1640
+ sourcesOf.set(link.target, (sourcesOf.get(link.target) ?? new Set()).add(link.source));
1641
+ }
1642
+ // ponytail: a gate is one source over two or more last-stage nodes, and its smallest outcome reads as the pass.
1643
+ const gates = new Map();
1644
+ for (const link of links) {
1645
+ if (onward.has(link.target) || (column.get(link.target) ?? 0) < last || sourcesOf.get(link.target)?.size !== 1)
1646
+ continue;
1647
+ gates.set(link.source, [...(gates.get(link.source) ?? []), link]);
1648
+ }
1649
+ for (const outcomes of gates.values()) {
1650
+ if (outcomes.length < 2)
1651
+ continue;
1652
+ const pass = outcomes.reduce((least, link) => (link.value < least.value ? link : least));
1653
+ for (const link of outcomes)
1654
+ if (link !== pass)
1655
+ exits.add(link.target);
1656
+ }
1657
+ return exits;
1658
+ }
1659
+ /**
1660
+ * A flow, built outside the shared-X contract the other geoms share.
1661
+ *
1662
+ * Every other geom reads the plot's one horizontal binding. A sankey binds both its ends.
1663
+ */
1664
+ function flowTrace(series, data, fieldAt, color) {
1665
+ const sourceId = typeof series.aes.source === "string" ? series.aes.source : undefined;
1666
+ const targetId = typeof series.aes.target === "string" ? series.aes.target : undefined;
1667
+ if (!sourceId || !targetId)
1668
+ return null;
1669
+ const valueId = typeof series.aes.value === "string" ? series.aes.value : undefined;
1670
+ const flow = flowOf(data, sourceId, targetId, valueId, series.statParams?.align);
1671
+ if (!flow)
1672
+ return null;
1673
+ const from = fieldAt.get(sourceId)?.label ?? sourceId;
1674
+ const to = fieldAt.get(targetId)?.label ?? targetId;
1675
+ return {
1676
+ trace: {
1677
+ id: series.id,
1678
+ layerId: series.id,
1679
+ name: series.name ?? `${from} to ${to}`,
1680
+ color,
1681
+ axis: series.axis ?? "y",
1682
+ ramp: () => color,
1683
+ data: {
1684
+ at: "groups",
1685
+ geom: "sankey",
1686
+ ...flow,
1687
+ ...(series.statParams?.normalize ? { normalize: series.statParams.normalize } : {}),
1688
+ },
1689
+ },
1690
+ dropped: flow.dropped,
1691
+ };
1692
+ }
1693
+ /** Sectors an ideogram draws. Past this the arcs are slivers and the names collide. */
1694
+ export const SECTOR_CAP = 64;
1695
+ /**
1696
+ * A genome read round a circle.
1697
+ *
1698
+ * A sector covers what its rows cover. The tiles keep their own spans inside it.
1699
+ */
1700
+ function ideogramTrace(series, data, fieldAt, color) {
1701
+ const sectorId = typeof series.aes.sector === "string" ? series.aes.sector : undefined;
1702
+ const startId = typeof series.aes.start === "string" ? series.aes.start : undefined;
1703
+ const endId = typeof series.aes.end === "string" ? series.aes.end : undefined;
1704
+ if (!sectorId || !startId || !endId)
1705
+ return null;
1706
+ const colorId = paintColumn(series);
1707
+ const far = series.links;
1708
+ const spans = new Map();
1709
+ const tiles = [];
1710
+ const levels = [];
1711
+ const links = [];
1712
+ /* A sector covers every position either end of a row put inside it. */
1713
+ const cover = (name, lo, hi) => {
1714
+ const held = spans.get(name) ?? { lo, hi };
1715
+ spans.set(name, { lo: Math.min(held.lo, lo), hi: Math.max(held.hi, hi) });
1716
+ };
1717
+ for (let row = 0; row < data.rowCount; row += 1) {
1718
+ const name = data.text(row, sectorId);
1719
+ const start = data.number(row, startId);
1720
+ const end = data.number(row, endId);
1721
+ if (name == null || start == null || end == null)
1722
+ continue;
1723
+ cover(name, start, end);
1724
+ /* A row naming a far end is a link. It draws no tile and takes no stain. */
1725
+ const other = far ? data.text(row, far.sector) : null;
1726
+ const otherStart = far ? data.number(row, far.start) : null;
1727
+ if (far && other != null && otherStart != null) {
1728
+ const otherEnd = far.end == null ? otherStart : (data.number(row, far.end) ?? otherStart);
1729
+ cover(other, otherStart, otherEnd);
1730
+ const measure = far.value == null ? null : data.number(row, far.value);
1731
+ links.push({ sector: name, start, end, other, otherStart, otherEnd, ...(measure == null ? {} : { value: measure }) });
1732
+ continue;
1733
+ }
1734
+ const level = colorId ? (data.text(row, colorId) ?? undefined) : undefined;
1735
+ if (level != null && !levels.includes(level))
1736
+ levels.push(level);
1737
+ tiles.push({ sector: name, start, end, ...(level == null ? {} : { level }) });
1738
+ }
1739
+ if (spans.size === 0)
1740
+ return null;
1741
+ /* The order the rows arrive in, which is the order a genome file already holds. */
1742
+ const order = [...spans.keys()];
1743
+ /* A sector with a tile of its own takes a place under the cap ahead of a name only a link reaches. */
1744
+ const tiled = new Set(tiles.map((tile) => tile.sector));
1745
+ const capped = new Set([...order.filter((id) => tiled.has(id)), ...order.filter((id) => !tiled.has(id))].slice(0, SECTOR_CAP));
1746
+ const kept = order.filter((id) => capped.has(id));
1747
+ const within = new Set(kept);
1748
+ const sectors = kept.map((id) => {
1749
+ const span = spans.get(id);
1750
+ return { id, xlim: [span.lo, span.hi] };
1751
+ });
1752
+ /* A link reaching a sector the cap turned down has nowhere to land, and the footer counts it. */
1753
+ const seated = links.filter((link) => within.has(link.sector) && within.has(link.other));
1754
+ /* The measure the drawn links cover. A ramp over anything wider would waste its range. */
1755
+ const measures = seated.map((link) => link.value).filter((one) => one != null);
1756
+ const linkDomain = measures.length > 0 ? boundsOf(measures) : null;
1757
+ const rings = (series.rings ?? []).map((ring) => ringReading(ring.content, kept, [sectorId], data, fieldAt, { sector: sectorId, start: startId, end: endId }));
1758
+ return {
1759
+ trace: {
1760
+ id: series.id,
1761
+ layerId: series.id,
1762
+ name: series.name ?? fieldAt.get(sectorId)?.label ?? sectorId,
1763
+ color,
1764
+ axis: series.axis ?? "y",
1765
+ ramp: () => color,
1766
+ data: {
1767
+ at: "groups",
1768
+ geom: "ideogram",
1769
+ sectors,
1770
+ tiles: tiles.filter((tile) => within.has(tile.sector)),
1771
+ levels,
1772
+ links: seated,
1773
+ ...(linkDomain == null ? {} : { linkDomain }),
1774
+ rings,
1775
+ },
1776
+ },
1777
+ dropped: spans.size - kept.length,
1778
+ offSector: links.length - seated.length,
1779
+ /* Rings, links and unstained tiles read the sector's own hue. A stain paints its own tile. */
1780
+ hued: seated.length > 0 || rings.length > 0 || tiles.some((tile) => tile.level == null) ? kept.length : 0,
1781
+ };
1782
+ }
1783
+ /**
1784
+ * Sectors a figure drew in one ink, once the map has run out.
1785
+ *
1786
+ * Zero where the colors still tell the sectors apart. An author's own fill answers zero.
1787
+ */
1788
+ const flattened = (count, size, fill) => size != null && fill == null && count > size ? count : 0;
1789
+ /**
1790
+ * A flow read round a center.
1791
+ *
1792
+ * The pairs come off the same builder the sankey reads. A chord holds no columns.
1793
+ */
1794
+ function chordTrace(series, data, fieldAt, color) {
1795
+ const sourceId = typeof series.aes.source === "string" ? series.aes.source : undefined;
1796
+ const targetId = typeof series.aes.target === "string" ? series.aes.target : undefined;
1797
+ if (!sourceId || !targetId)
1798
+ return null;
1799
+ const valueId = typeof series.aes.value === "string" ? series.aes.value : undefined;
1800
+ const flow = flowOf(data, sourceId, targetId, valueId);
1801
+ if (!flow)
1802
+ return null;
1803
+ const from = fieldAt.get(sourceId)?.label ?? sourceId;
1804
+ const to = fieldAt.get(targetId)?.label ?? targetId;
1805
+ const links = flow.links.map((link) => ({ source: link.source, target: link.target, value: link.value }));
1806
+ /* The sectors a ring reads against, settled by the same layout the geom draws. */
1807
+ const sectors = chordLayout(links).sectors.map((sector) => sector.id);
1808
+ const rings = (series.rings ?? []).map((ring) => ringReading(ring.content, sectors, [sourceId, targetId], data, fieldAt));
1809
+ return {
1810
+ trace: {
1811
+ id: series.id,
1812
+ layerId: series.id,
1813
+ name: series.name ?? `${from} and ${to}`,
1814
+ color,
1815
+ axis: series.axis ?? "y",
1816
+ ramp: () => color,
1817
+ data: { at: "groups", geom: "chord", links, rings },
1818
+ },
1819
+ dropped: flow.dropped,
1820
+ hued: sectors.length,
1821
+ };
1822
+ }
1823
+ /**
1824
+ * Lays out a hierarchy.
1825
+ *
1826
+ * A label, a value and a parent bind. `sum` is the default aggregate. The parent comes off the
1827
+ * first row naming one.
1828
+ */
1829
+ function hierarchyTrace(series, geom, data, fieldAt, color, identity) {
1830
+ const labelId = typeof series.aes.label === "string" ? series.aes.label : undefined;
1831
+ if (!labelId)
1832
+ return null;
1833
+ const valueId = typeof series.aes.value === "string" ? series.aes.value : undefined;
1834
+ const parentId = typeof series.aes.parent === "string" ? series.aes.parent : undefined;
1835
+ const valueField = valueId ? fieldAt.get(valueId) : undefined;
1836
+ const aggregate = (series.aggregate ?? (valueField?.numeric ? "sum" : "count"));
1837
+ const parents = new Map();
1838
+ if (parentId) {
1839
+ for (let row = 0; row < data.rowCount; row += 1) {
1840
+ const label = data.text(row, labelId);
1841
+ const parent = data.text(row, parentId);
1842
+ if (label == null || parent == null || parent === "" || parents.has(label))
1843
+ continue;
1844
+ parents.set(label, parent);
1845
+ }
1846
+ }
1847
+ const measure = aggregate === "count" ? null : (valueField?.id ?? null);
1848
+ if (!measure && aggregate !== "count")
1849
+ return null;
1850
+ const rows = groupRows(data, labelId, measure, aggregate).map((group) => {
1851
+ const parent = parents.get(group.key);
1852
+ return { label: group.key, value: group.value, ...(parent == null ? {} : { parent }) };
1853
+ });
1854
+ /* A sunburst reads the icicle's layout, differing in where a cell lands and not in the tiling. */
1855
+ const layout = geom === "treemap" ? treemapLayout(rows) : icicleLayout(rows);
1856
+ if (layout.cells.length === 0)
1857
+ return null;
1858
+ /* Groups in row order. All three arrangements paint one group one hue. A stated fill paints one. */
1859
+ const groups = groupsOf(layout.cells);
1860
+ const levels = series.style?.fill
1861
+ ? []
1862
+ : [...new Set(rows.map((row) => groups.get(row.label)).filter((group) => group != null))];
1863
+ const groupField = (parentId ? fieldAt.get(parentId) : undefined) ?? fieldAt.get(labelId);
1864
+ return {
1865
+ trace: {
1866
+ id: series.id,
1867
+ layerId: series.id,
1868
+ name: series.name ?? (valueField ? `${aggregate} of ${valueField.label}` : "Count"),
1869
+ color,
1870
+ axis: series.axis ?? "y",
1871
+ ramp: (code) => identity(Math.round(code)),
1872
+ ...(valueField ? { field: valueField } : {}),
1873
+ ...(levels.length > 0 && groupField
1874
+ ? { colorField: groupField, colorLevels: levels.map((value, code) => ({ value, code })) }
1875
+ : {}),
1876
+ data: { at: "groups", geom, cells: layout.cells, aggregate, dropped: layout.dropped },
1877
+ },
1878
+ dropped: layout.dropped,
1879
+ hued: levels.length,
1880
+ };
1881
+ }
1882
+ /** The categories a point layer paints, read off each drawn point's code. A path geom gives undefined. */
1883
+ function pointLevels(trace, levels = trace.colorLevels) {
1884
+ const data = trace.data;
1885
+ if (data.at !== "records" || data.geom !== "point" || !levels)
1886
+ return undefined;
1887
+ const byCode = new Map(levels.map(({ value, code }) => [code, value]));
1888
+ return data.points.flatMap((point) => (point.weight == null ? [] : (byCode.get(Math.round(point.weight)) ?? [])));
1889
+ }
1890
+ /** A category's color under a host's keyed map. A category the map misses draws in one ink. */
1891
+ function keyedInk(keyed, level) {
1892
+ return (level != null && Object.hasOwn(keyed, level) && keyed[level]) || UNMAPPED_INK;
1893
+ }
1894
+ /**
1895
+ * A color category's ramp. A layer naming a magnitude map steps along it in code order, as its split paths do.
1896
+ *
1897
+ * A keyed map colors a category by name.
1898
+ */
1899
+ function codeRamp(series, codes, palettes, options) {
1900
+ const keyed = options?.values;
1901
+ if (keyed) {
1902
+ const levels = new Map([...codes].map(([value, code]) => [code, value]));
1903
+ return (code) => keyedInk(keyed, levels.get(Math.round(code)));
1904
+ }
1905
+ if (series.palette && palettes.sequentialFor && !palettes.categoricalFor?.(series.palette)) {
1906
+ const steps = Math.max(1, codes.size - 1);
1907
+ return (code) => palettes.sequential(Math.round(code) / steps);
1908
+ }
1909
+ return (code) => palettes.categorical(Math.round(code));
1910
+ }
1911
+ /**
1912
+ * A line per record across several measures, built outside the shared-X contract.
1913
+ *
1914
+ * The measures come from one channel. A row missing any one of them is dropped.
1915
+ */
1916
+ function parallelTrace(series, geom, data, fieldAt, color, palettes, codesFor, rangeFor, colorOptions) {
1917
+ const bound = series.aes.dimensions;
1918
+ const ids = (Array.isArray(bound) ? bound : bound ? [bound] : []).filter((id) => fieldAt.has(id));
1919
+ /* Two rules and a closing edge draw a sliver. A radar wants a third. */
1920
+ if (ids.length < (geom === "radar" ? 3 : 2))
1921
+ return null;
1922
+ const kept = ids.slice(0, AXIS_CAP);
1923
+ const axes = [];
1924
+ for (const id of kept) {
1925
+ const field = fieldAt.get(id);
1926
+ const range = rangeFor(id);
1927
+ if (!range)
1928
+ return null;
1929
+ // Each axis has its own units and the title states them. The end numbers are bare.
1930
+ axes.push({
1931
+ id,
1932
+ label: field.unit ? `${field.label} (${field.unit})` : field.label,
1933
+ lo: range[0],
1934
+ hi: range[1],
1935
+ });
1936
+ }
1937
+ const colorId = paintColumn(series);
1938
+ const colorField = colorId ? fieldAt.get(colorId) : undefined;
1939
+ const codes = colorField && !colorField.numeric ? codesFor(colorField.id) : null;
1940
+ /* Complete rows are collected before the stride runs. The sample is of what draws. */
1941
+ const whole = [];
1942
+ let incomplete = 0;
1943
+ for (let row = 0; row < data.rowCount; row += 1) {
1944
+ if (kept.every((id) => data.number(row, id) != null))
1945
+ whole.push(row);
1946
+ else
1947
+ incomplete += 1;
1948
+ }
1949
+ if (whole.length === 0)
1950
+ return null;
1951
+ const step = Math.max(1, Math.ceil(whole.length / LINE_CAP));
1952
+ const lines = [];
1953
+ const outer = viewRows.get(data);
1954
+ for (let at = 0; at < whole.length; at += step) {
1955
+ const row = whole[at];
1956
+ let weight;
1957
+ if (colorField?.numeric) {
1958
+ const value = data.number(row, colorField.id);
1959
+ if (value != null)
1960
+ weight = value;
1961
+ }
1962
+ else if (colorField && codes) {
1963
+ const value = data.text(row, colorField.id);
1964
+ if (value != null)
1965
+ weight = codes.get(value);
1966
+ }
1967
+ lines.push({
1968
+ values: kept.map((id) => data.number(row, id)),
1969
+ weight,
1970
+ key: data.keyField ? (data.text(row, data.keyField) ?? undefined) : undefined,
1971
+ row: data.rowIndex(row),
1972
+ plotRow: outer ? outer[row] : row,
1973
+ });
1974
+ }
1975
+ let ramp = () => color;
1976
+ const range = colorField?.numeric ? rangeFor(colorField.id) : null;
1977
+ if (range) {
1978
+ ramp = valueRamp(range, palettes, colorOptions);
1979
+ }
1980
+ else if (codes) {
1981
+ ramp = codeRamp(series, codes, palettes, colorOptions);
1982
+ }
1983
+ return {
1984
+ trace: {
1985
+ id: series.id,
1986
+ layerId: series.id,
1987
+ name: series.name ?? `${axes.length} measures`,
1988
+ color,
1989
+ axis: series.axis ?? "y",
1990
+ ramp,
1991
+ colorField,
1992
+ ...(range ? colorScaleOf(range, colorOptions) : {}),
1993
+ data: { at: "records", geom, axes, lines },
1994
+ },
1995
+ skipped: skipped(whole.length, step),
1996
+ incomplete,
1997
+ axesDropped: ids.length - kept.length,
1998
+ };
1999
+ }
2000
+ /**
2001
+ * One reduction over the table, drawn as an arc.
2002
+ *
2003
+ * A gauge reduces `value` to one number. The range comes from `scales.y.limits`, or the measure's
2004
+ * extent stands in.
2005
+ */
2006
+ function gaugeTrace(series, data, fieldAt, color, rangeFor, stated) {
2007
+ const bound = series.aes.value;
2008
+ const id = typeof bound === "string" ? bound : undefined;
2009
+ const field = id ? fieldAt.get(id) : undefined;
2010
+ if (!field?.numeric)
2011
+ return null;
2012
+ const aggregate = (series.aggregate ?? "mean");
2013
+ const collect = NEEDS_VALUES.includes(aggregate);
2014
+ const bucket = { n: 0, sum: 0, sumSq: 0, min: Infinity, max: -Infinity };
2015
+ const values = [];
2016
+ for (let row = 0; row < data.rowCount; row += 1) {
2017
+ const reading = data.number(row, field.id);
2018
+ if (reading == null)
2019
+ continue;
2020
+ bucket.n += 1;
2021
+ bucket.sum += reading;
2022
+ bucket.sumSq += reading * reading;
2023
+ bucket.min = Math.min(bucket.min, reading);
2024
+ bucket.max = Math.max(bucket.max, reading);
2025
+ if (collect)
2026
+ values.push(reading);
2027
+ }
2028
+ if (bucket.n === 0)
2029
+ return null;
2030
+ const range = stated ? [stated[0], stated[1]] : rangeFor(field.id);
2031
+ if (!range)
2032
+ return null;
2033
+ return {
2034
+ id: series.id,
2035
+ layerId: series.id,
2036
+ name: series.name ?? `${aggregate} of ${field.label}`,
2037
+ color,
2038
+ axis: series.axis ?? "y",
2039
+ field,
2040
+ ramp: () => color,
2041
+ data: { at: "groups", geom: "gauge", value: reduceBucket(bucket, aggregate, values), range, aggregate },
2042
+ };
2043
+ }
2044
+ /**
2045
+ * The ends a summary's color runs between, over the medians it drew.
2046
+ *
2047
+ * An extent taken inside the geom puts each panel on its own scale.
2048
+ */
2049
+ const medianSpread = (medians) => {
2050
+ /* A counting pass. A spread argument list caps the categories a summary can hold. */
2051
+ let lo = Infinity;
2052
+ let hi = -Infinity;
2053
+ for (const median of medians) {
2054
+ if (median < lo)
2055
+ lo = median;
2056
+ if (median > hi)
2057
+ hi = median;
2058
+ }
2059
+ return [lo, hi];
2060
+ };
2061
+ /** ggplot's `geom_text` and `geom_label`: one label per row, painted by the color channel. */
2062
+ function textTrace(series, ctx) {
2063
+ const yId = typeof series.aes.y === "string" ? series.aes.y : undefined;
2064
+ const yField = yId ? ctx.fieldAt.get(yId) : undefined;
2065
+ const labelId = typeof series.aes.label === "string" ? series.aes.label : undefined;
2066
+ const labelField = labelId ? ctx.fieldAt.get(labelId) : undefined;
2067
+ if (!yId || !yField?.numeric || !labelField)
2068
+ return null;
2069
+ const colorId = paintColumn(series);
2070
+ const colorField = colorId ? ctx.fieldAt.get(colorId) : undefined;
2071
+ const codes = colorField && !colorField.numeric ? ctx.codesFor(colorField.id) : null;
2072
+ const bands = ctx.axisKind === "band" && !ctx.xField.numeric ? ctx.codesFor(ctx.xId) : null;
2073
+ const points = pointsOf(ctx.data, ctx.xId, yId, labelField, colorField, codes, null, null, bands, undefined, shoveOf(series)).filter((point) => point.text != null);
2074
+ if (points.length === 0)
2075
+ return null;
2076
+ const range = colorField?.numeric ? ctx.rangeFor(colorField.id) : null;
2077
+ const ramp = range
2078
+ ? valueRamp(range, ctx.palettes, ctx.colorOptions)
2079
+ : codes
2080
+ ? codeRamp(series, codes, ctx.palettes, ctx.colorOptions)
2081
+ : (() => ctx.color);
2082
+ return {
2083
+ id: series.id,
2084
+ layerId: series.id,
2085
+ name: series.name ?? labelField.label,
2086
+ color: ctx.color,
2087
+ axis: series.axis ?? "y",
2088
+ field: yField,
2089
+ ramp,
2090
+ ...(colorField ? { colorField } : {}),
2091
+ data: { at: "records", geom: "text", points, ...(series.kind === "label" ? { boxed: true } : {}) },
2092
+ };
2093
+ }
2094
+ /** Reference lines one layer draws. The footer counts the rest. */
2095
+ export const RULE_CAP = 24;
2096
+ /**
2097
+ * One reference line per row, off the layer's own position channels.
2098
+ *
2099
+ * An `abline` with neither channel bound is the identity line, ggplot's slope one and intercept zero.
2100
+ */
2101
+ function ruleTrace(series, geom, ctx) {
2102
+ const idOf = (channel) => {
2103
+ const id = series.aes[channel];
2104
+ return typeof id === "string" && ctx.fieldAt.get(id)?.numeric ? id : undefined;
2105
+ };
2106
+ const read = (id, row, fallback) => id ? ctx.data.number(row, id) : fallback;
2107
+ const labelId = typeof series.aes.label === "string" ? series.aes.label : undefined;
2108
+ const yi = idOf("yintercept");
2109
+ const xi = idOf("xintercept");
2110
+ const slopeId = idOf("slope");
2111
+ const interceptId = idOf("intercept");
2112
+ const rules = [];
2113
+ for (let row = 0; row < ctx.data.rowCount; row += 1) {
2114
+ const label = labelId ? (ctx.data.text(row, labelId) ?? undefined) : undefined;
2115
+ const named = label == null ? {} : { label };
2116
+ if (geom === "hline") {
2117
+ const y = read(yi, row, null);
2118
+ if (y != null)
2119
+ rules.push({ kind: "h", y, ...named });
2120
+ }
2121
+ else if (geom === "vline") {
2122
+ const x = read(xi, row, null);
2123
+ if (x != null)
2124
+ rules.push({ kind: "v", x, ...named });
2125
+ }
2126
+ else {
2127
+ const slope = read(slopeId, row, 1);
2128
+ const intercept = read(interceptId, row, 0);
2129
+ if (slope != null && intercept != null)
2130
+ rules.push({ kind: "ab", slope, intercept, ...named });
2131
+ }
2132
+ }
2133
+ if (rules.length === 0)
2134
+ return null;
2135
+ /* Rows naming the same line draw it once. */
2136
+ const distinct = [...new Map(rules.map((rule) => [JSON.stringify(rule), rule])).values()];
2137
+ omit(ctx.omitted, "rules", distinct.length - RULE_CAP);
2138
+ return {
2139
+ id: series.id,
2140
+ layerId: series.id,
2141
+ name: series.name ?? geom,
2142
+ color: ctx.color,
2143
+ axis: series.axis ?? "y",
2144
+ ramp: (() => ctx.color),
2145
+ data: { at: "records", geom, rules: distinct.slice(0, RULE_CAP) },
2146
+ };
2147
+ }
2148
+ /** Positions along X where a row names a place and holds no reading. A line breaks there. */
2149
+ function missingAlong(data, xId, yId) {
2150
+ const out = [];
2151
+ for (let row = 0; row < data.rowCount; row += 1) {
2152
+ const x = data.number(row, xId);
2153
+ if (x != null && data.number(row, yId) == null)
2154
+ out.push(x);
2155
+ }
2156
+ return out.sort((a, b) => a - b);
2157
+ }
2158
+ /**
2159
+ * Marks the first reading past each gap, on readings sorted along X.
2160
+ *
2161
+ * A gap before the first reading or after the last breaks nothing.
2162
+ */
2163
+ function breakAtGaps(points, gaps) {
2164
+ let at = 0;
2165
+ for (let index = 1; index < points.length && at < gaps.length; index += 1) {
2166
+ while (at < gaps.length && gaps[at] <= points[index - 1].x)
2167
+ at += 1;
2168
+ if (at < gaps.length && gaps[at] < points[index].x) {
2169
+ points[index].gap = true;
2170
+ while (at < gaps.length && gaps[at] < points[index].x)
2171
+ at += 1;
2172
+ }
2173
+ }
2174
+ }
2175
+ function traceOf(series, geom, ctx) {
2176
+ // These bind their own channels and wait for no shared X. Each is built above this.
2177
+ if (geom === "sankey" || geom === "parcoords" || geom === "radar")
2178
+ return null;
2179
+ if (geom === "hline" || geom === "vline" || geom === "abline")
2180
+ return ruleTrace(series, geom, ctx);
2181
+ const yId = typeof series.aes.y === "string" ? series.aes.y : undefined;
2182
+ const yField = yId ? ctx.fieldAt.get(yId) : undefined;
2183
+ const base = {
2184
+ id: series.id,
2185
+ layerId: series.id,
2186
+ color: ctx.color,
2187
+ axis: series.axis ?? "y",
2188
+ field: yField,
2189
+ // A reduction has no per-geom weight. The whole trace takes the series color.
2190
+ ramp: (() => ctx.color),
2191
+ };
2192
+ /*
2193
+ The cube. Three measures, three scales, and a payload the camera positions. The color and
2194
+ size channels resolve the way they do on a flat scatter.
2195
+ */
2196
+ if (geom === "point3d") {
2197
+ const zId = typeof series.aes.z === "string" ? series.aes.z : undefined;
2198
+ const zField = zId ? ctx.fieldAt.get(zId) : undefined;
2199
+ if (!yId || !yField?.numeric || !zField?.numeric || !ctx.xField.numeric)
2200
+ return null;
2201
+ const colorId = paintColumn(series);
2202
+ const colorField = colorId ? ctx.fieldAt.get(colorId) : undefined;
2203
+ const codes = colorField && !colorField.numeric ? ctx.codesFor(colorField.id) : null;
2204
+ const labelField = series.directLabels ? ctx.fieldAt.get(series.directLabels.field) : undefined;
2205
+ const sizeId = typeof series.aes.size === "string" ? series.aes.size : undefined;
2206
+ const sizeField = sizeId ? ctx.fieldAt.get(sizeId) : undefined;
2207
+ const sizeDomain = sizeField?.numeric ? ctx.rangeFor(sizeField.id) : null;
2208
+ const sizeRadii = series.style?.sizeRange ?? sizeRadiiFor(ctx.metrics);
2209
+ const size = sizeField && sizeDomain ? { field: sizeField, domain: sizeDomain, radii: sizeRadii } : null;
2210
+ /* The cube reads each field's own log flag. It draws no frame axis for an author to set. */
2211
+ const points = pointsOf(ctx.data, ctx.xId, yId, labelField, colorField, codes, size, zField).filter((point) => !(ctx.xField.logScale && point.x <= 0) && !(yField.logScale && point.y <= 0));
2212
+ if (points.length === 0)
2213
+ return null;
2214
+ const zDomain = ctx.rangeFor(zField.id);
2215
+ const xDomain = ctx.rangeFor(ctx.xId);
2216
+ const yDomain = ctx.rangeFor(yId);
2217
+ if (!zDomain || !xDomain || !yDomain)
2218
+ return null;
2219
+ let ramp = base.ramp;
2220
+ const range = colorField?.numeric ? ctx.rangeFor(colorField.id) : null;
2221
+ if (range) {
2222
+ ramp = valueRamp(range, ctx.palettes, ctx.colorOptions);
2223
+ }
2224
+ else if (codes) {
2225
+ ramp = codeRamp(series, codes, ctx.palettes, ctx.colorOptions);
2226
+ }
2227
+ return {
2228
+ ...base,
2229
+ name: series.name ?? zField.label,
2230
+ ramp,
2231
+ colorField,
2232
+ ...(range ? colorScaleOf(range, ctx.colorOptions) : {}),
2233
+ zField,
2234
+ ...(size ? { sizeField: size.field, sizeDomain: size.domain, sizeRadii: size.radii } : {}),
2235
+ data: { at: "records", geom, points, zField, xDomain, yDomain, zDomain },
2236
+ };
2237
+ }
2238
+ /*
2239
+ The two cube kinds that read a field through its depth. Three position channels place the
2240
+ grid and a fourth says what the cells measure. Unbound, they count rows.
2241
+ */
2242
+ if (geom === "isosurface" || geom === "volume") {
2243
+ const zId = typeof series.aes.z === "string" ? series.aes.z : undefined;
2244
+ const zField = zId ? ctx.fieldAt.get(zId) : undefined;
2245
+ if (!yId || !yField?.numeric || !zField?.numeric || !ctx.xField.numeric)
2246
+ return null;
2247
+ const valueId = typeof series.aes.value === "string" ? series.aes.value : undefined;
2248
+ const valueField = valueId ? ctx.fieldAt.get(valueId) : undefined;
2249
+ if (valueId && !valueField?.numeric)
2250
+ return null;
2251
+ const aggregate = (series.aggregate ?? "mean");
2252
+ const field = field3d(ctx.data, ctx.xId, yId, zField.id, valueField?.id ?? null, aggregate);
2253
+ if (!field)
2254
+ return null;
2255
+ return {
2256
+ ...base,
2257
+ name: series.name ?? (valueField ? `${aggregate} of ${valueField.label}` : "Count"),
2258
+ zField,
2259
+ data: {
2260
+ at: "groups",
2261
+ geom,
2262
+ field,
2263
+ ...(valueField ? { valueField } : {}),
2264
+ xDomain: field.xDomain,
2265
+ yDomain: field.yDomain,
2266
+ zDomain: field.zDomain,
2267
+ },
2268
+ };
2269
+ }
2270
+ /*
2271
+ The two cube kinds that draw a surface. A relief reduces a measure over a grid of two others
2272
+ and triangulates it. A structure arrives as vertices and faces.
2273
+ */
2274
+ if (geom === "surface" || geom === "mesh3d") {
2275
+ const zId = typeof series.aes.z === "string" ? series.aes.z : undefined;
2276
+ const zField = zId ? ctx.fieldAt.get(zId) : undefined;
2277
+ if (!yId || !yField?.numeric || !zField?.numeric || !ctx.xField.numeric)
2278
+ return null;
2279
+ if (geom === "surface") {
2280
+ const aggregate = (series.aggregate ?? "mean");
2281
+ const grid = relief(ctx.data, ctx.xId, yId, zField.id, aggregate);
2282
+ const mesh = grid ? meshOfRelief(grid) : null;
2283
+ if (!grid || !mesh)
2284
+ return null;
2285
+ return {
2286
+ ...base,
2287
+ name: series.name ?? `${aggregate} of ${zField.label}`,
2288
+ zField,
2289
+ data: { at: "groups", geom, mesh, zField, xDomain: grid.xDomain, yDomain: grid.yDomain, aggregate },
2290
+ };
2291
+ }
2292
+ /* Three columns of row numbers, one triangle a row, which is how a structure states its faces. */
2293
+ const bound = series.aes.faces;
2294
+ const faceIds = (Array.isArray(bound) ? bound : bound ? [bound] : []).filter((id) => ctx.fieldAt.has(id));
2295
+ if (faceIds.length !== 3)
2296
+ return null;
2297
+ const faces = [];
2298
+ for (let row = 0; row < ctx.data.rowCount; row += 1) {
2299
+ const corners = faceIds.map((id) => ctx.data.number(row, id));
2300
+ if (corners.some((corner) => corner == null))
2301
+ continue;
2302
+ faces.push(corners.map((corner) => Math.round(corner)));
2303
+ }
2304
+ const mesh = meshOfRows(ctx.data, ctx.xId, yId, zField.id, faces);
2305
+ const xSpan = ctx.rangeFor(ctx.xId);
2306
+ const ySpan = ctx.rangeFor(yId);
2307
+ if (!mesh || !xSpan || !ySpan)
2308
+ return null;
2309
+ return {
2310
+ ...base,
2311
+ name: series.name ?? zField.label,
2312
+ zField,
2313
+ data: { at: "groups", geom, mesh, zField, xDomain: xSpan, yDomain: ySpan },
2314
+ };
2315
+ }
2316
+ if (geom === "heatmap") {
2317
+ if (ctx.axisKind !== "band")
2318
+ return null;
2319
+ /**
2320
+ * The ends a ramp runs between.
2321
+ *
2322
+ * A fraction pins to zero and one, and a count to zero. Otherwise the extent of the cells
2323
+ * stands.
2324
+ */
2325
+ /*
2326
+ A z-scored grid is a measure whatever it reduced. Its neutral is zero. Centered and divided
2327
+ by its own spread, a fraction becomes an extent like any other measure.
2328
+ */
2329
+ const scale = ctx.colorOptions?.standardize ?? "none";
2330
+ const scaled = (cells) => scaledCells(cells, scale);
2331
+ const colorOptions = rampOptionsFor("heatmap", ctx.colorOptions);
2332
+ const heatExtent = (cells, kind) => {
2333
+ if (kind === "fraction" && scale === "none")
2334
+ return [0, 1];
2335
+ /* A grid is the cross-product of its two bands and reaches the count `boundsOf` exists for. */
2336
+ const [lo, hi] = boundsOf(cells.map((cell) => cell.value));
2337
+ return kind === "count" && scale === "none" ? [0, hi] : [lo, hi];
2338
+ };
2339
+ /* The author's setting is the more specific instruction, and the ramp reads the same answer. */
2340
+ const heatDomain = (cells, kind) => colorScaleOf(heatExtent(cells, kind), colorOptions);
2341
+ /* The domain reaches the ramp here. The geom draws a value and runs no scale of its own. */
2342
+ const heatRamp = (domain) => valueRamp(domain, ctx.palettes, colorOptions);
2343
+ /*
2344
+ Three grids on one geom, told apart by the binding. A list of measures binds columns that
2345
+ are not a column, and a sequence binds positions inside a string.
2346
+ */
2347
+ const bound = series.aes.dimensions;
2348
+ const measureIds = (Array.isArray(bound) ? bound : bound ? [bound] : []).filter((id) => ctx.fieldAt.has(id));
2349
+ if (measureIds.length > 0) {
2350
+ const measures = measureIds.map((id) => ctx.fieldAt.get(id));
2351
+ const cells = scaled(gateCells(ctx.data, ctx.xId, measures));
2352
+ if (cells.length === 0)
2353
+ return null;
2354
+ const domain = heatDomain(cells, "fraction");
2355
+ return {
2356
+ ...base,
2357
+ name: series.name ?? "fraction clearing the cut",
2358
+ ...domain,
2359
+ ramp: heatRamp(domain.colorExtent),
2360
+ data: { at: "groups", geom, cells, aggregate: "mean" },
2361
+ };
2362
+ }
2363
+ if (!yId) {
2364
+ const xField = ctx.fieldAt.get(ctx.xId);
2365
+ if (xField?.role !== "sequence")
2366
+ return null;
2367
+ const cells = scaled(occupancyCells(ctx.data, ctx.xId));
2368
+ if (cells.length === 0)
2369
+ return null;
2370
+ const domain = heatDomain(cells, "fraction");
2371
+ return {
2372
+ ...base,
2373
+ name: series.name ?? `${xField.label} occupancy`,
2374
+ ...domain,
2375
+ ramp: heatRamp(domain.colorExtent),
2376
+ data: { at: "groups", geom, cells, aggregate: "mean" },
2377
+ };
2378
+ }
2379
+ /* A text column on `fill` paints each cell by its rows' most common category. */
2380
+ const fillId = typeof series.aes.fill === "string" ? series.aes.fill : undefined;
2381
+ const fillField = fillId ? ctx.fieldAt.get(fillId) : undefined;
2382
+ if (fillField && !fillField.numeric) {
2383
+ const cells = modeCells(ctx.data, ctx.xId, yId, fillField.id);
2384
+ if (cells.length === 0)
2385
+ return null;
2386
+ const codes = ctx.codesFor(fillField.id);
2387
+ const levels = new Map([...codes].map(([value, code]) => [code, value]));
2388
+ /* A keyed map names a color per category and stays outside the palette switcher. */
2389
+ const keyed = ctx.colorOptions?.values;
2390
+ /* An indexed map stops at its length. Cycling past it would give two categories one hue. */
2391
+ const size = ctx.palettes.categoricalSize ?? Infinity;
2392
+ const own = (code) => {
2393
+ if (!keyed)
2394
+ return code < size ? ctx.palettes.categorical(code) : undefined;
2395
+ const level = levels.get(code);
2396
+ return level != null && Object.hasOwn(keyed, level) ? keyed[level] : undefined;
2397
+ };
2398
+ const ramp = ((code) => own(Math.round(code)) ?? UNMAPPED_INK);
2399
+ /* The categories the cells take, in code order. One no cell takes stays out of the legend. */
2400
+ const taken = new Set(cells.map((cell) => cell.category));
2401
+ const drawn = [...codes]
2402
+ .filter(([value]) => taken.has(value))
2403
+ .map(([value, code]) => ({ value, code }))
2404
+ .sort((a, b) => a.code - b.code);
2405
+ const hued = drawn.filter(({ code }) => own(code) != null);
2406
+ omit(ctx.omitted, "fills", drawn.length - hued.length);
2407
+ const colorOf = new Map(drawn.map(({ value, code }) => [value, ramp(code)]));
2408
+ return {
2409
+ ...base,
2410
+ field: undefined,
2411
+ name: series.name ?? fillField.label,
2412
+ ramp,
2413
+ colorField: fillField,
2414
+ colorLevels: hued,
2415
+ data: {
2416
+ at: "groups",
2417
+ geom,
2418
+ cells: cells.map((cell) => ({ ...cell, color: colorOf.get(cell.category) })),
2419
+ aggregate: "mean",
2420
+ },
2421
+ };
2422
+ }
2423
+ // Both axes name categories, and the color channel carries the measure the cells reduce.
2424
+ const zId = typeof series.aes.z === "string" ? series.aes.z : undefined;
2425
+ const zField = zId ? ctx.fieldAt.get(zId) : undefined;
2426
+ const aggregate = (series.aggregate ?? (zField ? "mean" : "count"));
2427
+ const measure = aggregate === "count" ? null : (zField?.id ?? null);
2428
+ if (!measure && aggregate !== "count")
2429
+ return null;
2430
+ const reduced = cellsOf(ctx.data, ctx.xId, yId, measure, aggregate);
2431
+ if (reduced.length === 0)
2432
+ return null;
2433
+ /*
2434
+ A pair with no rows, filled at nought where the style asks for it.
2435
+
2436
+ Here and not in the geom, so the color domain covers the nought. Filled at draw time it sat
2437
+ below the domain the real cells set and clamped to a shade the ramp never shows.
2438
+ */
2439
+ const cells = scaled(series.style?.emptyAsZero ? withZeros(reduced) : reduced);
2440
+ const gridDomain = heatDomain(cells, aggregate === "count" ? "count" : "measure");
2441
+ return {
2442
+ ...base,
2443
+ field: zField,
2444
+ name: series.name ?? (zField ? `${aggregate} of ${zField.label}` : "Count"),
2445
+ ...gridDomain,
2446
+ ramp: heatRamp(gridDomain.colorExtent),
2447
+ data: { at: "groups", geom, cells, aggregate },
2448
+ };
2449
+ }
2450
+ if (geom === "boxplot" || geom === "violin") {
2451
+ // Both want the values themselves, and a category to hold them apart.
2452
+ if (!yId || !yField?.numeric || ctx.axisKind !== "band")
2453
+ return null;
2454
+ const params = series.statParams ?? {};
2455
+ const boxes = [];
2456
+ const violins = [];
2457
+ const held = params.scale ?? "area";
2458
+ for (const [category, values] of valuesByCategory(ctx.data, ctx.xId, yId)) {
2459
+ const stats = boxStats(values, { coef: params.coef, quantileType: params.quantileType });
2460
+ if (!stats)
2461
+ continue;
2462
+ if (geom === "boxplot") {
2463
+ boxes.push({ category, ...stats });
2464
+ continue;
2465
+ }
2466
+ /*
2467
+ The outline, on the author's kernel.
2468
+
2469
+ `trim` defaults true here where the statistic's own default is false. A tail past the
2470
+ largest reading claims a measurement above it.
2471
+ */
2472
+ const density = kde(values, {
2473
+ bw: params.bw,
2474
+ adjust: params.adjust,
2475
+ kernel: params.kernel,
2476
+ bounds: params.bounds,
2477
+ trim: params.trim ?? true,
2478
+ n: VIOLIN_OUTLINE,
2479
+ // `width` reads a group's own peak. The other two divide over the whole list below.
2480
+ normalize: held === "width" ? "peak" : "density",
2481
+ });
2482
+ // A density needs a spread to estimate over. A category on one value draws none.
2483
+ if (!density) {
2484
+ if (params.drop === false)
2485
+ violins.push({ category, ...stats, grid: [], weight: [], bandwidth: 0 });
2486
+ continue;
2487
+ }
2488
+ violins.push({
2489
+ category,
2490
+ ...stats,
2491
+ ...density,
2492
+ quantiles: (params.quantiles ?? QUARTILES).flatMap((p) => {
2493
+ const at = quantileOf(values, p, params.quantileType ?? 7);
2494
+ return at == null ? [] : [at];
2495
+ }),
2496
+ });
2497
+ }
2498
+ const name = series.name ?? yField.label;
2499
+ if (geom === "violin") {
2500
+ if (violins.length === 0)
2501
+ return null;
2502
+ const spread = medianSpread(violins.map((violin) => violin.median));
2503
+ return {
2504
+ ...base,
2505
+ name,
2506
+ ...colorScaleOf(spread, ctx.colorOptions),
2507
+ ramp: valueRamp(spread, ctx.palettes, ctx.colorOptions),
2508
+ data: { at: "groups", geom, violins: heldAcross(violins, held) },
2509
+ };
2510
+ }
2511
+ if (boxes.length === 0)
2512
+ return null;
2513
+ const spread = medianSpread(boxes.map((box) => box.median));
2514
+ return {
2515
+ ...base,
2516
+ name,
2517
+ ...colorScaleOf(spread, ctx.colorOptions),
2518
+ ramp: valueRamp(spread, ctx.palettes, ctx.colorOptions),
2519
+ data: { at: "groups", geom, boxes },
2520
+ };
2521
+ }
2522
+ /*
2523
+ The band. Two bound columns and no reduction. Sorted along X here, where the fill walks
2524
+ forward along the high bound and back along the low one.
2525
+ */
2526
+ /*
2527
+ Both read the same pair of bounds. A band closes one region, and two readings are the floor of
2528
+ what draws. A range is a mark per reading.
2529
+ */
2530
+ if (geom === "ribbon" || geom === "range") {
2531
+ const loId = typeof series.aes.ymin === "string" ? series.aes.ymin : undefined;
2532
+ const hiId = typeof series.aes.ymax === "string" ? series.aes.ymax : undefined;
2533
+ const midId = typeof series.aes.y === "string" ? series.aes.y : undefined;
2534
+ if (!loId || !hiId)
2535
+ return null;
2536
+ if (!ctx.fieldAt.get(loId)?.numeric || !ctx.fieldAt.get(hiId)?.numeric)
2537
+ return null;
2538
+ const numericX = ctx.xField.numeric;
2539
+ const readings = [];
2540
+ for (let row = 0; row < ctx.data.rowCount; row += 1) {
2541
+ const at = numericX ? ctx.data.number(row, ctx.xId) : ctx.data.text(row, ctx.xId);
2542
+ const lo = ctx.data.number(row, loId);
2543
+ const hi = ctx.data.number(row, hiId);
2544
+ if (at == null || lo == null || hi == null)
2545
+ continue;
2546
+ const mid = midId ? ctx.data.number(row, midId) : null;
2547
+ // The author may have written the bounds either way round, and a band has no direction.
2548
+ readings.push({ x: at, lo: Math.min(lo, hi), hi: Math.max(lo, hi), ...(mid == null ? {} : { mid }) });
2549
+ }
2550
+ if (readings.length < (geom === "ribbon" ? 2 : 1))
2551
+ return null;
2552
+ if (numericX)
2553
+ readings.sort((a, b) => a.x - b.x);
2554
+ /*
2555
+ The estimate names the axis where one was bound.
2556
+
2557
+ `field` is what the axis title and the readout read. A band with no `y` names a bound.
2558
+ */
2559
+ const named = ctx.fieldAt.get(midId ?? hiId) ?? ctx.fieldAt.get(hiId);
2560
+ return {
2561
+ ...base,
2562
+ name: series.name ?? named?.label ?? (geom === "ribbon" ? "Interval" : "Range"),
2563
+ field: named,
2564
+ data: geom === "range"
2565
+ ? { at: "records", geom, glyph: series.kind, readings }
2566
+ : { at: "records", geom, readings },
2567
+ };
2568
+ }
2569
+ /*
2570
+ The segment. Four bound columns, read in the order they stand.
2571
+
2572
+ A row missing any of the four is dropped, and both ends are numeric.
2573
+ */
2574
+ if (geom === "segment") {
2575
+ const xEndId = typeof series.aes.xend === "string" ? series.aes.xend : undefined;
2576
+ const yEndId = typeof series.aes.yend === "string" ? series.aes.yend : undefined;
2577
+ if (!yId || !xEndId || !yEndId)
2578
+ return null;
2579
+ /*
2580
+ The dumbbell runs the pair inside one category.
2581
+
2582
+ Both ends name the same category, and the two measures do the moving. A mixed pair is refused.
2583
+ */
2584
+ const bands = ctx.axisKind === "band" && !ctx.xField.numeric;
2585
+ /* A category on a value scale has no place. The footer counts the rows it drops. */
2586
+ const placed = bands ? [yId, yEndId] : [yId, yEndId, ctx.xId, xEndId];
2587
+ if (placed.some((id) => ctx.fieldAt.get(id)?.numeric === false)) {
2588
+ omit(ctx.omitted, "segments", ctx.data.rowCount);
2589
+ return null;
2590
+ }
2591
+ if (!yField?.numeric || !ctx.fieldAt.get(yEndId)?.numeric)
2592
+ return null;
2593
+ if (!bands && (!ctx.xField.numeric || !ctx.fieldAt.get(xEndId)?.numeric))
2594
+ return null;
2595
+ if (bands && ctx.fieldAt.get(xEndId)?.numeric)
2596
+ return null;
2597
+ const outer = viewRows.get(ctx.data);
2598
+ const segments = [];
2599
+ for (let row = 0; row < ctx.data.rowCount; row += 1) {
2600
+ const x = bands ? ctx.data.text(row, ctx.xId) : ctx.data.number(row, ctx.xId);
2601
+ const y = ctx.data.number(row, yId);
2602
+ const xEnd = bands ? x : ctx.data.number(row, xEndId);
2603
+ const yEnd = ctx.data.number(row, yEndId);
2604
+ if (x == null || y == null || xEnd == null || yEnd == null)
2605
+ continue;
2606
+ segments.push({ x, y, xEnd, yEnd, row: ctx.data.rowIndex(row), plotRow: outer ? outer[row] : row });
2607
+ }
2608
+ if (segments.length === 0)
2609
+ return null;
2610
+ return {
2611
+ ...base,
2612
+ name: series.name ?? yField.label,
2613
+ data: { at: "records", geom, segments },
2614
+ };
2615
+ }
2616
+ /*
2617
+ Bars and areas always reduce. A line reduces too where the axis has categories. An area takes
2618
+ the route bars take, and a continuous axis bins it first.
2619
+ */
2620
+ /*
2621
+ A kernel density over the measure on X, drawn as one curve.
2622
+
2623
+ The vertical scale has the density itself. No measure binds to it and the trace names none.
2624
+ */
2625
+ if (geom === "density") {
2626
+ if (ctx.axisKind !== "continuous")
2627
+ return null;
2628
+ const params = series.statParams ?? {};
2629
+ const values = [];
2630
+ for (let row = 0; row < ctx.data.rowCount; row += 1) {
2631
+ const value = ctx.data.number(row, ctx.xId);
2632
+ if (value != null)
2633
+ values.push(value);
2634
+ }
2635
+ const curve = kde(values, {
2636
+ bw: params.bw,
2637
+ adjust: params.adjust,
2638
+ kernel: params.kernel,
2639
+ n: params.n,
2640
+ trim: params.trim,
2641
+ bounds: params.bounds,
2642
+ });
2643
+ if (!curve)
2644
+ return null;
2645
+ return { ...base, name: series.name ?? `density of ${ctx.xField.label}`, data: { at: "groups", geom, curve } };
2646
+ }
2647
+ const ring = geom === "pie";
2648
+ if (geom === "bar" ||
2649
+ geom === "waterfall" ||
2650
+ geom === "area" ||
2651
+ geom === "freqpoly" ||
2652
+ ring ||
2653
+ (geom === "line" && ctx.axisKind === "band")) {
2654
+ /*
2655
+ Steps are an ordered sequence and bins are a measure cut up.
2656
+
2657
+ A waterfall asks its horizontal channel for categories, and a continuous one draws none.
2658
+ */
2659
+ if (geom === "waterfall" && ctx.axisKind !== "band")
2660
+ return null;
2661
+ /*
2662
+ A ring divides one whole, and bins divide no whole anybody measured.
2663
+
2664
+ A pie asks its horizontal channel for categories. The aggregate keeps the bar's default mean.
2665
+ */
2666
+ if (ring && ctx.axisKind !== "band")
2667
+ return null;
2668
+ // An unbound measure defaults the aggregate to "count". The series answers how many rows.
2669
+ // A bound measure defaults to "mean", and to "sum" under a running total.
2670
+ const aggregate = (series.aggregate ?? (yField ? (runs(series) ? "sum" : "mean") : "count"));
2671
+ const measure = aggregate === "count" ? null : (yField?.id ?? null);
2672
+ if (!measure && aggregate !== "count")
2673
+ return null;
2674
+ const name = series.name ?? (yField ? `${aggregate} of ${yField.label}` : "Count");
2675
+ /*
2676
+ A count has no spread, and the author's request is dropped under it.
2677
+
2678
+ `halfWidth` returns undefined where the group has one reading.
2679
+ */
2680
+ const wants = aggregate === "count" ? undefined : series.error;
2681
+ const halfWidth = (of) => {
2682
+ if (!wants)
2683
+ return undefined;
2684
+ const half = wants === "sem" ? of.sem : of.sd;
2685
+ return half > 0 ? half : undefined;
2686
+ };
2687
+ if (ctx.axisKind === "band") {
2688
+ const shows = aggregate !== "count" && series.replicates === true;
2689
+ let replicatesDropped = 0;
2690
+ const bars = groupRows(ctx.data, ctx.xId, measure, aggregate, shows).map((group) => {
2691
+ const crowded = (group.values?.length ?? 0) > REPLICATE_CAP;
2692
+ if (shows && crowded)
2693
+ replicatesDropped += 1;
2694
+ return {
2695
+ category: group.key,
2696
+ value: group.value,
2697
+ n: group.n,
2698
+ error: halfWidth(group),
2699
+ ...(shows && !crowded ? { values: group.values } : {}),
2700
+ };
2701
+ });
2702
+ /* The cap the geom applied, on the ledger the footer reads. */
2703
+ omit(ctx.omitted, "replicates", replicatesDropped);
2704
+ return bars.length === 0
2705
+ ? null
2706
+ : {
2707
+ ...base,
2708
+ name,
2709
+ data: {
2710
+ at: "groups",
2711
+ geom,
2712
+ bars,
2713
+ aggregate,
2714
+ error: wants,
2715
+ ...(replicatesDropped ? { replicatesDropped } : {}),
2716
+ },
2717
+ };
2718
+ }
2719
+ /*
2720
+ A value scale has no groups of its own. A bar draws one per distinct reading, ggplot's
2721
+ `geom_bar` and `geom_col`, and binning is the histogram's.
2722
+ */
2723
+ const { bars, width, offScale } = series.kind === "bar"
2724
+ ? distinctBars(ctx.data, ctx.xId, measure ?? undefined, aggregate, ctx.xTransform, halfWidth)
2725
+ : binnedBars(ctx.data, ctx.xId, measure ?? undefined, aggregate, binOf(series), ctx.xTransform, halfWidth);
2726
+ return bars.length === 0
2727
+ ? null
2728
+ : {
2729
+ ...base,
2730
+ name,
2731
+ data: {
2732
+ at: "groups",
2733
+ geom,
2734
+ bars,
2735
+ aggregate,
2736
+ binWidth: width,
2737
+ error: wants,
2738
+ ...(offScale > 0 ? { offScale } : {}),
2739
+ },
2740
+ };
2741
+ }
2742
+ /* A label per row at its reading. A row with no text writes nothing. */
2743
+ if (geom === "text")
2744
+ return textTrace(series, ctx);
2745
+ /* What is left is the record payload, which five geometries share. */
2746
+ if (geom !== "point" && geom !== "hex" && geom !== "contour" && geom !== "line" && geom !== "smooth")
2747
+ return null;
2748
+ if (!yId || !yField?.numeric)
2749
+ return null;
2750
+ /* A contour over a bound measure cuts the rows' lattice into bands. The corners give the frame its domain. */
2751
+ const levelId = geom === "contour" && typeof series.aes.z === "string" ? series.aes.z : undefined;
2752
+ const levelField = levelId ? ctx.fieldAt.get(levelId) : undefined;
2753
+ if (geom === "contour" && levelField?.numeric && ctx.xField.numeric) {
2754
+ const grid = relief(ctx.data, ctx.xId, yId, levelField.id, (series.aggregate ?? "mean"));
2755
+ if (!grid)
2756
+ return null;
2757
+ const corners = [
2758
+ { x: grid.xDomain[0], y: grid.yDomain[0], row: -1 },
2759
+ { x: grid.xDomain[1], y: grid.yDomain[1], row: -1 },
2760
+ ];
2761
+ return {
2762
+ ...base,
2763
+ name: series.name ?? levelField.label,
2764
+ colorField: levelField,
2765
+ ramp: valueRamp(grid.zDomain, ctx.palettes, ctx.colorOptions),
2766
+ ...colorScaleOf(grid.zDomain, ctx.colorOptions),
2767
+ data: { at: "records", geom, points: corners, grid },
2768
+ };
2769
+ }
2770
+ const labelField = series.directLabels ? ctx.fieldAt.get(series.directLabels.field) : undefined;
2771
+ const colorId = paintColumn(series);
2772
+ const colorField = colorId ? ctx.fieldAt.get(colorId) : undefined;
2773
+ const codes = colorField && !colorField.numeric ? ctx.codesFor(colorField.id) : null;
2774
+ /*
2775
+ Only points have geoms to size. A cell and a band read as their own count, and a line has no
2776
+ per-record diameter. The channel is refused there.
2777
+ */
2778
+ const sizeId = typeof series.aes.size === "string" ? series.aes.size : undefined;
2779
+ const sizeField = geom === "point" && sizeId ? ctx.fieldAt.get(sizeId) : undefined;
2780
+ const sizeDomain = sizeField?.numeric ? ctx.rangeFor(sizeField.id) : null;
2781
+ const sizeRadii = series.style?.sizeRange ?? sizeRadiiFor(ctx.metrics);
2782
+ const size = sizeField && sizeDomain ? { field: sizeField, domain: sizeDomain, radii: sizeRadii } : null;
2783
+ /*
2784
+ The two channels that resolve per mark. A cell, a band and a path have no mark to take a glyph
2785
+ or an opacity.
2786
+ */
2787
+ const shapeId = geom === "point" && typeof series.aes.shape === "string" ? series.aes.shape : undefined;
2788
+ const shapeField = shapeId ? ctx.fieldAt.get(shapeId) : undefined;
2789
+ /* A measure has no levels to hand out, and four glyphs cannot carry a continuous reading. */
2790
+ const shapes = shapeField && !shapeField.numeric
2791
+ ? { field: shapeField, codes: ctx.codesFor(shapeField.id), levels: POINT_SHAPES }
2792
+ : null;
2793
+ const alphaId = geom === "point" && typeof series.aes.alpha === "string" ? series.aes.alpha : undefined;
2794
+ const alphaField = alphaId ? ctx.fieldAt.get(alphaId) : undefined;
2795
+ const alphaDomain = alphaField?.numeric ? ctx.rangeFor(alphaField.id) : null;
2796
+ const opacities = alphaField
2797
+ ? {
2798
+ field: alphaField,
2799
+ codes: alphaField.numeric ? null : ctx.codesFor(alphaField.id),
2800
+ domain: alphaDomain,
2801
+ }
2802
+ : null;
2803
+ const bandCodes = ctx.axisKind === "band" && !ctx.xField.numeric ? ctx.codesFor(ctx.xId) : null;
2804
+ const points = pointsOf(ctx.data, ctx.xId, yId, labelField, colorField, codes, size, null, bandCodes,
2805
+ /* A jitter position states the two axes apart and a nudge states a fixed offset. */
2806
+ jitterOf(series), shoveOf(series), shapes, opacities);
2807
+ if (points.length === 0)
2808
+ return null;
2809
+ // A line reads left to right, and breaks where a reading is missing, which is ggplot's `geom_path`.
2810
+ if (geom === "line") {
2811
+ points.sort((a, b) => a.x - b.x);
2812
+ breakAtGaps(points, missingAlong(ctx.data, ctx.xId, yId));
2813
+ }
2814
+ /*
2815
+ A running total over the readings themselves.
2816
+
2817
+ The grouped path accumulates its groups. A line over records has no groups to accumulate, and
2818
+ the same request there means the arrival curve: each reading carries what came before it.
2819
+ */
2820
+ const readings = runs(series) ? accumulateAlong(points) : points;
2821
+ /*
2822
+ Magnitude takes the sequential map and identity takes the categorical one, per chart-design
2823
+ rule 8. Sampling a sequential map for identity leaves neighboring groups indistinguishable.
2824
+ */
2825
+ let ramp = base.ramp;
2826
+ const range = colorField?.numeric ? ctx.rangeFor(colorField.id) : null;
2827
+ if (range) {
2828
+ ramp = valueRamp(range, ctx.palettes, ctx.colorOptions);
2829
+ }
2830
+ else if (codes) {
2831
+ ramp = codeRamp(series, codes, ctx.palettes, ctx.colorOptions);
2832
+ }
2833
+ /* The assignment, sorted by the index it hands out. The legend reads in palette order. */
2834
+ const colorLevels = codes
2835
+ ? [...codes].map(([value, code]) => ({ value, code })).sort((a, b) => a.code - b.code)
2836
+ : undefined;
2837
+ return {
2838
+ ...base,
2839
+ name: series.name ?? yField.label,
2840
+ ramp,
2841
+ colorField,
2842
+ ...(colorLevels ? { colorLevels } : {}),
2843
+ ...(range ? colorScaleOf(range, ctx.colorOptions) : {}),
2844
+ ...(size ? { sizeField: size.field, sizeDomain: size.domain, sizeRadii: size.radii } : {}),
2845
+ ...(shapes ? { shapeChannel: { field: shapes.field, levels: levelsOf(shapes) } } : {}),
2846
+ ...(opacities
2847
+ ? {
2848
+ alphaChannel: {
2849
+ field: opacities.field,
2850
+ ...(opacities.domain ? { domain: opacities.domain } : {}),
2851
+ ...(opacities.codes
2852
+ ? {
2853
+ levels: [...opacities.codes]
2854
+ .sort((a, b) => a[1] - b[1])
2855
+ .map(([value, code]) => ({
2856
+ value,
2857
+ at: opacityAt(code, [0, Math.max(1, opacities.codes.size - 1)]),
2858
+ })),
2859
+ }
2860
+ : {}),
2861
+ },
2862
+ }
2863
+ : {}),
2864
+ data: {
2865
+ at: "records",
2866
+ geom,
2867
+ points: readings,
2868
+ ...(geom === "contour" && series.statParams?.adjust != null ? { adjust: series.statParams.adjust } : {}),
2869
+ },
2870
+ };
2871
+ }
2872
+ /** What a category draws with where its color map names no color for it. */
2873
+ const UNMAPPED_INK = "var(--viz-ink-muted)";
2874
+ /**
2875
+ * The cells given, plus a nought for every pair of their categories that carries none.
2876
+ *
2877
+ * Built from the categories the cells name. A row absent from every cell has no band on the axis,
2878
+ * so nothing is invented the grid cannot place.
2879
+ */
2880
+ function withZeros(cells) {
2881
+ const xs = [...new Set(cells.map((cell) => cell.x))];
2882
+ const ys = [...new Set(cells.map((cell) => cell.y))];
2883
+ const seen = new Set(cells.map((cell) => `${cell.x}\u0000${cell.y}`));
2884
+ const filled = [...cells];
2885
+ for (const x of xs) {
2886
+ for (const y of ys) {
2887
+ if (!seen.has(`${x}\u0000${y}`))
2888
+ filled.push({ x, y, value: 0, n: 0 });
2889
+ }
2890
+ }
2891
+ return filled;
2892
+ }