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

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