@opendata-ai/openchart-engine 8.0.0-rc.12 → 8.0.0-rc.3

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 (271) hide show
  1. package/dist/index.d.ts +0 -7
  2. package/dist/index.js +161 -579
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -3
  5. package/src/__test-fixtures__/specs.ts +182 -0
  6. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +2339 -0
  7. package/src/__tests__/annotation-behavior.test.ts +721 -0
  8. package/src/__tests__/axes.test.ts +1579 -0
  9. package/src/__tests__/compile-animation.test.ts +161 -0
  10. package/src/__tests__/compile-chart.test.ts +1303 -0
  11. package/src/__tests__/compile-footnotes.test.ts +277 -0
  12. package/src/__tests__/compile-layer.test.ts +969 -0
  13. package/src/__tests__/compile-snapshot.test.ts +156 -0
  14. package/src/__tests__/compound-labels.test.ts +147 -0
  15. package/src/__tests__/dimensions.test.ts +918 -0
  16. package/src/__tests__/encoding-sugar.test.ts +390 -0
  17. package/src/__tests__/facet.test.ts +215 -0
  18. package/src/__tests__/helpers/invariants.ts +299 -0
  19. package/src/__tests__/known-bugs.test.ts +566 -0
  20. package/src/__tests__/layout-fuzz.test.ts +358 -0
  21. package/src/__tests__/layout-invariants.test.ts +535 -0
  22. package/src/__tests__/legend.test.ts +721 -0
  23. package/src/__tests__/mark-keys.test.ts +294 -0
  24. package/src/__tests__/ranking-recipes.test.ts +260 -0
  25. package/src/__tests__/rotation.test.ts +83 -0
  26. package/src/__tests__/scales.test.ts +323 -0
  27. package/src/__tests__/series-search.test.ts +92 -0
  28. package/src/__tests__/spec-sugar.test.ts +801 -0
  29. package/src/__tests__/you-draw-it.test.ts +160 -0
  30. package/src/annotations/__tests__/compute.test.ts +1672 -0
  31. package/src/annotations/__tests__/geometry.test.ts +66 -0
  32. package/src/annotations/__tests__/placement-fuzz.test.ts +256 -0
  33. package/src/annotations/__tests__/placement-invariants.test.ts +345 -0
  34. package/src/annotations/__tests__/placement.test.ts +316 -0
  35. package/src/annotations/__tests__/resolve-text.test.ts +788 -0
  36. package/src/annotations/__tests__/rich-text.test.ts +91 -0
  37. package/src/annotations/__tests__/thinning.test.ts +285 -0
  38. package/src/annotations/collisions.ts +326 -0
  39. package/src/annotations/compute.ts +333 -0
  40. package/src/annotations/constants.ts +162 -0
  41. package/src/annotations/geometry.ts +370 -0
  42. package/src/annotations/move.ts +135 -0
  43. package/src/annotations/placement.ts +636 -0
  44. package/src/annotations/position.ts +131 -0
  45. package/src/annotations/resolve-range.ts +117 -0
  46. package/src/annotations/resolve-refline.ts +157 -0
  47. package/src/annotations/resolve-text.ts +539 -0
  48. package/src/annotations/rich-text.ts +65 -0
  49. package/src/annotations/thinning.ts +190 -0
  50. package/src/barlist/__tests__/compile-barlist.test.ts +200 -0
  51. package/src/barlist/compile-barlist.ts +391 -0
  52. package/src/barlist/types.ts +28 -0
  53. package/src/charts/__tests__/post-process.test.ts +237 -0
  54. package/src/charts/__tests__/registry.test.ts +116 -0
  55. package/src/charts/__tests__/utils.test.ts +195 -0
  56. package/src/charts/_shared/__tests__/density-filter.test.ts +32 -0
  57. package/src/charts/_shared/density-filter.ts +26 -0
  58. package/src/charts/_shared/format-label-value.ts +16 -0
  59. package/src/charts/bar/__tests__/compute.test.ts +934 -0
  60. package/src/charts/bar/__tests__/gradient-orient.test.ts +127 -0
  61. package/src/charts/bar/__tests__/labels.test.ts +292 -0
  62. package/src/charts/bar/compute.ts +539 -0
  63. package/src/charts/bar/index.ts +60 -0
  64. package/src/charts/bar/labels.ts +311 -0
  65. package/src/charts/beeswarm/__tests__/compute.test.ts +280 -0
  66. package/src/charts/beeswarm/__tests__/dodge.test.ts +148 -0
  67. package/src/charts/beeswarm/compute.ts +203 -0
  68. package/src/charts/beeswarm/dodge.ts +155 -0
  69. package/src/charts/beeswarm/index.ts +32 -0
  70. package/src/charts/builtin.ts +75 -0
  71. package/src/charts/calendar/__tests__/compute.test.ts +417 -0
  72. package/src/charts/calendar/compute.ts +319 -0
  73. package/src/charts/calendar/index.ts +32 -0
  74. package/src/charts/column/__tests__/compute.test.ts +540 -0
  75. package/src/charts/column/__tests__/labels.test.ts +179 -0
  76. package/src/charts/column/compute.ts +493 -0
  77. package/src/charts/column/index.ts +53 -0
  78. package/src/charts/column/labels.ts +229 -0
  79. package/src/charts/dot/__tests__/compute.test.ts +380 -0
  80. package/src/charts/dot/__tests__/labels.test.ts +98 -0
  81. package/src/charts/dot/compute.ts +285 -0
  82. package/src/charts/dot/index.ts +62 -0
  83. package/src/charts/dot/labels.ts +121 -0
  84. package/src/charts/line/__tests__/compute.test.ts +1194 -0
  85. package/src/charts/line/__tests__/curves.test.ts +51 -0
  86. package/src/charts/line/__tests__/labels.test.ts +94 -0
  87. package/src/charts/line/__tests__/mark-options.test.ts +175 -0
  88. package/src/charts/line/area.ts +484 -0
  89. package/src/charts/line/compute.ts +356 -0
  90. package/src/charts/line/curves.ts +85 -0
  91. package/src/charts/line/index.ts +176 -0
  92. package/src/charts/line/labels.ts +177 -0
  93. package/src/charts/parliament/__tests__/compute.test.ts +411 -0
  94. package/src/charts/parliament/compute.ts +313 -0
  95. package/src/charts/parliament/index.ts +32 -0
  96. package/src/charts/pie/__tests__/compute.test.ts +384 -0
  97. package/src/charts/pie/__tests__/labels.test.ts +132 -0
  98. package/src/charts/pie/compute.ts +324 -0
  99. package/src/charts/pie/index.ts +49 -0
  100. package/src/charts/pie/labels.ts +143 -0
  101. package/src/charts/post-process.ts +229 -0
  102. package/src/charts/range/__tests__/compute.test.ts +486 -0
  103. package/src/charts/range/compute.ts +273 -0
  104. package/src/charts/range/index.ts +82 -0
  105. package/src/charts/range/labels.ts +169 -0
  106. package/src/charts/rect/__tests__/compute.test.ts +120 -0
  107. package/src/charts/rect/index.ts +127 -0
  108. package/src/charts/registry.ts +72 -0
  109. package/src/charts/rule/index.ts +139 -0
  110. package/src/charts/scatter/__tests__/compute.test.ts +488 -0
  111. package/src/charts/scatter/__tests__/trendline.test.ts +191 -0
  112. package/src/charts/scatter/compute.ts +192 -0
  113. package/src/charts/scatter/index.ts +46 -0
  114. package/src/charts/scatter/trendline.ts +100 -0
  115. package/src/charts/text/__tests__/compute.test.ts +307 -0
  116. package/src/charts/text/index.ts +141 -0
  117. package/src/charts/tick/__tests__/compute.test.ts +75 -0
  118. package/src/charts/tick/index.ts +99 -0
  119. package/src/charts/utils.ts +170 -0
  120. package/src/charts/waffle/__tests__/compute.test.ts +305 -0
  121. package/src/charts/waffle/compute.ts +197 -0
  122. package/src/charts/waffle/index.ts +31 -0
  123. package/src/compile/__tests__/color-scale-range.test.ts +158 -0
  124. package/src/compile/__tests__/color-scale-reverse.test.ts +89 -0
  125. package/src/compile/__tests__/data-clip.test.ts +127 -0
  126. package/src/compile/__tests__/fill-patterns.test.ts +154 -0
  127. package/src/compile/__tests__/size-scale.test.ts +108 -0
  128. package/src/compile/__tests__/watermark-obstacle.test.ts +93 -0
  129. package/src/compile/color-scale-range.ts +101 -0
  130. package/src/compile/data-clip.ts +48 -0
  131. package/src/compile/fill-patterns.ts +74 -0
  132. package/src/compile/layer.ts +626 -0
  133. package/src/compile/size-scale.ts +141 -0
  134. package/src/compile/spec-sugar.ts +758 -0
  135. package/src/compile/watermark-obstacle.ts +54 -0
  136. package/src/compile/you-draw-it.ts +123 -0
  137. package/src/compile.ts +1450 -0
  138. package/src/compiler/__tests__/a11y-warnings.test.ts +148 -0
  139. package/src/compiler/__tests__/animation.test.ts +177 -0
  140. package/src/compiler/__tests__/compile.test.ts +87 -0
  141. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +19 -0
  142. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +20 -0
  143. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +22 -0
  144. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +19 -0
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +14 -0
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +34 -0
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +22 -0
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +41 -0
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +38 -0
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +28 -0
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +28 -0
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +30 -0
  153. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +29 -0
  154. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +32 -0
  155. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +25 -0
  156. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +19 -0
  157. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +19 -0
  158. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +21 -0
  159. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +23 -0
  160. package/src/compiler/__tests__/keys.test.ts +83 -0
  161. package/src/compiler/__tests__/normalize-highlight.test.ts +103 -0
  162. package/src/compiler/__tests__/normalize.test.ts +399 -0
  163. package/src/compiler/__tests__/sparkline-defaults.test.ts +153 -0
  164. package/src/compiler/__tests__/validate-did-you-mean.test.ts +86 -0
  165. package/src/compiler/__tests__/validate-highlight.test.ts +112 -0
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +89 -0
  167. package/src/compiler/__tests__/validate.test.ts +629 -0
  168. package/src/compiler/__tests__/vl-parity.test.ts +68 -0
  169. package/src/compiler/a11y-warnings.ts +110 -0
  170. package/src/compiler/animation.ts +142 -0
  171. package/src/compiler/index.ts +47 -0
  172. package/src/compiler/keys.ts +55 -0
  173. package/src/compiler/normalize.ts +734 -0
  174. package/src/compiler/sparkline-defaults.ts +138 -0
  175. package/src/compiler/types.ts +241 -0
  176. package/src/compiler/validate.ts +1871 -0
  177. package/src/endpoint-labels/__tests__/compute.test.ts +587 -0
  178. package/src/endpoint-labels/compute.ts +621 -0
  179. package/src/endpoint-labels/constants.ts +54 -0
  180. package/src/endpoint-labels/format.ts +60 -0
  181. package/src/endpoint-labels/predict.ts +139 -0
  182. package/src/format/__tests__/field-format.test.ts +164 -0
  183. package/src/format/field-format.ts +27 -0
  184. package/src/geo/__tests__/compile-map.test.ts +832 -0
  185. package/src/geo/compile-map.ts +1243 -0
  186. package/src/geo/join.ts +115 -0
  187. package/src/geo/projections.ts +45 -0
  188. package/src/geo/types.ts +26 -0
  189. package/src/graphs/__tests__/community.test.ts +228 -0
  190. package/src/graphs/__tests__/compile-graph.test.ts +396 -0
  191. package/src/graphs/__tests__/encoding.test.ts +415 -0
  192. package/src/graphs/community.ts +92 -0
  193. package/src/graphs/compile-graph.ts +329 -0
  194. package/src/graphs/encoding.ts +356 -0
  195. package/src/graphs/types.ts +106 -0
  196. package/src/index.ts +177 -0
  197. package/src/layout/__tests__/metrics.test.ts +97 -0
  198. package/src/layout/__tests__/scales-highlight.test.ts +192 -0
  199. package/src/layout/axes/rotation.ts +152 -0
  200. package/src/layout/axes/thinning.ts +98 -0
  201. package/src/layout/axes/ticks.ts +409 -0
  202. package/src/layout/axes.ts +757 -0
  203. package/src/layout/dimensions.ts +912 -0
  204. package/src/layout/facet.ts +91 -0
  205. package/src/layout/gridlines.ts +84 -0
  206. package/src/layout/metrics.ts +132 -0
  207. package/src/layout/plan.ts +631 -0
  208. package/src/layout/scales.ts +1053 -0
  209. package/src/layout/shared.ts +44 -0
  210. package/src/legend/__tests__/continuous.test.ts +318 -0
  211. package/src/legend/__tests__/redundancy.test.ts +108 -0
  212. package/src/legend/__tests__/size.test.ts +348 -0
  213. package/src/legend/__tests__/suppression.test.ts +382 -0
  214. package/src/legend/compute.ts +747 -0
  215. package/src/legend/continuous.ts +327 -0
  216. package/src/legend/size.ts +407 -0
  217. package/src/legend/suppression.ts +226 -0
  218. package/src/legend/wrap.ts +117 -0
  219. package/src/sankey/__tests__/compile-sankey.test.ts +458 -0
  220. package/src/sankey/__tests__/layout.test.ts +165 -0
  221. package/src/sankey/__tests__/node-label-wrap.test.ts +114 -0
  222. package/src/sankey/__tests__/node-sort.test.ts +45 -0
  223. package/src/sankey/compile-sankey.ts +706 -0
  224. package/src/sankey/layout.ts +184 -0
  225. package/src/sankey/types.ts +41 -0
  226. package/src/tables/__tests__/bar-column.test.ts +147 -0
  227. package/src/tables/__tests__/category-colors.test.ts +230 -0
  228. package/src/tables/__tests__/compile-table.test.ts +236 -0
  229. package/src/tables/__tests__/format-cells.test.ts +143 -0
  230. package/src/tables/__tests__/heatmap.test.ts +148 -0
  231. package/src/tables/__tests__/pagination.test.ts +78 -0
  232. package/src/tables/__tests__/search.test.ts +94 -0
  233. package/src/tables/__tests__/sort.test.ts +107 -0
  234. package/src/tables/__tests__/sparkline.test.ts +122 -0
  235. package/src/tables/bar-column.ts +94 -0
  236. package/src/tables/category-colors.ts +78 -0
  237. package/src/tables/compile-table.ts +427 -0
  238. package/src/tables/format-cells.ts +115 -0
  239. package/src/tables/heatmap.ts +141 -0
  240. package/src/tables/pagination.ts +46 -0
  241. package/src/tables/search.ts +66 -0
  242. package/src/tables/sort.ts +69 -0
  243. package/src/tables/sparkline.ts +113 -0
  244. package/src/tables/utils.ts +16 -0
  245. package/src/tilemap/__tests__/compile-tilemap.test.ts +576 -0
  246. package/src/tilemap/compile-tilemap.ts +755 -0
  247. package/src/tilemap/layout.ts +172 -0
  248. package/src/tilemap/types.ts +33 -0
  249. package/src/tooltips/__tests__/compute.test.ts +582 -0
  250. package/src/tooltips/compute.ts +700 -0
  251. package/src/transforms/__tests__/aggregate.test.ts +159 -0
  252. package/src/transforms/__tests__/bin.test.ts +88 -0
  253. package/src/transforms/__tests__/calculate.test.ts +146 -0
  254. package/src/transforms/__tests__/conditional.test.ts +127 -0
  255. package/src/transforms/__tests__/filter-relative.test.ts +202 -0
  256. package/src/transforms/__tests__/filter.test.ts +59 -0
  257. package/src/transforms/__tests__/fold.test.ts +79 -0
  258. package/src/transforms/__tests__/index.test.ts +93 -0
  259. package/src/transforms/__tests__/predicates.test.ts +193 -0
  260. package/src/transforms/__tests__/timeunit.test.ts +129 -0
  261. package/src/transforms/__tests__/window.test.ts +286 -0
  262. package/src/transforms/aggregate.ts +131 -0
  263. package/src/transforms/bin.ts +87 -0
  264. package/src/transforms/calculate.ts +60 -0
  265. package/src/transforms/conditional.ts +46 -0
  266. package/src/transforms/filter.ts +122 -0
  267. package/src/transforms/fold.ts +49 -0
  268. package/src/transforms/index.ts +60 -0
  269. package/src/transforms/predicates.ts +123 -0
  270. package/src/transforms/timeunit.ts +88 -0
  271. package/src/transforms/window.ts +185 -0
@@ -0,0 +1,539 @@
1
+ /**
2
+ * Bar chart (horizontal) mark computation.
3
+ *
4
+ * Takes a normalized chart spec with resolved scales and produces
5
+ * RectMark[] for rendering horizontal bars. Supports grouped and
6
+ * stacked variants via the color encoding channel.
7
+ */
8
+
9
+ import type {
10
+ ConditionalValueDef,
11
+ DataRow,
12
+ Encoding,
13
+ GradientDef,
14
+ LayoutStrategy,
15
+ LinearGradient,
16
+ MarkAria,
17
+ Rect,
18
+ RectMark,
19
+ } from '@opendata-ai/openchart-core';
20
+ import { isGradientDef, NARROW_VIEWPORT_MAX } from '@opendata-ai/openchart-core';
21
+ import type { ScaleBand, ScaleLinear } from 'd3-scale';
22
+ import { dedupeKeys, serializeKeyValue } from '../../compiler/keys';
23
+ import type { NormalizedChartSpec } from '../../compiler/types';
24
+ import type { ResolvedScales } from '../../layout/scales';
25
+ import { isConditionalValueDef, resolveConditionalValue } from '../../transforms/conditional';
26
+ import { formatLabelValue } from '../_shared/format-label-value';
27
+ import { getColor, getSequentialColor, groupByField } from '../utils';
28
+
29
+ /**
30
+ * Auto-orient a gradient for horizontal bars.
31
+ *
32
+ * If the gradient uses the default top-to-bottom direction (no explicit
33
+ * x1/y1/x2/y2, or the defaults x1:0, y1:0, x2:0, y2:1), rotate it to
34
+ * left-to-right so the gradient follows the bar's data direction.
35
+ *
36
+ * Gradients with explicit non-default coordinates are left unchanged.
37
+ */
38
+ function orientGradientForHorizontalBar(grad: GradientDef): GradientDef {
39
+ if (grad.gradient !== 'linear') return grad;
40
+ const lg = grad as LinearGradient;
41
+ // Only auto-orient if using the default vertical direction.
42
+ // Default is x1:0, y1:0, x2:0, y2:1 (top-to-bottom).
43
+ const isDefaultVertical =
44
+ (lg.x1 === undefined || lg.x1 === 0) &&
45
+ (lg.y1 === undefined || lg.y1 === 0) &&
46
+ (lg.x2 === undefined || lg.x2 === 0) &&
47
+ (lg.y2 === undefined || lg.y2 === 1);
48
+ if (!isDefaultVertical) return grad;
49
+ return { ...lg, x1: 0, y1: 0, x2: 1, y2: 0 };
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Constants
54
+ // ---------------------------------------------------------------------------
55
+
56
+ const MIN_BAR_WIDTH = 1;
57
+
58
+ /**
59
+ * Readable floor (px) for a single grouped-bar thickness. Value labels render at
60
+ * fontSize 10 with ~12px line height; below this a bar is thinner than its own
61
+ * label and the chart reads as stripes (observed on iOS at 375-430px). When
62
+ * grouped sub-bars would fall under this, we reclaim the band scale's reserved
63
+ * inter-category whitespace (step - bandwidth) before letting bars shrink,
64
+ * trading padding for legibility rather than inventing extra height.
65
+ */
66
+ const MIN_GROUPED_BAR_THICKNESS = 8;
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Public API
70
+ // ---------------------------------------------------------------------------
71
+
72
+ /**
73
+ * Compute horizontal bar marks from a normalized chart spec.
74
+ *
75
+ * Y axis uses a band scale for categories. X axis uses a linear scale
76
+ * for values. When a color encoding is present, bars within each category
77
+ * are grouped (subdivided bands) or stacked (cumulative widths).
78
+ */
79
+ export function computeBarMarks(
80
+ spec: NormalizedChartSpec,
81
+ scales: ResolvedScales,
82
+ _chartArea: Rect,
83
+ _strategy: LayoutStrategy,
84
+ containerWidth: number,
85
+ ): RectMark[] {
86
+ const encoding = spec.encoding as Encoding;
87
+ const xChannel = encoding.x;
88
+ const yChannel = encoding.y;
89
+
90
+ if (!xChannel || !yChannel || !scales.x || !scales.y) {
91
+ return [];
92
+ }
93
+
94
+ const yScale = scales.y.scale as ScaleBand<string>;
95
+ const xScale = scales.x.scale as ScaleLinear<number, number>;
96
+
97
+ // Band scale should provide bandwidth
98
+ if (typeof yScale.bandwidth !== 'function') {
99
+ return [];
100
+ }
101
+
102
+ const bandwidth = yScale.bandwidth();
103
+ // Baseline = pixel x where the bar's left edge anchors. When the x-domain
104
+ // includes zero (the common case), this is xScale(0). When the domain
105
+ // excludes zero (explicit non-zero domain or scale.zero: false), xScale(0)
106
+ // would extrapolate outside the plot area and overrun the y-axis labels, so
107
+ // anchor to the domain minimum (the plot-area left edge) instead.
108
+ const xDomain = xScale.domain() as [number, number];
109
+ const xIncludesZero = xDomain[0] <= 0 && xDomain[1] >= 0;
110
+ const baseline = xIncludesZero ? xScale(0) : xScale(xDomain[0]);
111
+ const colorEnc = encoding.color && 'field' in encoding.color ? encoding.color : undefined;
112
+ const conditionalColor =
113
+ encoding.color && isConditionalValueDef(encoding.color)
114
+ ? (encoding.color as ConditionalValueDef)
115
+ : undefined;
116
+ const colorField = colorEnc?.field;
117
+ const isSequentialColor = colorEnc?.type === 'quantitative';
118
+
119
+ let marks: RectMark[];
120
+
121
+ // If no color encoding, or sequential color (value-based gradient), render simple bars
122
+ if (!colorField || isSequentialColor) {
123
+ marks = computeSimpleBars(
124
+ spec.data,
125
+ xChannel.field,
126
+ yChannel.field,
127
+ xScale,
128
+ yScale,
129
+ bandwidth,
130
+ baseline,
131
+ scales,
132
+ isSequentialColor,
133
+ conditionalColor,
134
+ );
135
+ } else {
136
+ // Color encoding present: decide between colored simple bars vs stacked
137
+ const categoryGroups = groupByField(spec.data, yChannel.field);
138
+ const needsStacking = Array.from(categoryGroups.values()).some((rows) => rows.length > 1);
139
+
140
+ if (needsStacking) {
141
+ // stack: undefined/true/'zero'/'normalize'/'center' -> stacked (default); null/false -> grouped
142
+ const stackEnabled = xChannel.stack !== null && xChannel.stack !== false;
143
+
144
+ if (!stackEnabled) {
145
+ marks = computeGroupedBars(
146
+ spec.data,
147
+ xChannel.field,
148
+ yChannel.field,
149
+ colorField,
150
+ xScale,
151
+ yScale,
152
+ bandwidth,
153
+ baseline,
154
+ scales,
155
+ containerWidth,
156
+ );
157
+ } else {
158
+ const stackMode =
159
+ xChannel.stack === 'normalize'
160
+ ? 'normalize'
161
+ : xChannel.stack === 'center'
162
+ ? 'center'
163
+ : 'zero';
164
+
165
+ marks = computeStackedBars(
166
+ spec.data,
167
+ xChannel.field,
168
+ yChannel.field,
169
+ colorField,
170
+ xScale,
171
+ yScale,
172
+ bandwidth,
173
+ baseline,
174
+ scales,
175
+ stackMode,
176
+ );
177
+ }
178
+ } else {
179
+ // Single row per category: render like simple bars but with color from scale
180
+ marks = computeColoredBars(
181
+ spec.data,
182
+ xChannel.field,
183
+ yChannel.field,
184
+ colorField,
185
+ xScale,
186
+ yScale,
187
+ bandwidth,
188
+ baseline,
189
+ scales,
190
+ );
191
+ }
192
+ }
193
+
194
+ // Stamp identity keys for data-update transitions
195
+ const categoryField = yChannel.field;
196
+ stampBarKeys(marks, categoryField, colorField);
197
+
198
+ return applyMarkDefOverrides(marks, spec, bandwidth);
199
+ }
200
+
201
+ /** Stamp stable identity keys on bar marks for data-update transitions. */
202
+ function stampBarKeys(marks: RectMark[], categoryField: string, colorField?: string): void {
203
+ const rawKeys = marks.map((m) => {
204
+ const series = colorField ? String(m.data[colorField] ?? '') : '';
205
+ const cat = serializeKeyValue(m.data[categoryField]);
206
+ return `${series}|${cat}`;
207
+ });
208
+ const keys = dedupeKeys(rawKeys);
209
+ for (let i = 0; i < marks.length; i++) {
210
+ marks[i].key = keys[i];
211
+ }
212
+ }
213
+
214
+ /** Compute stacked horizontal bars with support for zero/normalize/center modes. */
215
+ function computeStackedBars(
216
+ data: DataRow[],
217
+ valueField: string,
218
+ categoryField: string,
219
+ colorField: string,
220
+ xScale: ScaleLinear<number, number>,
221
+ yScale: ScaleBand<string>,
222
+ bandwidth: number,
223
+ _baseline: number,
224
+ scales: ResolvedScales,
225
+ stackMode: 'zero' | 'normalize' | 'center' = 'zero',
226
+ ): RectMark[] {
227
+ const marks: RectMark[] = [];
228
+ const categoryGroups = groupByField(data, categoryField);
229
+
230
+ for (const [category, rows] of categoryGroups) {
231
+ const bandY = yScale(category);
232
+ if (bandY === undefined) continue;
233
+
234
+ // Compute category total for normalize/center modes
235
+ let categoryTotal = 0;
236
+ for (const row of rows) {
237
+ const v = Number(row[valueField] ?? 0);
238
+ if (Number.isFinite(v) && v > 0) categoryTotal += v;
239
+ }
240
+
241
+ // For center mode, offset so the stack is centered around zero
242
+ let cumulativeValue = stackMode === 'center' ? -categoryTotal / 2 : 0;
243
+
244
+ for (const row of rows) {
245
+ const groupKey = String(row[colorField] ?? '');
246
+ const rawValue = Number(row[valueField] ?? 0);
247
+ // Only stack positive values (same approach as stacked columns)
248
+ if (!Number.isFinite(rawValue) || rawValue <= 0) continue;
249
+
250
+ // For normalize mode, scale the value to a fraction of the total
251
+ const value =
252
+ stackMode === 'normalize' && categoryTotal > 0 ? rawValue / categoryTotal : rawValue;
253
+
254
+ const color = getColor(scales, groupKey);
255
+
256
+ const xLeft = xScale(cumulativeValue);
257
+ const xRight = xScale(cumulativeValue + value);
258
+ const barWidth = Math.max(Math.abs(xRight - xLeft), MIN_BAR_WIDTH);
259
+
260
+ const aria: MarkAria = {
261
+ label: `${category}, ${groupKey}: ${formatLabelValue(rawValue)}`,
262
+ };
263
+
264
+ marks.push({
265
+ type: 'rect',
266
+ x: Math.min(xLeft, xRight),
267
+ y: bandY,
268
+ width: barWidth,
269
+ height: bandwidth,
270
+ fill: isGradientDef(color) ? orientGradientForHorizontalBar(color) : color,
271
+ cornerRadius: 0,
272
+ data: row as Record<string, unknown>,
273
+ aria,
274
+ orient: 'horizontal',
275
+ stackGroup: category,
276
+ });
277
+
278
+ cumulativeValue += value;
279
+ }
280
+ }
281
+
282
+ return marks;
283
+ }
284
+
285
+ /** Compute grouped (dodged) horizontal bars -- side-by-side within each category band. */
286
+ function computeGroupedBars(
287
+ data: DataRow[],
288
+ valueField: string,
289
+ categoryField: string,
290
+ colorField: string,
291
+ xScale: ScaleLinear<number, number>,
292
+ yScale: ScaleBand<string>,
293
+ bandwidth: number,
294
+ baseline: number,
295
+ scales: ResolvedScales,
296
+ containerWidth: number,
297
+ ): RectMark[] {
298
+ const marks: RectMark[] = [];
299
+ const categoryGroups = groupByField(data, categoryField);
300
+
301
+ // Build a stable group order from first appearance in data (Map for O(1) lookup)
302
+ const groupIndexMap = new Map<string, number>();
303
+ for (const row of data) {
304
+ const key = String(row[colorField] ?? '');
305
+ if (!groupIndexMap.has(key)) {
306
+ groupIndexMap.set(key, groupIndexMap.size);
307
+ }
308
+ }
309
+ const groupCount = groupIndexMap.size;
310
+ if (groupCount === 0) return marks;
311
+
312
+ // Subdivide the band height by group count with a small gap.
313
+ const gap = Math.min(1, bandwidth * 0.05);
314
+ let groupHeight = bandwidth;
315
+ let subBandHeight = (groupHeight - gap * (groupCount - 1)) / groupCount;
316
+
317
+ // At tight bandwidths sub-bars fall below the readable floor and read as
318
+ // stripes. The band scale reserves whitespace between categories (step -
319
+ // bandwidth); reclaim it by growing the group height toward the full step
320
+ // before letting bars shrink. Bars stay centered in the band so the widened
321
+ // group doesn't touch its neighbors. A one-pixel residual keeps adjacent
322
+ // categories visually separable even at full reclaim.
323
+ //
324
+ // Gated to narrow containers (< NARROW_VIEWPORT_MAX): the fix targets phones
325
+ // where this was observed. Gating on the container width (not the derived plot
326
+ // width) keeps desktop embeds pixel-identical even when a wide container's
327
+ // left gutter shrinks the plot below 500px.
328
+ const step = typeof yScale.step === 'function' ? yScale.step() : bandwidth;
329
+ const maxGroupHeight = Math.max(bandwidth, step - MIN_BAR_WIDTH);
330
+ if (
331
+ containerWidth < NARROW_VIEWPORT_MAX &&
332
+ subBandHeight < MIN_GROUPED_BAR_THICKNESS &&
333
+ maxGroupHeight > bandwidth
334
+ ) {
335
+ const needed = MIN_GROUPED_BAR_THICKNESS * groupCount + gap * (groupCount - 1);
336
+ groupHeight = Math.min(Math.max(groupHeight, needed), maxGroupHeight);
337
+ subBandHeight = (groupHeight - gap * (groupCount - 1)) / groupCount;
338
+ }
339
+ subBandHeight = Math.max(subBandHeight, MIN_BAR_WIDTH);
340
+ // Center the (possibly widened) group within the band.
341
+ const groupOffset = (bandwidth - groupHeight) / 2;
342
+
343
+ for (const [category, rows] of categoryGroups) {
344
+ const bandY = yScale(category);
345
+ if (bandY === undefined) continue;
346
+
347
+ for (const row of rows) {
348
+ const groupKey = String(row[colorField] ?? '');
349
+ const value = Number(row[valueField] ?? 0);
350
+ if (!Number.isFinite(value)) continue;
351
+
352
+ const groupIndex = groupIndexMap.get(groupKey) ?? 0;
353
+ const color = getColor(scales, groupKey);
354
+ const xPos = value >= 0 ? baseline : xScale(value);
355
+ const barWidth = Math.max(Math.abs(xScale(value) - baseline), MIN_BAR_WIDTH);
356
+ const subY = bandY + groupOffset + groupIndex * (subBandHeight + gap);
357
+
358
+ const aria: MarkAria = {
359
+ label: `${category}, ${groupKey}: ${formatLabelValue(value)}`,
360
+ };
361
+
362
+ marks.push({
363
+ type: 'rect',
364
+ x: xPos,
365
+ y: subY,
366
+ width: barWidth,
367
+ height: subBandHeight,
368
+ fill: isGradientDef(color) ? orientGradientForHorizontalBar(color) : color,
369
+ cornerRadius: 2,
370
+ data: row as Record<string, unknown>,
371
+ aria,
372
+ orient: 'horizontal',
373
+ });
374
+ }
375
+ }
376
+
377
+ return marks;
378
+ }
379
+
380
+ /** Compute colored (non-stacked) horizontal bars. Used when color encoding
381
+ * is present but each category has only one row (e.g., diverging charts). */
382
+ function computeColoredBars(
383
+ data: DataRow[],
384
+ valueField: string,
385
+ categoryField: string,
386
+ colorField: string,
387
+ xScale: ScaleLinear<number, number>,
388
+ yScale: ScaleBand<string>,
389
+ bandwidth: number,
390
+ baseline: number,
391
+ scales: ResolvedScales,
392
+ ): RectMark[] {
393
+ const marks: RectMark[] = [];
394
+
395
+ for (const row of data) {
396
+ const category = String(row[categoryField] ?? '');
397
+ const value = Number(row[valueField] ?? 0);
398
+ if (!Number.isFinite(value)) continue;
399
+
400
+ const bandY = yScale(category);
401
+ if (bandY === undefined) continue;
402
+
403
+ const groupKey = String(row[colorField] ?? '');
404
+ const color = getColor(scales, groupKey);
405
+ const xPos = value >= 0 ? baseline : xScale(value);
406
+ const barWidth = Math.max(Math.abs(xScale(value) - baseline), MIN_BAR_WIDTH);
407
+
408
+ const aria: MarkAria = {
409
+ label: `${category}, ${groupKey}: ${formatLabelValue(value)}`,
410
+ };
411
+
412
+ marks.push({
413
+ type: 'rect',
414
+ x: xPos,
415
+ y: bandY,
416
+ width: barWidth,
417
+ height: bandwidth,
418
+ fill: isGradientDef(color) ? orientGradientForHorizontalBar(color) : color,
419
+ cornerRadius: 2,
420
+ data: row as Record<string, unknown>,
421
+ aria,
422
+ orient: 'horizontal',
423
+ });
424
+ }
425
+
426
+ return marks;
427
+ }
428
+
429
+ function applyMarkDefOverrides(
430
+ marks: RectMark[],
431
+ spec: NormalizedChartSpec,
432
+ bandwidth: number,
433
+ ): RectMark[] {
434
+ const { markDef } = spec;
435
+ const fixedSize = markDef.size;
436
+ const crSpec = markDef.cornerRadius;
437
+
438
+ if (fixedSize == null && crSpec == null) return marks;
439
+
440
+ // Identify the rightmost segment per stackGroup (largest `x + width`).
441
+ // Only that segment receives the corner rounding so the seams between
442
+ // stacked segments stay square and flush.
443
+ const rightPerStack = new Map<string, RectMark>();
444
+ for (const mark of marks) {
445
+ if (mark.stackGroup === undefined) continue;
446
+ const current = rightPerStack.get(mark.stackGroup);
447
+ const markRight = mark.x + mark.width;
448
+ if (!current || markRight > current.x + current.width) {
449
+ rightPerStack.set(mark.stackGroup, mark);
450
+ }
451
+ }
452
+
453
+ for (const mark of marks) {
454
+ if (fixedSize != null && mark.stackGroup === undefined) {
455
+ const barHeight = Math.min(fixedSize, bandwidth);
456
+ const offset = (bandwidth - barHeight) / 2;
457
+ mark.y = mark.y + offset;
458
+ mark.height = barHeight;
459
+ }
460
+ const effectiveHeight = mark.height;
461
+ const isStacked = mark.stackGroup !== undefined;
462
+ const isStackRight = isStacked && rightPerStack.get(mark.stackGroup!) === mark;
463
+
464
+ if (isStacked && !isStackRight) continue;
465
+
466
+ if (crSpec === 'pill') {
467
+ mark.cornerRadius = effectiveHeight / 2;
468
+ } else if (typeof crSpec === 'number') {
469
+ mark.cornerRadius = crSpec;
470
+ } else {
471
+ continue;
472
+ }
473
+
474
+ if (isStackRight) {
475
+ mark.cornerRadiusSides = { tl: false, tr: true, br: true, bl: false };
476
+ }
477
+ }
478
+ return marks;
479
+ }
480
+
481
+ /** Compute simple (non-grouped) horizontal bars. */
482
+ function computeSimpleBars(
483
+ data: DataRow[],
484
+ valueField: string,
485
+ categoryField: string,
486
+ xScale: ScaleLinear<number, number>,
487
+ yScale: ScaleBand<string>,
488
+ bandwidth: number,
489
+ baseline: number,
490
+ scales: ResolvedScales,
491
+ sequentialColor = false,
492
+ conditionalColor?: ConditionalValueDef,
493
+ ): RectMark[] {
494
+ const marks: RectMark[] = [];
495
+
496
+ for (const row of data) {
497
+ const category = String(row[categoryField] ?? '');
498
+ const value = Number(row[valueField] ?? 0);
499
+ if (!Number.isFinite(value)) continue;
500
+
501
+ const bandY = yScale(category);
502
+ if (bandY === undefined) continue;
503
+
504
+ let color: string | GradientDef;
505
+ if (conditionalColor) {
506
+ const resolved = resolveConditionalValue(row, conditionalColor);
507
+ if (resolved != null) {
508
+ color = isGradientDef(resolved) ? resolved : String(resolved);
509
+ } else {
510
+ color = getColor(scales, '__default__');
511
+ }
512
+ } else if (sequentialColor) {
513
+ color = getSequentialColor(scales, value);
514
+ } else {
515
+ color = getColor(scales, '__default__');
516
+ }
517
+ const xPos = value >= 0 ? baseline : xScale(value);
518
+ const barWidth = Math.max(Math.abs(xScale(value) - baseline), MIN_BAR_WIDTH);
519
+
520
+ const aria: MarkAria = {
521
+ label: `${category}: ${formatLabelValue(value)}`,
522
+ };
523
+
524
+ marks.push({
525
+ type: 'rect',
526
+ x: xPos,
527
+ y: bandY,
528
+ width: barWidth,
529
+ height: bandwidth,
530
+ fill: isGradientDef(color) ? orientGradientForHorizontalBar(color) : color,
531
+ cornerRadius: 2,
532
+ data: row as Record<string, unknown>,
533
+ aria,
534
+ orient: 'horizontal',
535
+ });
536
+ }
537
+
538
+ return marks;
539
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Bar chart module (horizontal bars).
3
+ *
4
+ * Exports the bar chart renderer and computation functions.
5
+ */
6
+
7
+ import type { Mark } from '@opendata-ai/openchart-core';
8
+ import { resolveFieldFormatter } from '../../format/field-format';
9
+ import type { ChartRenderer } from '../registry';
10
+ import { computeBarMarks } from './compute';
11
+ import { computeBarLabels } from './labels';
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Bar chart renderer
15
+ // ---------------------------------------------------------------------------
16
+
17
+ export const barRenderer: ChartRenderer = (
18
+ spec,
19
+ scales,
20
+ chartArea,
21
+ strategy,
22
+ theme,
23
+ containerWidth,
24
+ ) => {
25
+ const marks = computeBarMarks(spec, scales, chartArea, strategy, containerWidth);
26
+
27
+ // Compute and attach value labels (respects spec.labels.density)
28
+ const valueField =
29
+ spec.encoding?.x && 'field' in spec.encoding.x ? spec.encoding.x.field : undefined;
30
+ const labelFormatter = resolveFieldFormatter({
31
+ surfaceFormat: spec.labels.format,
32
+ channelFormat:
33
+ spec.encoding?.x && 'format' in spec.encoding.x ? spec.encoding.x.format : undefined,
34
+ values: valueField ? spec.data.map((r) => r[valueField]) : [],
35
+ });
36
+ const labels = computeBarLabels(
37
+ marks,
38
+ chartArea,
39
+ spec.labels.density,
40
+ labelFormatter,
41
+ spec.labels.prefix,
42
+ valueField,
43
+ spec.labels.color,
44
+ theme.isDark,
45
+ spec.labels.fontSize,
46
+ spec.labels.suffix,
47
+ );
48
+ for (let i = 0; i < marks.length && i < labels.length; i++) {
49
+ marks[i].label = labels[i];
50
+ }
51
+
52
+ return marks as Mark[];
53
+ };
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Public exports
57
+ // ---------------------------------------------------------------------------
58
+
59
+ export { computeBarMarks } from './compute';
60
+ export { computeBarLabels } from './labels';