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

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 (159) hide show
  1. package/dist/index.d.ts +123 -14
  2. package/dist/index.js +16166 -10027
  3. package/dist/index.js.map +1 -1
  4. package/package.json +11 -4
  5. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +170 -56
  6. package/src/__tests__/annotation-behavior.test.ts +721 -0
  7. package/src/__tests__/axes.test.ts +50 -3
  8. package/src/__tests__/compile-chart.test.ts +30 -0
  9. package/src/__tests__/compile-footnotes.test.ts +277 -0
  10. package/src/__tests__/compile-layer.test.ts +120 -1
  11. package/src/__tests__/helpers/invariants.ts +54 -20
  12. package/src/__tests__/known-bugs.test.ts +455 -2
  13. package/src/__tests__/legend.test.ts +69 -4
  14. package/src/__tests__/ranking-recipes.test.ts +260 -0
  15. package/src/__tests__/scales.test.ts +9 -3
  16. package/src/__tests__/series-search.test.ts +92 -0
  17. package/src/__tests__/spec-sugar.test.ts +801 -0
  18. package/src/__tests__/you-draw-it.test.ts +160 -0
  19. package/src/annotations/__tests__/compute.test.ts +207 -92
  20. package/src/annotations/__tests__/geometry.test.ts +66 -0
  21. package/src/annotations/__tests__/resolve-text.test.ts +527 -27
  22. package/src/annotations/__tests__/rich-text.test.ts +91 -0
  23. package/src/annotations/__tests__/thinning.test.ts +148 -0
  24. package/src/annotations/collisions.ts +130 -84
  25. package/src/annotations/compute.ts +83 -85
  26. package/src/annotations/constants.ts +116 -6
  27. package/src/annotations/geometry.ts +222 -77
  28. package/src/annotations/move.ts +135 -0
  29. package/src/annotations/placement.ts +62 -14
  30. package/src/annotations/resolve-range.ts +2 -0
  31. package/src/annotations/resolve-refline.ts +2 -0
  32. package/src/annotations/resolve-text.ts +312 -111
  33. package/src/annotations/rich-text.ts +65 -0
  34. package/src/annotations/thinning.ts +84 -10
  35. package/src/barlist/compile-barlist.ts +16 -6
  36. package/src/charts/_shared/format-label-value.ts +9 -8
  37. package/src/charts/bar/__tests__/compute.test.ts +57 -10
  38. package/src/charts/bar/__tests__/labels.test.ts +5 -4
  39. package/src/charts/bar/compute.ts +2 -6
  40. package/src/charts/bar/index.ts +8 -1
  41. package/src/charts/bar/labels.ts +3 -3
  42. package/src/charts/beeswarm/__tests__/compute.test.ts +280 -0
  43. package/src/charts/beeswarm/__tests__/dodge.test.ts +148 -0
  44. package/src/charts/beeswarm/compute.ts +203 -0
  45. package/src/charts/beeswarm/dodge.ts +155 -0
  46. package/src/charts/beeswarm/index.ts +32 -0
  47. package/src/charts/builtin.ts +12 -1
  48. package/src/charts/calendar/__tests__/compute.test.ts +417 -0
  49. package/src/charts/calendar/compute.ts +319 -0
  50. package/src/charts/calendar/index.ts +32 -0
  51. package/src/charts/column/__tests__/compute.test.ts +21 -7
  52. package/src/charts/column/__tests__/labels.test.ts +76 -1
  53. package/src/charts/column/compute.ts +2 -6
  54. package/src/charts/column/index.ts +10 -2
  55. package/src/charts/column/labels.ts +95 -21
  56. package/src/charts/dot/index.ts +8 -1
  57. package/src/charts/dot/labels.ts +3 -3
  58. package/src/charts/line/__tests__/compute.test.ts +15 -19
  59. package/src/charts/line/area.ts +8 -23
  60. package/src/charts/line/compute.ts +32 -2
  61. package/src/charts/parliament/__tests__/compute.test.ts +411 -0
  62. package/src/charts/parliament/compute.ts +313 -0
  63. package/src/charts/parliament/index.ts +32 -0
  64. package/src/charts/pie/__tests__/compute.test.ts +103 -0
  65. package/src/charts/pie/compute.ts +63 -8
  66. package/src/charts/pie/labels.ts +1 -0
  67. package/src/charts/range/__tests__/compute.test.ts +486 -0
  68. package/src/charts/range/compute.ts +273 -0
  69. package/src/charts/range/index.ts +82 -0
  70. package/src/charts/range/labels.ts +169 -0
  71. package/src/charts/rect/__tests__/compute.test.ts +120 -0
  72. package/src/charts/rect/index.ts +127 -0
  73. package/src/charts/scatter/compute.ts +7 -21
  74. package/src/charts/text/__tests__/compute.test.ts +307 -0
  75. package/src/charts/text/index.ts +44 -7
  76. package/src/charts/tick/__tests__/compute.test.ts +75 -0
  77. package/src/charts/tick/index.ts +7 -4
  78. package/src/charts/utils.ts +5 -3
  79. package/src/charts/waffle/__tests__/compute.test.ts +305 -0
  80. package/src/charts/waffle/compute.ts +197 -0
  81. package/src/charts/waffle/index.ts +31 -0
  82. package/src/compile/__tests__/color-scale-reverse.test.ts +89 -0
  83. package/src/compile/__tests__/data-clip.test.ts +68 -0
  84. package/src/compile/__tests__/fill-patterns.test.ts +154 -0
  85. package/src/compile/__tests__/size-scale.test.ts +108 -0
  86. package/src/compile/color-scale-range.ts +54 -33
  87. package/src/compile/data-clip.ts +21 -6
  88. package/src/compile/fill-patterns.ts +74 -0
  89. package/src/compile/layer.ts +117 -21
  90. package/src/compile/size-scale.ts +139 -0
  91. package/src/compile/spec-sugar.ts +758 -0
  92. package/src/compile/you-draw-it.ts +123 -0
  93. package/src/compile.ts +310 -103
  94. package/src/compiler/__tests__/a11y-warnings.test.ts +148 -0
  95. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +19 -0
  96. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +20 -0
  97. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +22 -0
  98. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +19 -0
  99. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +14 -0
  100. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +34 -0
  101. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +22 -0
  102. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +41 -0
  103. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +38 -0
  104. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +28 -0
  105. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +28 -0
  106. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +30 -0
  107. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +29 -0
  108. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +32 -0
  109. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +25 -0
  110. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +19 -0
  111. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +19 -0
  112. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +21 -0
  113. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +23 -0
  114. package/src/compiler/__tests__/keys.test.ts +3 -9
  115. package/src/compiler/__tests__/normalize.test.ts +65 -1
  116. package/src/compiler/__tests__/validate-did-you-mean.test.ts +86 -0
  117. package/src/compiler/__tests__/validate-near-miss.test.ts +89 -0
  118. package/src/compiler/__tests__/validate.test.ts +156 -0
  119. package/src/compiler/__tests__/vl-parity.test.ts +68 -0
  120. package/src/compiler/a11y-warnings.ts +110 -0
  121. package/src/compiler/keys.ts +5 -4
  122. package/src/compiler/normalize.ts +150 -7
  123. package/src/compiler/types.ts +11 -0
  124. package/src/compiler/validate.ts +664 -18
  125. package/src/endpoint-labels/__tests__/compute.test.ts +88 -0
  126. package/src/endpoint-labels/compute.ts +40 -12
  127. package/src/endpoint-labels/format.ts +45 -15
  128. package/src/endpoint-labels/predict.ts +50 -36
  129. package/src/format/__tests__/field-format.test.ts +164 -0
  130. package/src/format/field-format.ts +27 -0
  131. package/src/geo/__tests__/compile-map.test.ts +621 -0
  132. package/src/geo/compile-map.ts +856 -0
  133. package/src/geo/join.ts +115 -0
  134. package/src/geo/projections.ts +45 -0
  135. package/src/geo/types.ts +24 -0
  136. package/src/graphs/__tests__/compile-graph.test.ts +25 -0
  137. package/src/graphs/compile-graph.ts +27 -18
  138. package/src/index.ts +20 -2
  139. package/src/layout/axes/ticks.ts +59 -10
  140. package/src/layout/axes.ts +35 -6
  141. package/src/layout/dimensions.ts +139 -83
  142. package/src/layout/facet.ts +14 -3
  143. package/src/layout/plan.ts +83 -33
  144. package/src/layout/scales.ts +132 -15
  145. package/src/legend/__tests__/continuous.test.ts +318 -0
  146. package/src/legend/__tests__/size.test.ts +348 -0
  147. package/src/legend/__tests__/suppression.test.ts +17 -1
  148. package/src/legend/compute.ts +119 -13
  149. package/src/legend/continuous.ts +327 -0
  150. package/src/legend/size.ts +407 -0
  151. package/src/legend/suppression.ts +8 -7
  152. package/src/sankey/compile-sankey.ts +31 -19
  153. package/src/tables/format-cells.ts +16 -7
  154. package/src/tilemap/__tests__/compile-tilemap.test.ts +39 -0
  155. package/src/tilemap/compile-tilemap.ts +24 -7
  156. package/src/tooltips/__tests__/compute.test.ts +2 -2
  157. package/src/tooltips/compute.ts +422 -41
  158. package/src/transforms/__tests__/conditional.test.ts +18 -0
  159. package/src/transforms/aggregate.ts +2 -1
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { computeTextBlockBounds, heuristicMeasure } from '../geometry';
3
+ import { parseAnnotationSpans } from '../rich-text';
4
+
5
+ describe('parseAnnotationSpans', () => {
6
+ it('returns a single regular span for plain text', () => {
7
+ expect(parseAnnotationSpans('Inflation cooled')).toEqual([
8
+ { text: 'Inflation cooled', bold: false },
9
+ ]);
10
+ });
11
+
12
+ it('splits a single bold span out of the surrounding text', () => {
13
+ expect(parseAnnotationSpans('Inflation peaked at **8.5%** in June')).toEqual([
14
+ { text: 'Inflation peaked at ', bold: false },
15
+ { text: '8.5%', bold: true },
16
+ { text: ' in June', bold: false },
17
+ ]);
18
+ });
19
+
20
+ it('handles multiple bold spans on one line', () => {
21
+ expect(parseAnnotationSpans('In **California,** ballots arrive by **Nov. 20**')).toEqual([
22
+ { text: 'In ', bold: false },
23
+ { text: 'California,', bold: true },
24
+ { text: ' ballots arrive by ', bold: false },
25
+ { text: 'Nov. 20', bold: true },
26
+ ]);
27
+ });
28
+
29
+ it('bolds a span at the start of the line', () => {
30
+ expect(parseAnnotationSpans('**Feb. 25** peak')).toEqual([
31
+ { text: 'Feb. 25', bold: true },
32
+ { text: ' peak', bold: false },
33
+ ]);
34
+ });
35
+
36
+ it('bolds a span at the end of the line', () => {
37
+ expect(parseAnnotationSpans('Peak on **Feb. 25**')).toEqual([
38
+ { text: 'Peak on ', bold: false },
39
+ { text: 'Feb. 25', bold: true },
40
+ ]);
41
+ });
42
+
43
+ it('renders an unmatched delimiter literally', () => {
44
+ expect(parseAnnotationSpans('Up **50% since 2020')).toEqual([
45
+ { text: 'Up **50% since 2020', bold: false },
46
+ ]);
47
+ });
48
+
49
+ it('renders an empty delimiter pair literally', () => {
50
+ expect(parseAnnotationSpans('Nothing **** here')).toEqual([
51
+ { text: 'Nothing **** here', bold: false },
52
+ ]);
53
+ });
54
+
55
+ it('never returns an empty span list', () => {
56
+ expect(parseAnnotationSpans('')).toEqual([{ text: '', bold: false }]);
57
+ });
58
+ });
59
+
60
+ describe('computeTextBlockBounds with rich text', () => {
61
+ const style = {
62
+ fontSize: 13,
63
+ fontWeight: 400,
64
+ lineHeight: 1.3,
65
+ textAnchor: 'start' as const,
66
+ };
67
+
68
+ it('measures a line with bold spans wider than the same line all-regular', () => {
69
+ const bold = computeTextBlockBounds(0, 20, 'Inflation peaked at **8.5%**', style);
70
+ const plain = computeTextBlockBounds(0, 20, 'Inflation peaked at 8.5%', style);
71
+
72
+ expect(bold.width).toBeGreaterThan(plain.width);
73
+ });
74
+
75
+ it('does not count the ** markers in the measured width', () => {
76
+ // The markers are syntax, not glyphs. A naive raw-string measure would make
77
+ // the bold version wider by four asterisks at weight 400 — this asserts the
78
+ // widening comes from the weight, not the delimiters.
79
+ const withMarkers = computeTextBlockBounds(0, 20, '**8.5%**', style, heuristicMeasure);
80
+ const boldOnly = heuristicMeasure('8.5%', { fontSize: 13, fontWeight: 700 });
81
+
82
+ expect(withMarkers.width).toBeCloseTo(boldOnly, 5);
83
+ });
84
+
85
+ it('measures multi-line rich text by its widest line', () => {
86
+ const bounds = computeTextBlockBounds(0, 20, 'short\n**a much longer bold line**', style);
87
+ const longestAlone = computeTextBlockBounds(0, 20, '**a much longer bold line**', style);
88
+
89
+ expect(bounds.width).toBeCloseTo(longestAlone.width, 5);
90
+ });
91
+ });
@@ -134,4 +134,152 @@ describe('thinAnnotations', () => {
134
134
  expect(result.annotations[1].footnoteIndex).toBeUndefined();
135
135
  expect(result.annotations[2].footnoteIndex).toBe(1);
136
136
  });
137
+
138
+ describe('plot-area containment', () => {
139
+ // Label `y` is the text baseline, so bounds extend upward from it: a label
140
+ // at y=40 with a 12px font spans roughly y=28..44. Keep test baselines far
141
+ // enough from the top edge that a fitting label really does fit.
142
+ const plotArea = { x: 0, y: 0, width: 120, height: 200 };
143
+
144
+ it('demotes a label that overflows the plot even when nothing collides', () => {
145
+ // Stacked at different y, so the two never pairwise-collide. The second
146
+ // runs off the right edge and must still demote.
147
+ const annotations = [
148
+ makeResolved(0, 40, 'Fits'),
149
+ makeResolved(60, 120, 'Way too long to fit here'),
150
+ ];
151
+ const specs: Annotation[] = [makeSpec('Fits'), makeSpec('Way too long to fit here')];
152
+ const result = thinAnnotations(annotations, specs, measure, plotArea);
153
+ expect(result.footnotes).toHaveLength(1);
154
+ expect(result.footnotes[0].text).toBe('Way too long to fit here');
155
+ expect(result.annotations[0].footnoteIndex).toBeUndefined();
156
+ expect(result.annotations[1].footnoteIndex).toBe(1);
157
+ });
158
+
159
+ it('keeps a label that fits inside the plot', () => {
160
+ const annotations = [makeResolved(0, 40, 'A'), makeResolved(0, 120, 'B')];
161
+ const specs: Annotation[] = [makeSpec('A'), makeSpec('B')];
162
+ const result = thinAnnotations(annotations, specs, measure, plotArea);
163
+ expect(result.footnotes).toHaveLength(0);
164
+ });
165
+
166
+ it('never demotes a pinned label, even when it overflows', () => {
167
+ const annotations = [
168
+ makeResolved(0, 40, 'Fits'),
169
+ makeResolved(60, 120, 'Way too long to fit here'),
170
+ ];
171
+ const specs: Annotation[] = [
172
+ makeSpec('Fits'),
173
+ makeSpec('Way too long to fit here', { responsive: false }),
174
+ ];
175
+ const result = thinAnnotations(annotations, specs, measure, plotArea);
176
+ expect(result.footnotes).toHaveLength(0);
177
+ expect(result.annotations[1].footnoteIndex).toBeUndefined();
178
+ });
179
+
180
+ it('applies no containment constraint when plotArea is omitted', () => {
181
+ const annotations = [
182
+ makeResolved(0, 40, 'Fits'),
183
+ makeResolved(60, 120, 'Way too long to fit here'),
184
+ ];
185
+ const specs: Annotation[] = [makeSpec('Fits'), makeSpec('Way too long to fit here')];
186
+ const result = thinAnnotations(annotations, specs, measure);
187
+ expect(result.footnotes).toHaveLength(0);
188
+ });
189
+
190
+ // A callout above a peak or below a trough lands in the margin, outside the
191
+ // plot but inside the chart. Annotations render outside the clip path, so
192
+ // that is legal placement and must stay inline. Fencing containment to the
193
+ // plot demoted ordinary callouts to footnotes.
194
+ //
195
+ // The plot is inset inside the chart here (a real top margin exists), so
196
+ // "above the plot" and "outside the chart" are genuinely different regions.
197
+ // Roomy enough that the coverage budget stays out of the way — containment
198
+ // is what's under test here.
199
+ const insetPlot = { x: 40, y: 60, width: 700, height: 400 };
200
+ const chart = { x: 0, y: 0, width: 780, height: 520 };
201
+
202
+ it('keeps a label sitting in the margin above the plot', () => {
203
+ // Baseline y=30: bounds span roughly y=18..34, above insetPlot.y (60) but
204
+ // well inside the chart. Fenced to the plot this demotes; fenced to the
205
+ // chart it stays inline.
206
+ const annotations = [makeResolved(50, 120, 'Inside'), makeResolved(50, 30, 'Above the peak')];
207
+ const specs: Annotation[] = [makeSpec('Inside'), makeSpec('Above the peak')];
208
+
209
+ const result = thinAnnotations(annotations, specs, measure, insetPlot, chart);
210
+
211
+ expect(result.footnotes).toHaveLength(0);
212
+ expect(result.annotations[1].footnoteIndex).toBeUndefined();
213
+ });
214
+
215
+ it('still demotes a label that escapes the chart entirely', () => {
216
+ // x=740 in a 780-wide chart: the text runs past the right edge.
217
+ const annotations = [
218
+ makeResolved(50, 120, 'Inside'),
219
+ makeResolved(740, 120, 'Off the right edge of the chart'),
220
+ ];
221
+ const specs: Annotation[] = [makeSpec('Inside'), makeSpec('Off the right edge of the chart')];
222
+
223
+ const result = thinAnnotations(annotations, specs, measure, insetPlot, chart);
224
+
225
+ expect(result.footnotes).toHaveLength(1);
226
+ expect(result.annotations[1].footnoteIndex).toBe(1);
227
+ });
228
+ });
229
+
230
+ describe('coverage budget', () => {
231
+ // Four labels, each well clear of the others and of the plot edges, so
232
+ // neither the overlap test nor the containment test fires. Only the
233
+ // coverage budget can demote here — which is the point: at narrow widths
234
+ // collision resolution spreads labels out and clamping tucks them back in,
235
+ // leaving a crowded-but-legal layout that the other two rules cannot see.
236
+ // Editorial-length copy, not toy strings: label area is what the budget
237
+ // meters, and real callouts ("Recovery begins") are several times wider
238
+ // than a five-letter placeholder.
239
+ const TEXTS = ['Recovery begins', 'Strong rebound', 'Record territory', 'Pandemic low'];
240
+ const spread = () => TEXTS.map((t, i) => makeResolved(5, 20 + i * 40, t));
241
+ const specs: Annotation[] = TEXTS.map((t) => makeSpec(t));
242
+
243
+ it('demotes the crowded tail once labels exceed the budget on a small plot', () => {
244
+ const annotations = spread();
245
+ const plotArea = { x: 0, y: 0, width: 160, height: 160 };
246
+ const result = thinAnnotations(annotations, specs, measure, plotArea);
247
+
248
+ // Nothing collides and everything is inside the plot, so a demotion here
249
+ // is attributable to the budget alone.
250
+ expect(result.footnotes.length).toBeGreaterThan(0);
251
+
252
+ // Priority ties fall back to spec order, so the tail demotes and the head
253
+ // stays inline.
254
+ expect(result.annotations[0].footnoteIndex).toBeUndefined();
255
+ expect(result.annotations[3].footnoteIndex).toBeDefined();
256
+ });
257
+
258
+ it('leaves every label inline when the plot has room', () => {
259
+ const annotations = spread();
260
+ const plotArea = { x: 0, y: 0, width: 900, height: 500 };
261
+ const result = thinAnnotations(annotations, specs, measure, plotArea);
262
+ expect(result.footnotes).toHaveLength(0);
263
+ });
264
+
265
+ it('does not let a pinned label consume the budget and evict candidates', () => {
266
+ // The pinned label is enormous — on its own it would blow the budget. It
267
+ // must not be charged against it, or the candidate that easily fits gets
268
+ // demoted in its place.
269
+ const annotations = [
270
+ makeResolved(5, 20, 'A pinned label that is extremely long and wide'),
271
+ makeResolved(5, 120, 'Tiny'),
272
+ ];
273
+ const pinnedSpecs: Annotation[] = [
274
+ makeSpec('A pinned label that is extremely long and wide', { responsive: false }),
275
+ makeSpec('Tiny'),
276
+ ];
277
+ const plotArea = { x: 0, y: 0, width: 400, height: 200 };
278
+ const result = thinAnnotations(annotations, pinnedSpecs, measure, plotArea);
279
+
280
+ expect(result.annotations[0].footnoteIndex).toBeUndefined();
281
+ expect(result.annotations[1].footnoteIndex).toBeUndefined();
282
+ expect(result.footnotes).toHaveLength(0);
283
+ });
284
+ });
137
285
  });
@@ -3,22 +3,14 @@
3
3
  * resolving annotation-to-annotation overlaps, and clamping to SVG bounds.
4
4
  */
5
5
 
6
- import type {
7
- Rect,
8
- ResolvedAnnotation,
9
- ResolvedLabel,
10
- TextAnnotation,
11
- } from '@opendata-ai/openchart-core';
6
+ import type { Rect, ResolvedAnnotation, TextAnnotation } from '@opendata-ai/openchart-core';
12
7
  import { detectCollision } from '@opendata-ai/openchart-core';
13
8
  import type { NormalizedChartSpec } from '../compiler/types';
14
9
  import type { ResolvedScales } from '../layout/scales';
15
- import { CLAMP_MARGIN, NUDGE_PADDING } from './constants';
16
- import {
17
- type AnnotationMeasureTextFn,
18
- estimateLabelBounds,
19
- heuristicMeasure,
20
- recomputeConnector,
21
- } from './geometry';
10
+ import { CLAMP_MARGIN, DEFAULT_ANNOTATION_FONT_SIZE, NUDGE_PADDING } from './constants';
11
+ import { type AnnotationMeasureTextFn, heuristicMeasure } from './geometry';
12
+ import { annotationBlockBounds, moveAnnotationBy } from './move';
13
+ import { isAutoPlacement } from './placement';
22
14
  import { resolvePosition } from './position';
23
15
 
24
16
  /**
@@ -55,6 +47,31 @@ export function generateNudgeCandidates(
55
47
  return candidates;
56
48
  }
57
49
 
50
+ /**
51
+ * Did the author hand-place this block?
52
+ *
53
+ * A hand-placed block goes exactly where it was put, and the automatic passes keep
54
+ * their hands off it. Without that, the obstacle pass overrides the author: on a line
55
+ * chart the polyline is one long obstacle, so `dy: -10` moved a block by ZERO pixels
56
+ * while `dy: -15` teleported it 56px. Same knob, no monotonicity -- unaimable.
57
+ *
58
+ * `isAutoPlacement` is the ONLY definition of "did the author place this". It already
59
+ * decides which resolve path an annotation takes, and a non-zero `offset` disqualifies
60
+ * the scored search there, so an offset ALWAYS means hand-placed -- with or without an
61
+ * `anchor`. A second, subtly different rule here (an earlier version of this function
62
+ * additionally demanded an `anchor`) does not create a second tier of annotation; it
63
+ * just disagrees with the function that actually routed the thing, and the disagreement
64
+ * shows up as an un-aimable offset on exactly the annotations the extra condition
65
+ * excluded.
66
+ *
67
+ * `offset: { dx: 0 }` is not an instruction, just the default spelled out, so it does
68
+ * not count -- matching `applyOffset`, which is likewise a no-op for it.
69
+ */
70
+ function hasExplicitOffset(annotation: TextAnnotation): boolean {
71
+ const moved = (annotation.offset?.dx ?? 0) !== 0 || (annotation.offset?.dy ?? 0) !== 0;
72
+ return moved && !isAutoPlacement(annotation);
73
+ }
74
+
58
75
  /**
59
76
  * Try to reposition a text annotation to avoid overlapping with obstacle rects
60
77
  * (legend bounds, etc.). First tries standard anchor alternatives, then
@@ -70,33 +87,56 @@ export function nudgeAnnotationFromObstacles(
70
87
  ): boolean {
71
88
  if (annotation.type !== 'text' || !annotation.label) return false;
72
89
 
73
- const labelBounds = estimateLabelBounds(annotation.label, measure);
90
+ // An `offset` is the author stating where the block goes. Auto-avoidance is for
91
+ // annotations that didn't say. Nudging one anyway makes the offset behave like a
92
+ // suggestion the engine is free to ignore: on a line chart the polyline is one
93
+ // long obstacle, so `dy: -10` moved a right-anchored block by *zero* pixels and
94
+ // `dy: -15` teleported it 56px. Same knob, no monotonicity -- unauthorable.
95
+ if (hasExplicitOffset(originalAnnotation)) return false;
96
+
97
+ const label = annotation.label;
98
+ const bounds = annotation.bounds ?? annotationBlockBounds(annotation, label, measure);
74
99
  const collidingObs = obstacles.filter(
75
- (obs) => obs.width > 0 && obs.height > 0 && detectCollision(labelBounds, obs),
100
+ (obs) => obs.width > 0 && obs.height > 0 && detectCollision(bounds, obs),
76
101
  );
77
102
 
78
103
  if (collidingObs.length === 0) return false;
79
104
 
80
- // Resolve the data point pixel position for offset calculations
81
- const px = resolvePosition(originalAnnotation.x, scales.x);
82
- const py = resolvePosition(originalAnnotation.y, scales.y);
83
- if (px === null || py === null) return false;
105
+ // A guard, not an input: the nudge geometry below comes from `bounds` and
106
+ // `connector.endpoint`, not from the data point. But an annotation whose
107
+ // position no longer resolves has nothing to anchor a connector to, so refuse
108
+ // to move it rather than shift a label away from a point we can't locate.
109
+ if (
110
+ resolvePosition(originalAnnotation.x, scales.x) === null ||
111
+ resolvePosition(originalAnnotation.y, scales.y) === null
112
+ ) {
113
+ return false;
114
+ }
84
115
 
85
- const candidates = generateNudgeCandidates(labelBounds, collidingObs, NUDGE_PADDING);
86
- const fontSize = labelBounds.height / Math.max(1, annotation.label.text.split('\n').length);
116
+ const candidates = generateNudgeCandidates(bounds, collidingObs, NUDGE_PADDING);
117
+ // Read the size off the label, don't back-derive it from the box: `bounds` is
118
+ // the label ∪ subtitle union, so dividing its height by the *primary* line
119
+ // count returns roughly double the real size on a subtitled annotation, which
120
+ // silently doubles the margin slop below.
121
+ const fontSize = label.style.fontSize ?? DEFAULT_ANNOTATION_FONT_SIZE;
122
+
123
+ // A drop-line is a vertical rule running DOWN from the block to the point. Nudge
124
+ // the block below its own endpoint and the line inverts: it points up, away from
125
+ // the data, and the block covers the mark it was labelling. The resolver already
126
+ // placed it (side auto-flip, clamp against the chart top), so the only nudges
127
+ // worth taking are ones that keep it overhead.
128
+ const dropLineEndpointY =
129
+ label.connector?.style === 'drop-line' ? label.connector.endpoint?.y : undefined;
87
130
 
88
131
  for (const { dx, dy } of candidates) {
89
- const newLabelX = annotation.label.x + dx;
90
- const newLabelY = annotation.label.y + dy;
91
-
92
- const candidateLabel: ResolvedLabel = {
93
- ...annotation.label,
94
- x: newLabelX,
95
- y: newLabelY,
96
- connector: recomputeConnector({ ...annotation.label, x: newLabelX, y: newLabelY }, px, py),
97
- };
132
+ const candidateBounds: Rect = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
98
133
 
99
- const candidateBounds = estimateLabelBounds(candidateLabel, measure);
134
+ if (
135
+ dropLineEndpointY !== undefined &&
136
+ candidateBounds.y + candidateBounds.height > dropLineEndpointY
137
+ ) {
138
+ continue;
139
+ }
100
140
 
101
141
  // Check no collisions with any obstacle
102
142
  const stillCollides = obstacles.some(
@@ -119,8 +159,7 @@ export function nudgeAnnotationFromObstacles(
119
159
  labelCenterY <= chartArea.y + chartArea.height + fontSize * 3;
120
160
 
121
161
  if (inBounds) {
122
- annotation.label = candidateLabel;
123
- annotation.label.bounds = candidateBounds;
162
+ moveAnnotationBy(annotation, label, dx, dy, measure);
124
163
  return true;
125
164
  }
126
165
  }
@@ -134,7 +173,7 @@ export function nudgeAnnotationFromObstacles(
134
173
  * Iterates through text annotations in order, building a list of "placed"
135
174
  * bounding rects. When a later annotation overlaps an already-placed one,
136
175
  * it tries offset positions (below, above, left, right) to find a
137
- * non-colliding spot. Recomputes the connector origin after nudging.
176
+ * non-colliding spot. Recomputes the connector after nudging.
138
177
  */
139
178
  export function resolveAnnotationCollisions(
140
179
  annotations: ResolvedAnnotation[],
@@ -142,46 +181,79 @@ export function resolveAnnotationCollisions(
142
181
  scales: ResolvedScales,
143
182
  chartArea: Rect,
144
183
  measure: AnnotationMeasureTextFn = heuristicMeasure,
184
+ /**
185
+ * Predicate on the index into `annotations`: true for an auto-placed entry.
186
+ *
187
+ * The scored placement pass already positioned those to avoid everything, so
188
+ * they must not be nudged again — but they still occupy space, so they stay in
189
+ * `placedBounds` and the explicit annotations avoid them. Callers pass the full
190
+ * annotation list; nobody hand-builds a filtered copy, because a second
191
+ * representation of the list is what breaks `specIndex` lookups.
192
+ */
193
+ isAutoPlaced?: (index: number) => boolean,
145
194
  ): void {
195
+ /** Immovable here: sited by the scored search, or hand-placed by the author. */
196
+ const isPinned = (annotation: ResolvedAnnotation, i: number): boolean => {
197
+ if (isAutoPlaced?.(i)) return true;
198
+ // `annotations` is a filtered view of `originalSpecs` -- an annotation that
199
+ // failed to resolve was dropped -- so index by the stamped spec index, not
200
+ // by position here. Falling back to `i` keeps a hand-built layout working.
201
+ const spec = originalSpecs[annotation.specIndex ?? i];
202
+ return spec?.type === 'text' && hasExplicitOffset(spec);
203
+ };
204
+
205
+ const isText = (a: ResolvedAnnotation) => a.type === 'text' && !!a.label;
206
+
207
+ // Seed with EVERY pinned block before nudging anything.
208
+ //
209
+ // This used to be one forward sweep that pushed a pinned block's bounds when it
210
+ // reached it. That only lets annotations authored *after* a pinned one route
211
+ // around it -- everything earlier was nudged against a `placedBounds` that did not
212
+ // contain it yet, so "the pinned block claims its space" held or failed purely on
213
+ // spec order, and two callouts on the same point printed on top of each other when
214
+ // the pinned one happened to be listed second.
146
215
  const placedBounds: Rect[] = [];
216
+ for (let i = 0; i < annotations.length; i++) {
217
+ const annotation = annotations[i];
218
+ if (!isText(annotation) || !isPinned(annotation, i)) continue;
219
+ placedBounds.push(
220
+ annotation.bounds ?? annotationBlockBounds(annotation, annotation.label!, measure),
221
+ );
222
+ }
147
223
 
148
224
  for (let i = 0; i < annotations.length; i++) {
149
225
  const annotation = annotations[i];
150
- if (annotation.type !== 'text' || !annotation.label) {
151
- continue;
152
- }
226
+ if (!isText(annotation) || isPinned(annotation, i)) continue;
153
227
 
154
- const bounds = estimateLabelBounds(annotation.label, measure);
228
+ const label = annotation.label!;
229
+ const bounds = annotation.bounds ?? annotationBlockBounds(annotation, label, measure);
230
+ const originalSpec = originalSpecs[annotation.specIndex ?? i];
155
231
 
156
- // Check against all previously placed annotation labels
232
+ // Check against all previously placed annotation blocks
157
233
  const collidingBounds = placedBounds.filter(
158
234
  (pb) => pb.width > 0 && pb.height > 0 && detectCollision(bounds, pb),
159
235
  );
160
236
 
161
237
  if (collidingBounds.length > 0) {
162
- // Find the original spec to get data point coordinates for connector recomputation
163
- const originalSpec = originalSpecs[i];
164
-
165
238
  if (originalSpec?.type === 'text') {
239
+ // A guard, not an input: same as in nudgeAnnotationFromObstacles, the
240
+ // geometry below comes from `bounds` and `connector.endpoint`. Refuse to
241
+ // move a label whose data point we can no longer locate.
166
242
  const px = resolvePosition(originalSpec.x, scales.x);
167
243
  const py = resolvePosition(originalSpec.y, scales.y);
168
244
 
169
245
  if (px !== null && py !== null) {
170
246
  const candidates = generateNudgeCandidates(bounds, collidingBounds, NUDGE_PADDING);
171
- const fontSize = bounds.height / Math.max(1, annotation.label.text.split('\n').length);
247
+ // Read the size off the label, don't back-derive it from the box: `bounds` is
248
+ // the label ∪ subtitle union, so dividing its height by the *primary* line
249
+ // count returns roughly double the real size on a subtitled annotation, which
250
+ // silently doubles the margin slop below.
251
+ const fontSize = label.style.fontSize ?? DEFAULT_ANNOTATION_FONT_SIZE;
172
252
 
173
253
  for (const { dx, dy } of candidates) {
174
- const newLabelX = annotation.label.x + dx;
175
- const newLabelY = annotation.label.y + dy;
176
-
177
- const candidateLabel: ResolvedLabel = {
178
- ...annotation.label,
179
- x: newLabelX,
180
- y: newLabelY,
181
- };
182
- const candidateBounds = estimateLabelBounds(candidateLabel, measure);
254
+ const candidateBounds: Rect = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
183
255
 
184
- // Check no collisions with any placed label
256
+ // Check no collisions with any placed block
185
257
  const stillCollides = placedBounds.some(
186
258
  (pb) => pb.width > 0 && pb.height > 0 && detectCollision(candidateBounds, pb),
187
259
  );
@@ -197,17 +269,7 @@ export function resolveAnnotationCollisions(
197
269
  labelCenterY <= chartArea.y + chartArea.height + fontSize;
198
270
 
199
271
  if (inBounds) {
200
- annotation.label = {
201
- ...annotation.label,
202
- x: newLabelX,
203
- y: newLabelY,
204
- bounds: candidateBounds,
205
- connector: recomputeConnector(
206
- { ...annotation.label, x: newLabelX, y: newLabelY },
207
- px,
208
- py,
209
- ),
210
- };
272
+ moveAnnotationBy(annotation, label, dx, dy, measure);
211
273
  break;
212
274
  }
213
275
  }
@@ -216,7 +278,7 @@ export function resolveAnnotationCollisions(
216
278
  }
217
279
 
218
280
  // Add this annotation's final bounds to the placed list
219
- placedBounds.push(estimateLabelBounds(annotation.label, measure));
281
+ placedBounds.push(annotation.bounds ?? annotationBlockBounds(annotation, label, measure));
220
282
  }
221
283
  }
222
284
 
@@ -235,7 +297,8 @@ export function clampAnnotationsToBounds(
235
297
  for (const annotation of annotations) {
236
298
  if (annotation.type !== 'text' || !annotation.label) continue;
237
299
 
238
- const bounds = estimateLabelBounds(annotation.label, measure);
300
+ const label = annotation.label;
301
+ const bounds = annotation.bounds ?? annotationBlockBounds(annotation, label, measure);
239
302
  let dx = 0;
240
303
  let dy = 0;
241
304
 
@@ -258,23 +321,6 @@ export function clampAnnotationsToBounds(
258
321
 
259
322
  if (dx === 0 && dy === 0) continue;
260
323
 
261
- const newX = annotation.label.x + dx;
262
- const newY = annotation.label.y + dy;
263
-
264
- const connector = annotation.label.connector;
265
- const newBounds = estimateLabelBounds({ ...annotation.label, x: newX, y: newY }, measure);
266
- annotation.label = {
267
- ...annotation.label,
268
- x: newX,
269
- y: newY,
270
- bounds: newBounds,
271
- connector: connector
272
- ? recomputeConnector(
273
- { ...annotation.label, x: newX, y: newY },
274
- connector.to.x,
275
- connector.to.y,
276
- )
277
- : undefined,
278
- };
324
+ moveAnnotationBy(annotation, label, dx, dy, measure);
279
325
  }
280
326
  }