@opendata-ai/openchart-engine 8.0.0-rc.2 → 8.0.0-rc.20

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 +140 -2
  2. package/dist/index.js +1403 -210
  3. package/dist/index.js.map +1 -1
  4. package/package.json +3 -4
  5. package/src/__test-fixtures__/specs.ts +0 -182
  6. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +0 -2339
  7. package/src/__tests__/annotation-behavior.test.ts +0 -721
  8. package/src/__tests__/axes.test.ts +0 -1579
  9. package/src/__tests__/compile-animation.test.ts +0 -161
  10. package/src/__tests__/compile-chart.test.ts +0 -1303
  11. package/src/__tests__/compile-footnotes.test.ts +0 -277
  12. package/src/__tests__/compile-layer.test.ts +0 -969
  13. package/src/__tests__/compile-snapshot.test.ts +0 -156
  14. package/src/__tests__/compound-labels.test.ts +0 -147
  15. package/src/__tests__/dimensions.test.ts +0 -918
  16. package/src/__tests__/encoding-sugar.test.ts +0 -390
  17. package/src/__tests__/facet.test.ts +0 -215
  18. package/src/__tests__/helpers/invariants.ts +0 -299
  19. package/src/__tests__/known-bugs.test.ts +0 -566
  20. package/src/__tests__/layout-fuzz.test.ts +0 -358
  21. package/src/__tests__/layout-invariants.test.ts +0 -535
  22. package/src/__tests__/legend.test.ts +0 -721
  23. package/src/__tests__/mark-keys.test.ts +0 -294
  24. package/src/__tests__/ranking-recipes.test.ts +0 -260
  25. package/src/__tests__/rotation.test.ts +0 -83
  26. package/src/__tests__/scales.test.ts +0 -323
  27. package/src/__tests__/series-search.test.ts +0 -92
  28. package/src/__tests__/spec-sugar.test.ts +0 -801
  29. package/src/__tests__/you-draw-it.test.ts +0 -160
  30. package/src/annotations/__tests__/compute.test.ts +0 -1672
  31. package/src/annotations/__tests__/geometry.test.ts +0 -66
  32. package/src/annotations/__tests__/placement-fuzz.test.ts +0 -256
  33. package/src/annotations/__tests__/placement-invariants.test.ts +0 -345
  34. package/src/annotations/__tests__/placement.test.ts +0 -316
  35. package/src/annotations/__tests__/resolve-text.test.ts +0 -788
  36. package/src/annotations/__tests__/rich-text.test.ts +0 -91
  37. package/src/annotations/__tests__/thinning.test.ts +0 -285
  38. package/src/annotations/collisions.ts +0 -326
  39. package/src/annotations/compute.ts +0 -333
  40. package/src/annotations/constants.ts +0 -162
  41. package/src/annotations/geometry.ts +0 -370
  42. package/src/annotations/move.ts +0 -135
  43. package/src/annotations/placement.ts +0 -636
  44. package/src/annotations/position.ts +0 -131
  45. package/src/annotations/resolve-range.ts +0 -117
  46. package/src/annotations/resolve-refline.ts +0 -157
  47. package/src/annotations/resolve-text.ts +0 -539
  48. package/src/annotations/rich-text.ts +0 -65
  49. package/src/annotations/thinning.ts +0 -190
  50. package/src/barlist/__tests__/compile-barlist.test.ts +0 -200
  51. package/src/barlist/compile-barlist.ts +0 -391
  52. package/src/barlist/types.ts +0 -28
  53. package/src/charts/__tests__/post-process.test.ts +0 -237
  54. package/src/charts/__tests__/registry.test.ts +0 -116
  55. package/src/charts/__tests__/utils.test.ts +0 -195
  56. package/src/charts/_shared/__tests__/density-filter.test.ts +0 -32
  57. package/src/charts/_shared/density-filter.ts +0 -26
  58. package/src/charts/_shared/format-label-value.ts +0 -16
  59. package/src/charts/bar/__tests__/compute.test.ts +0 -934
  60. package/src/charts/bar/__tests__/gradient-orient.test.ts +0 -127
  61. package/src/charts/bar/__tests__/labels.test.ts +0 -292
  62. package/src/charts/bar/compute.ts +0 -539
  63. package/src/charts/bar/index.ts +0 -60
  64. package/src/charts/bar/labels.ts +0 -311
  65. package/src/charts/beeswarm/__tests__/compute.test.ts +0 -280
  66. package/src/charts/beeswarm/__tests__/dodge.test.ts +0 -148
  67. package/src/charts/beeswarm/compute.ts +0 -203
  68. package/src/charts/beeswarm/dodge.ts +0 -155
  69. package/src/charts/beeswarm/index.ts +0 -32
  70. package/src/charts/builtin.ts +0 -75
  71. package/src/charts/calendar/__tests__/compute.test.ts +0 -417
  72. package/src/charts/calendar/compute.ts +0 -319
  73. package/src/charts/calendar/index.ts +0 -32
  74. package/src/charts/column/__tests__/compute.test.ts +0 -540
  75. package/src/charts/column/__tests__/labels.test.ts +0 -179
  76. package/src/charts/column/compute.ts +0 -493
  77. package/src/charts/column/index.ts +0 -53
  78. package/src/charts/column/labels.ts +0 -229
  79. package/src/charts/dot/__tests__/compute.test.ts +0 -380
  80. package/src/charts/dot/__tests__/labels.test.ts +0 -98
  81. package/src/charts/dot/compute.ts +0 -285
  82. package/src/charts/dot/index.ts +0 -62
  83. package/src/charts/dot/labels.ts +0 -121
  84. package/src/charts/line/__tests__/compute.test.ts +0 -1194
  85. package/src/charts/line/__tests__/curves.test.ts +0 -51
  86. package/src/charts/line/__tests__/labels.test.ts +0 -94
  87. package/src/charts/line/__tests__/mark-options.test.ts +0 -175
  88. package/src/charts/line/area.ts +0 -484
  89. package/src/charts/line/compute.ts +0 -356
  90. package/src/charts/line/curves.ts +0 -85
  91. package/src/charts/line/index.ts +0 -176
  92. package/src/charts/line/labels.ts +0 -177
  93. package/src/charts/parliament/__tests__/compute.test.ts +0 -411
  94. package/src/charts/parliament/compute.ts +0 -313
  95. package/src/charts/parliament/index.ts +0 -32
  96. package/src/charts/pie/__tests__/compute.test.ts +0 -384
  97. package/src/charts/pie/__tests__/labels.test.ts +0 -132
  98. package/src/charts/pie/compute.ts +0 -324
  99. package/src/charts/pie/index.ts +0 -49
  100. package/src/charts/pie/labels.ts +0 -143
  101. package/src/charts/post-process.ts +0 -229
  102. package/src/charts/range/__tests__/compute.test.ts +0 -486
  103. package/src/charts/range/compute.ts +0 -273
  104. package/src/charts/range/index.ts +0 -82
  105. package/src/charts/range/labels.ts +0 -169
  106. package/src/charts/rect/__tests__/compute.test.ts +0 -120
  107. package/src/charts/rect/index.ts +0 -127
  108. package/src/charts/registry.ts +0 -72
  109. package/src/charts/rule/index.ts +0 -139
  110. package/src/charts/scatter/__tests__/compute.test.ts +0 -488
  111. package/src/charts/scatter/__tests__/trendline.test.ts +0 -191
  112. package/src/charts/scatter/compute.ts +0 -192
  113. package/src/charts/scatter/index.ts +0 -46
  114. package/src/charts/scatter/trendline.ts +0 -100
  115. package/src/charts/text/__tests__/compute.test.ts +0 -307
  116. package/src/charts/text/index.ts +0 -141
  117. package/src/charts/tick/__tests__/compute.test.ts +0 -75
  118. package/src/charts/tick/index.ts +0 -99
  119. package/src/charts/utils.ts +0 -170
  120. package/src/charts/waffle/__tests__/compute.test.ts +0 -305
  121. package/src/charts/waffle/compute.ts +0 -197
  122. package/src/charts/waffle/index.ts +0 -31
  123. package/src/compile/__tests__/color-scale-range.test.ts +0 -158
  124. package/src/compile/__tests__/color-scale-reverse.test.ts +0 -89
  125. package/src/compile/__tests__/data-clip.test.ts +0 -127
  126. package/src/compile/__tests__/fill-patterns.test.ts +0 -154
  127. package/src/compile/__tests__/size-scale.test.ts +0 -108
  128. package/src/compile/__tests__/watermark-obstacle.test.ts +0 -93
  129. package/src/compile/color-scale-range.ts +0 -101
  130. package/src/compile/data-clip.ts +0 -48
  131. package/src/compile/fill-patterns.ts +0 -74
  132. package/src/compile/layer.ts +0 -626
  133. package/src/compile/size-scale.ts +0 -139
  134. package/src/compile/spec-sugar.ts +0 -758
  135. package/src/compile/watermark-obstacle.ts +0 -54
  136. package/src/compile/you-draw-it.ts +0 -123
  137. package/src/compile.ts +0 -1450
  138. package/src/compiler/__tests__/a11y-warnings.test.ts +0 -148
  139. package/src/compiler/__tests__/animation.test.ts +0 -177
  140. package/src/compiler/__tests__/compile.test.ts +0 -87
  141. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +0 -19
  142. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +0 -20
  143. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +0 -22
  144. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +0 -19
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +0 -14
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +0 -34
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +0 -22
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +0 -41
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +0 -38
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +0 -28
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +0 -28
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +0 -30
  153. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +0 -29
  154. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +0 -32
  155. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +0 -25
  156. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +0 -19
  157. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +0 -19
  158. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +0 -21
  159. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +0 -23
  160. package/src/compiler/__tests__/keys.test.ts +0 -83
  161. package/src/compiler/__tests__/normalize-highlight.test.ts +0 -103
  162. package/src/compiler/__tests__/normalize.test.ts +0 -399
  163. package/src/compiler/__tests__/sparkline-defaults.test.ts +0 -153
  164. package/src/compiler/__tests__/validate-did-you-mean.test.ts +0 -86
  165. package/src/compiler/__tests__/validate-highlight.test.ts +0 -112
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +0 -89
  167. package/src/compiler/__tests__/validate.test.ts +0 -629
  168. package/src/compiler/__tests__/vl-parity.test.ts +0 -68
  169. package/src/compiler/a11y-warnings.ts +0 -110
  170. package/src/compiler/animation.ts +0 -142
  171. package/src/compiler/index.ts +0 -47
  172. package/src/compiler/keys.ts +0 -55
  173. package/src/compiler/normalize.ts +0 -733
  174. package/src/compiler/sparkline-defaults.ts +0 -138
  175. package/src/compiler/types.ts +0 -241
  176. package/src/compiler/validate.ts +0 -1810
  177. package/src/endpoint-labels/__tests__/compute.test.ts +0 -587
  178. package/src/endpoint-labels/compute.ts +0 -621
  179. package/src/endpoint-labels/constants.ts +0 -54
  180. package/src/endpoint-labels/format.ts +0 -60
  181. package/src/endpoint-labels/predict.ts +0 -139
  182. package/src/format/__tests__/field-format.test.ts +0 -164
  183. package/src/format/field-format.ts +0 -27
  184. package/src/geo/__tests__/compile-map.test.ts +0 -621
  185. package/src/geo/compile-map.ts +0 -856
  186. package/src/geo/join.ts +0 -115
  187. package/src/geo/projections.ts +0 -45
  188. package/src/geo/types.ts +0 -24
  189. package/src/graphs/__tests__/community.test.ts +0 -228
  190. package/src/graphs/__tests__/compile-graph.test.ts +0 -396
  191. package/src/graphs/__tests__/encoding.test.ts +0 -415
  192. package/src/graphs/community.ts +0 -92
  193. package/src/graphs/compile-graph.ts +0 -329
  194. package/src/graphs/encoding.ts +0 -356
  195. package/src/graphs/types.ts +0 -106
  196. package/src/index.ts +0 -177
  197. package/src/layout/__tests__/metrics.test.ts +0 -97
  198. package/src/layout/__tests__/scales-highlight.test.ts +0 -192
  199. package/src/layout/axes/rotation.ts +0 -152
  200. package/src/layout/axes/thinning.ts +0 -98
  201. package/src/layout/axes/ticks.ts +0 -409
  202. package/src/layout/axes.ts +0 -757
  203. package/src/layout/dimensions.ts +0 -912
  204. package/src/layout/facet.ts +0 -91
  205. package/src/layout/gridlines.ts +0 -84
  206. package/src/layout/metrics.ts +0 -132
  207. package/src/layout/plan.ts +0 -631
  208. package/src/layout/scales.ts +0 -1053
  209. package/src/layout/shared.ts +0 -44
  210. package/src/legend/__tests__/continuous.test.ts +0 -318
  211. package/src/legend/__tests__/redundancy.test.ts +0 -108
  212. package/src/legend/__tests__/size.test.ts +0 -348
  213. package/src/legend/__tests__/suppression.test.ts +0 -382
  214. package/src/legend/compute.ts +0 -747
  215. package/src/legend/continuous.ts +0 -327
  216. package/src/legend/size.ts +0 -407
  217. package/src/legend/suppression.ts +0 -226
  218. package/src/legend/wrap.ts +0 -117
  219. package/src/sankey/__tests__/compile-sankey.test.ts +0 -458
  220. package/src/sankey/__tests__/layout.test.ts +0 -165
  221. package/src/sankey/__tests__/node-label-wrap.test.ts +0 -114
  222. package/src/sankey/__tests__/node-sort.test.ts +0 -45
  223. package/src/sankey/compile-sankey.ts +0 -706
  224. package/src/sankey/layout.ts +0 -184
  225. package/src/sankey/types.ts +0 -41
  226. package/src/tables/__tests__/bar-column.test.ts +0 -147
  227. package/src/tables/__tests__/category-colors.test.ts +0 -230
  228. package/src/tables/__tests__/compile-table.test.ts +0 -236
  229. package/src/tables/__tests__/format-cells.test.ts +0 -143
  230. package/src/tables/__tests__/heatmap.test.ts +0 -148
  231. package/src/tables/__tests__/pagination.test.ts +0 -78
  232. package/src/tables/__tests__/search.test.ts +0 -94
  233. package/src/tables/__tests__/sort.test.ts +0 -107
  234. package/src/tables/__tests__/sparkline.test.ts +0 -122
  235. package/src/tables/bar-column.ts +0 -94
  236. package/src/tables/category-colors.ts +0 -78
  237. package/src/tables/compile-table.ts +0 -427
  238. package/src/tables/format-cells.ts +0 -115
  239. package/src/tables/heatmap.ts +0 -141
  240. package/src/tables/pagination.ts +0 -46
  241. package/src/tables/search.ts +0 -66
  242. package/src/tables/sort.ts +0 -69
  243. package/src/tables/sparkline.ts +0 -113
  244. package/src/tables/utils.ts +0 -16
  245. package/src/tilemap/__tests__/compile-tilemap.test.ts +0 -576
  246. package/src/tilemap/compile-tilemap.ts +0 -755
  247. package/src/tilemap/layout.ts +0 -172
  248. package/src/tilemap/types.ts +0 -33
  249. package/src/tooltips/__tests__/compute.test.ts +0 -582
  250. package/src/tooltips/compute.ts +0 -700
  251. package/src/transforms/__tests__/aggregate.test.ts +0 -159
  252. package/src/transforms/__tests__/bin.test.ts +0 -88
  253. package/src/transforms/__tests__/calculate.test.ts +0 -146
  254. package/src/transforms/__tests__/conditional.test.ts +0 -127
  255. package/src/transforms/__tests__/filter-relative.test.ts +0 -202
  256. package/src/transforms/__tests__/filter.test.ts +0 -59
  257. package/src/transforms/__tests__/fold.test.ts +0 -79
  258. package/src/transforms/__tests__/index.test.ts +0 -93
  259. package/src/transforms/__tests__/predicates.test.ts +0 -193
  260. package/src/transforms/__tests__/timeunit.test.ts +0 -129
  261. package/src/transforms/__tests__/window.test.ts +0 -286
  262. package/src/transforms/aggregate.ts +0 -131
  263. package/src/transforms/bin.ts +0 -87
  264. package/src/transforms/calculate.ts +0 -60
  265. package/src/transforms/conditional.ts +0 -46
  266. package/src/transforms/filter.ts +0 -122
  267. package/src/transforms/fold.ts +0 -49
  268. package/src/transforms/index.ts +0 -60
  269. package/src/transforms/predicates.ts +0 -123
  270. package/src/transforms/timeunit.ts +0 -88
  271. package/src/transforms/window.ts +0 -185
@@ -1,539 +0,0 @@
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
- }
@@ -1,60 +0,0 @@
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';