@opendata-ai/openchart-engine 8.0.0-rc.9 → 8.1.0

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 +175 -12
  2. package/dist/index.js +917 -168
  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 -2401
  7. package/src/__tests__/annotation-behavior.test.ts +0 -852
  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 -376
  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 -545
  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 -630
  133. package/src/compile/size-scale.ts +0 -141
  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 -1503
  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 -170
  165. package/src/compiler/__tests__/validate-highlight.test.ts +0 -112
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +0 -251
  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 -734
  174. package/src/compiler/sparkline-defaults.ts +0 -138
  175. package/src/compiler/types.ts +0 -241
  176. package/src/compiler/validate.ts +0 -2041
  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 -1128
  185. package/src/geo/compile-map.ts +0 -1376
  186. package/src/geo/join.ts +0 -115
  187. package/src/geo/projections.ts +0 -65
  188. package/src/geo/types.ts +0 -26
  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 -748
  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,636 +0,0 @@
1
- /**
2
- * Annotation placement engine: typed obstacles, candidate generation,
3
- * scored search, and two-pass deterministic placement.
4
- */
5
-
6
- import { overlapArea, type Rect } from '@opendata-ai/openchart-core';
7
- import { ANCHOR_OFFSET, subtitleBaselineY } from './constants';
8
- import {
9
- type AnnotationMeasureTextFn,
10
- computeTextBlockBounds,
11
- heuristicMeasure,
12
- unionRects,
13
- } from './geometry';
14
-
15
- export type ObstacleKind =
16
- | 'mark'
17
- | 'line'
18
- | 'area-fill'
19
- | 'legend'
20
- | 'data-label'
21
- | 'endpoint-label'
22
- | 'watermark'
23
- | 'axis-band'
24
- | 'annotation';
25
-
26
- export interface PlacementObstacle extends Rect {
27
- kind: ObstacleKind;
28
- }
29
-
30
- /**
31
- * Sample a polyline into bucket-based obstacle rects. Each bucket spans a
32
- * fixed x-width and covers the min/max y of the line within that bucket,
33
- * padded vertically. Interpolates segment y-values at bucket edges so steep
34
- * segments produce gap-free coverage.
35
- */
36
- function lerpY(p0: { x: number; y: number }, p1: { x: number; y: number }, x: number): number {
37
- const dx = p1.x - p0.x;
38
- if (Math.abs(dx) < 1e-9) return (p0.y + p1.y) / 2;
39
- const t = (x - p0.x) / dx;
40
- return p0.y + t * (p1.y - p0.y);
41
- }
42
-
43
- function fillBucketsFromSegments(
44
- points: Array<{ x: number; y: number }>,
45
- buckets: Array<{ minY: number; maxY: number }>,
46
- xMin: number,
47
- bucketWidth: number,
48
- ): void {
49
- const bucketCount = buckets.length;
50
-
51
- function updateBucket(b: number, y: number): void {
52
- if (b < 0 || b >= bucketCount) return;
53
- if (y < buckets[b].minY) buckets[b].minY = y;
54
- if (y > buckets[b].maxY) buckets[b].maxY = y;
55
- }
56
-
57
- for (let i = 0; i < points.length - 1; i++) {
58
- const p0 = points[i];
59
- const p1 = points[i + 1];
60
- const segXMin = Math.min(p0.x, p1.x);
61
- const segXMax = Math.max(p0.x, p1.x);
62
- const bStart = Math.max(0, Math.floor((segXMin - xMin) / bucketWidth));
63
- const bEnd = Math.min(bucketCount - 1, Math.floor((segXMax - xMin) / bucketWidth));
64
- for (let b = bStart; b <= bEnd; b++) {
65
- const bx0 = xMin + b * bucketWidth;
66
- const bx1 = xMin + (b + 1) * bucketWidth;
67
- updateBucket(b, lerpY(p0, p1, Math.max(bx0, segXMin)));
68
- updateBucket(b, lerpY(p0, p1, Math.min(bx1, segXMax)));
69
- }
70
- }
71
-
72
- for (const p of points) {
73
- const b = Math.min(Math.floor((p.x - xMin) / bucketWidth), bucketCount - 1);
74
- updateBucket(b, p.y);
75
- }
76
- }
77
-
78
- export function samplePolylineObstacles(
79
- points: Array<{ x: number; y: number }>,
80
- kind: 'line' | 'area-fill' = 'line',
81
- bucketWidth = 24,
82
- pad = 3,
83
- ): PlacementObstacle[] {
84
- if (points.length === 0) return [];
85
-
86
- if (points.length === 1) {
87
- const p = points[0];
88
- return [
89
- {
90
- x: p.x - pad,
91
- y: p.y - pad,
92
- width: pad * 2,
93
- height: pad * 2,
94
- kind,
95
- },
96
- ];
97
- }
98
-
99
- let xMin = Infinity;
100
- let xMax = -Infinity;
101
- for (const p of points) {
102
- if (p.x < xMin) xMin = p.x;
103
- if (p.x > xMax) xMax = p.x;
104
- }
105
-
106
- const span = xMax - xMin;
107
- if (span <= 0) {
108
- // All points at same x: single vertical rect
109
- let yMin = Infinity;
110
- let yMax = -Infinity;
111
- for (const p of points) {
112
- if (p.y < yMin) yMin = p.y;
113
- if (p.y > yMax) yMax = p.y;
114
- }
115
- return [
116
- {
117
- x: xMin - pad,
118
- y: yMin - pad,
119
- width: pad * 2,
120
- height: yMax - yMin + pad * 2,
121
- kind,
122
- },
123
- ];
124
- }
125
-
126
- const bucketCount = Math.ceil(span / bucketWidth);
127
- const buckets: Array<{ minY: number; maxY: number }> = [];
128
- for (let i = 0; i < bucketCount; i++) {
129
- buckets.push({ minY: Infinity, maxY: -Infinity });
130
- }
131
-
132
- fillBucketsFromSegments(points, buckets, xMin, bucketWidth);
133
-
134
- const obstacles: PlacementObstacle[] = [];
135
- for (let b = 0; b < bucketCount; b++) {
136
- const bucket = buckets[b];
137
- if (bucket.minY === Infinity) continue;
138
- obstacles.push({
139
- x: xMin + b * bucketWidth,
140
- y: bucket.minY - pad,
141
- width: bucketWidth,
142
- height: bucket.maxY - bucket.minY + pad * 2,
143
- kind,
144
- });
145
- }
146
-
147
- return obstacles;
148
- }
149
-
150
- /**
151
- * Sample an area mark's fill region into bucket-based obstacles. The top
152
- * boundary produces 'line' obstacles (hard), and the fill between top and
153
- * bottom produces 'area-fill' obstacles (soft).
154
- */
155
- export function sampleAreaObstacles(
156
- topPoints: Array<{ x: number; y: number }>,
157
- bottomPoints: Array<{ x: number; y: number }>,
158
- bucketWidth = 24,
159
- pad = 3,
160
- ): PlacementObstacle[] {
161
- const lineObs = samplePolylineObstacles(topPoints, 'line', bucketWidth, pad);
162
-
163
- // For the fill region, sample both top and bottom boundaries and create
164
- // fill obstacles spanning from the top boundary down to the bottom boundary
165
- // within each bucket.
166
- if (topPoints.length < 2 || bottomPoints.length < 2) return lineObs;
167
-
168
- let xMin = Infinity;
169
- let xMax = -Infinity;
170
- for (const p of topPoints) {
171
- if (p.x < xMin) xMin = p.x;
172
- if (p.x > xMax) xMax = p.x;
173
- }
174
-
175
- const span = xMax - xMin;
176
- if (span <= 0) return lineObs;
177
-
178
- const bucketCount = Math.ceil(span / bucketWidth);
179
- const topBuckets: Array<{ minY: number; maxY: number }> = [];
180
- const bottomBuckets: Array<{ minY: number; maxY: number }> = [];
181
- for (let i = 0; i < bucketCount; i++) {
182
- topBuckets.push({ minY: Infinity, maxY: -Infinity });
183
- bottomBuckets.push({ minY: Infinity, maxY: -Infinity });
184
- }
185
-
186
- fillBucketsFromSegments(topPoints, topBuckets, xMin, bucketWidth);
187
- fillBucketsFromSegments(bottomPoints, bottomBuckets, xMin, bucketWidth);
188
-
189
- const fillObs: PlacementObstacle[] = [];
190
- for (let b = 0; b < bucketCount; b++) {
191
- const top = topBuckets[b];
192
- const bottom = bottomBuckets[b];
193
- if (top.minY === Infinity || bottom.minY === Infinity) continue;
194
-
195
- const fillTop = Math.min(top.minY, top.maxY);
196
- const fillBottom = Math.max(bottom.minY, bottom.maxY);
197
- if (fillBottom <= fillTop) continue;
198
-
199
- fillObs.push({
200
- x: xMin + b * bucketWidth,
201
- y: fillTop,
202
- width: bucketWidth,
203
- height: fillBottom - fillTop,
204
- kind: 'area-fill',
205
- });
206
- }
207
-
208
- return [...lineObs, ...fillObs];
209
- }
210
-
211
- /** Normalize a plain Rect[] to PlacementObstacle[] with a default kind. */
212
- export function normalizeObstacles(
213
- rects: Rect[],
214
- kind: ObstacleKind = 'mark',
215
- ): PlacementObstacle[] {
216
- return rects.map((r) => ({ ...r, kind }));
217
- }
218
-
219
- // ---------------------------------------------------------------------------
220
- // Scored placement search
221
- // ---------------------------------------------------------------------------
222
-
223
- const OBSTACLE_WEIGHTS: Record<ObstacleKind, number> = {
224
- annotation: 30,
225
- line: 20,
226
- mark: 8,
227
- 'data-label': 8,
228
- 'endpoint-label': 8,
229
- legend: 6,
230
- watermark: 6,
231
- 'axis-band': 6,
232
- 'area-fill': 1.5,
233
- };
234
-
235
- const W_SVG = 50;
236
- const W_CHART = 6;
237
- const W_DIST = 2;
238
- const EPSILON = 0.001;
239
- const CLEAN_THRESHOLD = EPSILON * 16;
240
-
241
- interface DirectionDef {
242
- ux: number;
243
- uy: number;
244
- textAnchor: 'start' | 'end';
245
- attach:
246
- | 'bottom-center'
247
- | 'bottom-left'
248
- | 'left-middle'
249
- | 'top-left'
250
- | 'top-center'
251
- | 'top-right'
252
- | 'right-middle'
253
- | 'bottom-right';
254
- }
255
-
256
- const D = Math.SQRT1_2;
257
-
258
- const DIRECTIONS: DirectionDef[] = [
259
- { ux: 0, uy: -1, textAnchor: 'start', attach: 'bottom-center' }, // N
260
- { ux: D, uy: -D, textAnchor: 'start', attach: 'bottom-left' }, // NE
261
- { ux: 1, uy: 0, textAnchor: 'start', attach: 'left-middle' }, // E
262
- { ux: D, uy: D, textAnchor: 'start', attach: 'top-left' }, // SE
263
- { ux: 0, uy: 1, textAnchor: 'start', attach: 'top-center' }, // S
264
- { ux: -D, uy: D, textAnchor: 'end', attach: 'top-right' }, // SW
265
- { ux: -1, uy: 0, textAnchor: 'end', attach: 'right-middle' }, // W
266
- { ux: -D, uy: -D, textAnchor: 'end', attach: 'bottom-right' }, // NW
267
- ];
268
-
269
- // Preferred direction orderings: away from data vertically, right over left
270
- const LOWER_HALF_ORDER = [1, 0, 7, 2, 3, 4, 5, 6]; // NE, N, NW, E, SE, S, SW, W
271
- const UPPER_HALF_ORDER = [3, 4, 5, 2, 1, 0, 7, 6]; // SE, S, SW, E, NE, N, NW, W
272
-
273
- export interface PlacementCandidate {
274
- labelX: number;
275
- labelY: number;
276
- textAnchor: 'start' | 'end';
277
- box: Rect;
278
- directionIndex: number;
279
- ring: 1 | 2 | 3;
280
- score: number;
281
- candidateIdx: number;
282
- }
283
-
284
- export interface CandidateScoreBreakdown {
285
- direction: string;
286
- ring: 1 | 2 | 3;
287
- box: Rect;
288
- perObstacle: Array<{ kind: ObstacleKind; overlap: number; contribution: number }>;
289
- outsideSvg: number;
290
- outsideChart: number;
291
- distance: number;
292
- tiebreak: number;
293
- total: number;
294
- }
295
-
296
- function computeAttachmentPoint(
297
- anchorX: number,
298
- anchorY: number,
299
- dir: DirectionDef,
300
- radius: number,
301
- ): { x: number; y: number } {
302
- return {
303
- x: anchorX + dir.ux * radius,
304
- y: anchorY + dir.uy * radius,
305
- };
306
- }
307
-
308
- function labelPositionFromAttachment(
309
- attachPt: { x: number; y: number },
310
- dir: DirectionDef,
311
- boxHeight: number,
312
- fontSize: number,
313
- boxWidth: number,
314
- ): { labelX: number; labelY: number } {
315
- const attach = dir.attach;
316
-
317
- // A `*-center` attach means the block straddles the point, so `labelX` (the
318
- // text's start edge, since these directions render textAnchor 'start') has to
319
- // back off by half the block width. Centering the BLOCK is not the same as
320
- // center-aligning the TEXT: the lines inside stay left-aligned and ragged
321
- // right, per the reference voice. Without this the point sits at the block's
322
- // left edge and a "top" anchor reads as "up and to the right".
323
- const centered = attach === 'top-center' || attach === 'bottom-center';
324
- const labelX = centered ? attachPt.x - boxWidth / 2 : attachPt.x;
325
-
326
- let labelY: number;
327
- if (attach === 'left-middle' || attach === 'right-middle') {
328
- labelY = attachPt.y - boxHeight / 2 + fontSize;
329
- } else if (attach === 'top-left' || attach === 'top-center' || attach === 'top-right') {
330
- labelY = attachPt.y + fontSize;
331
- } else {
332
- labelY = attachPt.y - boxHeight + fontSize;
333
- }
334
-
335
- return { labelX, labelY };
336
- }
337
-
338
- function areaOutside(box: Rect, container: Rect): number {
339
- const insideX = Math.max(
340
- 0,
341
- Math.min(box.x + box.width, container.x + container.width) - Math.max(box.x, container.x),
342
- );
343
- const insideY = Math.max(
344
- 0,
345
- Math.min(box.y + box.height, container.y + container.height) - Math.max(box.y, container.y),
346
- );
347
- const insideArea = insideX * insideY;
348
- const boxArea = box.width * box.height;
349
- return Math.max(0, boxArea - insideArea);
350
- }
351
-
352
- function inflateRect(r: Rect, pad: number): Rect {
353
- return {
354
- x: r.x - pad,
355
- y: r.y - pad,
356
- width: r.width + pad * 2,
357
- height: r.height + pad * 2,
358
- };
359
- }
360
-
361
- function scoreCandidate(
362
- box: Rect,
363
- obstacles: Rect[],
364
- svgRect: Rect,
365
- chartArea: Rect,
366
- anchorX: number,
367
- anchorY: number,
368
- chartDiagonal: number,
369
- candidateIndex: number,
370
- debug?: boolean,
371
- ): { score: number; breakdown?: CandidateScoreBreakdown } {
372
- const boxArea = box.width * box.height || 1;
373
- const inflated = inflateRect(box, 3);
374
-
375
- let obstacleScore = 0;
376
- const perObstacle: CandidateScoreBreakdown['perObstacle'] = [];
377
-
378
- for (const obs of obstacles) {
379
- const kind = 'kind' in obs ? (obs as PlacementObstacle).kind : 'mark';
380
- const overlap = overlapArea(inflated, obs);
381
- if (overlap > 0) {
382
- const weight = OBSTACLE_WEIGHTS[kind] ?? 8;
383
- const contribution = (weight * overlap) / boxArea;
384
- obstacleScore += contribution;
385
- if (debug) {
386
- perObstacle.push({ kind, overlap, contribution });
387
- }
388
- }
389
- }
390
-
391
- const outsideSvg = (W_SVG * areaOutside(box, svgRect)) / boxArea;
392
- const outsideChart = (W_CHART * areaOutside(box, chartArea) * 0.3) / boxArea;
393
-
394
- const nearestX = Math.max(box.x, Math.min(anchorX, box.x + box.width));
395
- const nearestY = Math.max(box.y, Math.min(anchorY, box.y + box.height));
396
- const dx = anchorX - nearestX;
397
- const dy = anchorY - nearestY;
398
- const dist = Math.sqrt(dx * dx + dy * dy);
399
- const distance = (W_DIST * dist) / (chartDiagonal || 1);
400
-
401
- const tiebreak = candidateIndex * EPSILON;
402
- const score = obstacleScore + outsideSvg + outsideChart + distance + tiebreak;
403
-
404
- if (debug) {
405
- return {
406
- score,
407
- breakdown: {
408
- direction: '',
409
- ring: 1,
410
- box,
411
- perObstacle,
412
- outsideSvg,
413
- outsideChart,
414
- distance,
415
- tiebreak,
416
- total: score,
417
- },
418
- };
419
- }
420
-
421
- return { score };
422
- }
423
-
424
- export interface PlacementResult {
425
- labelX: number;
426
- labelY: number;
427
- textAnchor: 'start' | 'end';
428
- bounds: Rect;
429
- score: number;
430
- debug?: CandidateScoreBreakdown[];
431
- }
432
-
433
- /**
434
- * Run the scored placement search for a single auto annotation.
435
- * Generates candidates around the anchor point, scores each, returns the best.
436
- */
437
- export function findBestPlacement(
438
- anchorX: number,
439
- anchorY: number,
440
- text: string,
441
- style: { fontSize: number; fontWeight: number; lineHeight: number; fontFamily?: string },
442
- subtitleText: string | undefined,
443
- subtitleStyle:
444
- | { fontSize: number; fontWeight: number; lineHeight: number; fontFamily?: string }
445
- | undefined,
446
- obstacles: Rect[],
447
- chartArea: Rect,
448
- svgRect: Rect,
449
- measure: AnnotationMeasureTextFn = heuristicMeasure,
450
- debug = false,
451
- ): PlacementResult {
452
- const isUpperHalf = anchorY < chartArea.y + chartArea.height / 2;
453
- const dirOrder = isUpperHalf ? UPPER_HALF_ORDER : LOWER_HALF_ORDER;
454
- const chartDiagonal = Math.sqrt(chartArea.width ** 2 + chartArea.height ** 2);
455
-
456
- // Compute box dimensions for candidate generation
457
- const sampleBounds = computeTextBlockBounds(
458
- 0,
459
- style.fontSize,
460
- text,
461
- {
462
- ...style,
463
- textAnchor: 'start',
464
- },
465
- measure,
466
- );
467
- const boxHeight = sampleBounds.height;
468
-
469
- // Centering a `*-center` attach needs the width of the WHOLE block, not just
470
- // the primary line: a subtitle is often the wider of the two, and centering on
471
- // the primary width alone would leave a lede+subtitle stack visibly off-center
472
- // over its point.
473
- const subtitleSampleWidth =
474
- subtitleText && subtitleStyle
475
- ? computeTextBlockBounds(
476
- 0,
477
- subtitleStyle.fontSize,
478
- subtitleText,
479
- { ...subtitleStyle, textAnchor: 'start' },
480
- measure,
481
- ).width
482
- : 0;
483
- const boxWidth = Math.max(sampleBounds.width, subtitleSampleWidth);
484
-
485
- // The innermost ring is the default setback for an auto-placed label, so it's
486
- // the same quantity ANCHOR_OFFSET expresses for the explicit path — keep them
487
- // as one constant. A 12px ring sat inside the standoff + marker-pullback
488
- // overhead, so an auto-placed label's connector was always shorter than
489
- // MIN_CONNECTOR_LENGTH and got suppressed: six bare callouts rendered as
490
- // floating text with no leader back to the data.
491
- const r1 = ANCHOR_OFFSET;
492
- const r2 = r1 + boxHeight + 8;
493
- const r3 = 2 * r2;
494
-
495
- let nextCandidateIdx = 0;
496
-
497
- function generateCandidates(radii: number[]): PlacementCandidate[] {
498
- const candidates: PlacementCandidate[] = [];
499
-
500
- for (const radius of radii) {
501
- const ring = radius === r1 ? 1 : radius === r2 ? 2 : 3;
502
- for (const di of dirOrder) {
503
- const dir = DIRECTIONS[di];
504
- const attachPt = computeAttachmentPoint(anchorX, anchorY, dir, radius);
505
- const { labelX, labelY } = labelPositionFromAttachment(
506
- attachPt,
507
- dir,
508
- boxHeight,
509
- style.fontSize,
510
- boxWidth,
511
- );
512
-
513
- let box = computeTextBlockBounds(
514
- labelX,
515
- labelY,
516
- text,
517
- {
518
- ...style,
519
- textAnchor: dir.textAnchor,
520
- },
521
- measure,
522
- );
523
-
524
- // Union with subtitle bounds if present
525
- if (subtitleText && subtitleStyle) {
526
- // This pass SCORES a candidate subtitle position; the resolver STAMPS the
527
- // one that renders. They must agree, or the scored block height is a lie
528
- // and the bounds other annotations avoid no longer contain the subtitle.
529
- // Hence the shared formula rather than a second copy of the sum.
530
- const subtitleY = subtitleBaselineY(
531
- labelY,
532
- style.fontSize * style.lineHeight,
533
- text.split('\n').length,
534
- );
535
- const subBounds = computeTextBlockBounds(
536
- labelX,
537
- subtitleY,
538
- subtitleText,
539
- {
540
- ...subtitleStyle,
541
- textAnchor: dir.textAnchor,
542
- },
543
- measure,
544
- );
545
- box = unionRects(box, subBounds);
546
- }
547
-
548
- const idx = nextCandidateIdx++;
549
- const { score } = scoreCandidate(
550
- box,
551
- obstacles,
552
- svgRect,
553
- chartArea,
554
- anchorX,
555
- anchorY,
556
- chartDiagonal,
557
- idx,
558
- );
559
-
560
- candidates.push({
561
- labelX,
562
- labelY,
563
- textAnchor: dir.textAnchor,
564
- box,
565
- directionIndex: di,
566
- ring: ring as 1 | 2 | 3,
567
- score,
568
- candidateIdx: idx,
569
- });
570
- }
571
- }
572
-
573
- return candidates;
574
- }
575
-
576
- // Ring 1 + Ring 2 (16 candidates)
577
- let candidates = generateCandidates([r1, r2]);
578
- let best = candidates.reduce((a, b) => (a.score <= b.score ? a : b));
579
-
580
- // Ring 3 if no clean placement found
581
- if (best.score > CLEAN_THRESHOLD) {
582
- const ring3 = generateCandidates([r3]);
583
- candidates = [...candidates, ...ring3];
584
- best = candidates.reduce((a, b) => (a.score <= b.score ? a : b));
585
- }
586
-
587
- let debugBreakdowns: CandidateScoreBreakdown[] | undefined;
588
- if (debug) {
589
- const dirNames = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
590
- debugBreakdowns = candidates.map((c) => {
591
- const { breakdown } = scoreCandidate(
592
- c.box,
593
- obstacles,
594
- svgRect,
595
- chartArea,
596
- anchorX,
597
- anchorY,
598
- chartDiagonal,
599
- c.candidateIdx,
600
- true,
601
- );
602
- return {
603
- ...breakdown!,
604
- direction: dirNames[c.directionIndex],
605
- ring: c.ring,
606
- };
607
- });
608
- }
609
-
610
- return {
611
- labelX: best.labelX,
612
- labelY: best.labelY,
613
- textAnchor: best.textAnchor,
614
- bounds: best.box,
615
- score: best.score,
616
- debug: debugBreakdowns,
617
- };
618
- }
619
-
620
- /** Check if an annotation should use the placement search (pure-auto, non-drop-line). */
621
- export function isAutoPlacement(annotation: {
622
- anchor?: string;
623
- offset?: { dx?: number; dy?: number };
624
- connector?: string | boolean | { type?: string };
625
- }): boolean {
626
- if (annotation.offset) return false;
627
- if (annotation.anchor && annotation.anchor !== 'auto') return false;
628
- if (annotation.connector === 'drop-line') return false;
629
- if (
630
- typeof annotation.connector === 'object' &&
631
- annotation.connector !== null &&
632
- annotation.connector.type === 'drop-line'
633
- )
634
- return false;
635
- return true;
636
- }