benchforge 0.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 (98) hide show
  1. package/README.md +432 -0
  2. package/bin/benchforge +3 -0
  3. package/dist/bin/benchforge.mjs +9 -0
  4. package/dist/bin/benchforge.mjs.map +1 -0
  5. package/dist/browser/index.js +914 -0
  6. package/dist/index.mjs +3 -0
  7. package/dist/src-CGuaC3Wo.mjs +3676 -0
  8. package/dist/src-CGuaC3Wo.mjs.map +1 -0
  9. package/package.json +49 -0
  10. package/src/BenchMatrix.ts +380 -0
  11. package/src/Benchmark.ts +33 -0
  12. package/src/BenchmarkReport.ts +156 -0
  13. package/src/GitUtils.ts +79 -0
  14. package/src/HtmlDataPrep.ts +148 -0
  15. package/src/MeasuredResults.ts +127 -0
  16. package/src/NodeGC.ts +48 -0
  17. package/src/PermutationTest.ts +115 -0
  18. package/src/StandardSections.ts +268 -0
  19. package/src/StatisticalUtils.ts +176 -0
  20. package/src/TypeUtil.ts +8 -0
  21. package/src/bin/benchforge.ts +4 -0
  22. package/src/browser/BrowserGcStats.ts +44 -0
  23. package/src/browser/BrowserHeapSampler.ts +248 -0
  24. package/src/cli/CliArgs.ts +64 -0
  25. package/src/cli/FilterBenchmarks.ts +68 -0
  26. package/src/cli/RunBenchCLI.ts +856 -0
  27. package/src/export/JsonExport.ts +103 -0
  28. package/src/export/JsonFormat.ts +91 -0
  29. package/src/export/PerfettoExport.ts +203 -0
  30. package/src/heap-sample/HeapSampleReport.ts +196 -0
  31. package/src/heap-sample/HeapSampler.ts +78 -0
  32. package/src/html/HtmlReport.ts +131 -0
  33. package/src/html/HtmlTemplate.ts +284 -0
  34. package/src/html/Types.ts +88 -0
  35. package/src/html/browser/CIPlot.ts +287 -0
  36. package/src/html/browser/HistogramKde.ts +118 -0
  37. package/src/html/browser/LegendUtils.ts +163 -0
  38. package/src/html/browser/RenderPlots.ts +263 -0
  39. package/src/html/browser/SampleTimeSeries.ts +389 -0
  40. package/src/html/browser/Types.ts +96 -0
  41. package/src/html/browser/index.ts +1 -0
  42. package/src/html/index.ts +17 -0
  43. package/src/index.ts +92 -0
  44. package/src/matrix/CaseLoader.ts +36 -0
  45. package/src/matrix/MatrixFilter.ts +103 -0
  46. package/src/matrix/MatrixReport.ts +290 -0
  47. package/src/matrix/VariantLoader.ts +46 -0
  48. package/src/runners/AdaptiveWrapper.ts +391 -0
  49. package/src/runners/BasicRunner.ts +368 -0
  50. package/src/runners/BenchRunner.ts +60 -0
  51. package/src/runners/CreateRunner.ts +11 -0
  52. package/src/runners/GcStats.ts +107 -0
  53. package/src/runners/RunnerOrchestrator.ts +374 -0
  54. package/src/runners/RunnerUtils.ts +2 -0
  55. package/src/runners/TimingUtils.ts +13 -0
  56. package/src/runners/WorkerScript.ts +256 -0
  57. package/src/table-util/ConvergenceFormatters.ts +19 -0
  58. package/src/table-util/Formatters.ts +152 -0
  59. package/src/table-util/README.md +70 -0
  60. package/src/table-util/TableReport.ts +293 -0
  61. package/src/table-util/test/TableReport.test.ts +105 -0
  62. package/src/table-util/test/TableValueExtractor.test.ts +41 -0
  63. package/src/table-util/test/TableValueExtractor.ts +100 -0
  64. package/src/test/AdaptiveRunner.test.ts +185 -0
  65. package/src/test/AdaptiveStatistics.integration.ts +119 -0
  66. package/src/test/BenchmarkReport.test.ts +82 -0
  67. package/src/test/BrowserBench.e2e.test.ts +44 -0
  68. package/src/test/BrowserBench.test.ts +79 -0
  69. package/src/test/GcStats.test.ts +94 -0
  70. package/src/test/PermutationTest.test.ts +121 -0
  71. package/src/test/RunBenchCLI.test.ts +166 -0
  72. package/src/test/RunnerOrchestrator.test.ts +102 -0
  73. package/src/test/StatisticalUtils.test.ts +112 -0
  74. package/src/test/TestUtils.ts +93 -0
  75. package/src/test/fixtures/test-bench-script.ts +30 -0
  76. package/src/tests/AdaptiveConvergence.test.ts +177 -0
  77. package/src/tests/AdaptiveSampling.test.ts +240 -0
  78. package/src/tests/BenchMatrix.test.ts +366 -0
  79. package/src/tests/MatrixFilter.test.ts +117 -0
  80. package/src/tests/MatrixReport.test.ts +139 -0
  81. package/src/tests/RealDataValidation.test.ts +177 -0
  82. package/src/tests/fixtures/baseline/impl.ts +4 -0
  83. package/src/tests/fixtures/bevy30-samples.ts +158 -0
  84. package/src/tests/fixtures/cases/asyncCases.ts +7 -0
  85. package/src/tests/fixtures/cases/cases.ts +8 -0
  86. package/src/tests/fixtures/cases/variants/product.ts +2 -0
  87. package/src/tests/fixtures/cases/variants/sum.ts +2 -0
  88. package/src/tests/fixtures/discover/fast.ts +1 -0
  89. package/src/tests/fixtures/discover/slow.ts +4 -0
  90. package/src/tests/fixtures/invalid/bad.ts +1 -0
  91. package/src/tests/fixtures/loader/fast.ts +1 -0
  92. package/src/tests/fixtures/loader/slow.ts +4 -0
  93. package/src/tests/fixtures/loader/stateful.ts +2 -0
  94. package/src/tests/fixtures/stateful/stateful.ts +2 -0
  95. package/src/tests/fixtures/variants/extra.ts +1 -0
  96. package/src/tests/fixtures/variants/impl.ts +1 -0
  97. package/src/tests/fixtures/worker/fast.ts +1 -0
  98. package/src/tests/fixtures/worker/slow.ts +4 -0
@@ -0,0 +1,287 @@
1
+ import type { ComparisonCI, HistogramBin } from "./Types.ts";
2
+
3
+ export interface DistributionPlotOptions {
4
+ width?: number;
5
+ height?: number;
6
+ title?: string;
7
+ smooth?: boolean;
8
+ direction?: "faster" | "slower" | "uncertain";
9
+ }
10
+
11
+ const defaultOpts: Required<DistributionPlotOptions> = {
12
+ width: 260,
13
+ height: 85,
14
+ title: "p50 Δ%",
15
+ smooth: false,
16
+ direction: "uncertain",
17
+ };
18
+
19
+ const colors = {
20
+ faster: { fill: "#dcfce7", stroke: "#22c55e" },
21
+ slower: { fill: "#fee2e2", stroke: "#ef4444" },
22
+ uncertain: { fill: "#dbeafe", stroke: "#3b82f6" },
23
+ };
24
+
25
+ type Scales = { x: (v: number) => number; y: (v: number) => number };
26
+ type Layout = {
27
+ width: number;
28
+ height: number;
29
+ margin: typeof defaultMargin;
30
+ plot: { w: number; h: number };
31
+ };
32
+ const defaultMargin = { top: 22, right: 12, bottom: 22, left: 12 };
33
+
34
+ /** Create a small distribution plot showing histogram with CI shading */
35
+ export function createDistributionPlot(
36
+ histogram: HistogramBin[],
37
+ ci: [number, number],
38
+ pointEstimate: number,
39
+ options: DistributionPlotOptions = {},
40
+ ): SVGSVGElement {
41
+ const opts = { ...defaultOpts, ...options };
42
+ const layout = buildLayout(opts.width, opts.height);
43
+ const svg = createSvg(layout.width, layout.height);
44
+ if (!histogram?.length) return svg;
45
+
46
+ const { fill, stroke } = colors[opts.direction];
47
+ const scales = buildScales(histogram, ci, layout);
48
+
49
+ drawTitle(svg, opts.title, layout.margin.left);
50
+ drawCIRegion(svg, ci, scales, layout, fill);
51
+ opts.smooth
52
+ ? drawSmoothedDist(svg, histogram, scales, stroke)
53
+ : drawHistogramBars(svg, histogram, scales, layout, stroke);
54
+ drawZeroLine(svg, scales, layout);
55
+ drawPointEstimate(svg, pointEstimate, scales, layout, stroke);
56
+ drawCILabels(svg, ci, scales, layout.height);
57
+ return svg;
58
+ }
59
+
60
+ /** Convenience wrapper for ComparisonCI data */
61
+ export function createCIPlot(
62
+ ci: ComparisonCI,
63
+ options: Partial<DistributionPlotOptions> = {},
64
+ ): SVGSVGElement {
65
+ if (!ci.histogram) return createSvg(0, 0);
66
+ return createDistributionPlot(ci.histogram, ci.ci, ci.percent, {
67
+ direction: ci.direction,
68
+ ...options,
69
+ });
70
+ }
71
+
72
+ function buildLayout(width: number, height: number): Layout {
73
+ const margin = defaultMargin;
74
+ const w = width - margin.left - margin.right;
75
+ const h = height - margin.top - margin.bottom;
76
+ return { width, height, margin, plot: { w, h } };
77
+ }
78
+
79
+ /** Compute x/y scale functions mapping data values to SVG coordinates */
80
+ function buildScales(
81
+ histogram: HistogramBin[],
82
+ ci: [number, number],
83
+ layout: Layout,
84
+ ): Scales {
85
+ const { margin, plot } = layout;
86
+ const xMin = Math.min(...histogram.map(b => b.x), ci[0], 0);
87
+ const xMax = Math.max(...histogram.map(b => b.x), ci[1], 0);
88
+ const yMax = Math.max(...histogram.map(b => b.count));
89
+ return {
90
+ x: (v: number) => margin.left + ((v - xMin) / (xMax - xMin)) * plot.w,
91
+ y: (v: number) => margin.top + plot.h - (v / yMax) * plot.h,
92
+ };
93
+ }
94
+
95
+ function drawTitle(svg: SVGSVGElement, title: string, x: number): void {
96
+ svg.appendChild(text(x, 14, title, "start", "13", "#333", "600"));
97
+ }
98
+
99
+ function drawCIRegion(
100
+ svg: SVGSVGElement,
101
+ ci: [number, number],
102
+ scales: Scales,
103
+ layout: Layout,
104
+ fill: string,
105
+ ) {
106
+ const x = scales.x(ci[0]);
107
+ const w = scales.x(ci[1]) - x;
108
+ svg.appendChild(
109
+ rect(x, layout.margin.top, w, layout.plot.h, { fill, opacity: "0.5" }),
110
+ );
111
+ }
112
+
113
+ function drawSmoothedDist(
114
+ svg: SVGSVGElement,
115
+ histogram: HistogramBin[],
116
+ scales: Scales,
117
+ stroke: string,
118
+ ): void {
119
+ const sorted = [...histogram].sort((a, b) => a.x - b.x);
120
+ const smoothed = gaussianSmooth(sorted, 2);
121
+ const pts = smoothed.map(b => `${scales.x(b.x)},${scales.y(b.count)}`);
122
+ const baseline = scales.y(0);
123
+ svg.appendChild(
124
+ path(
125
+ `M${scales.x(smoothed[0].x)},${baseline}L${pts.join("L")}L${scales.x(smoothed.at(-1)!.x)},${baseline}Z`,
126
+ { fill: stroke, opacity: "0.3" },
127
+ ),
128
+ );
129
+ svg.appendChild(
130
+ path(`M${pts.join("L")}`, { stroke, fill: "none", strokeWidth: "1.5" }),
131
+ );
132
+ }
133
+
134
+ function drawHistogramBars(
135
+ svg: SVGSVGElement,
136
+ histogram: HistogramBin[],
137
+ scales: Scales,
138
+ layout: Layout,
139
+ stroke: string,
140
+ ): void {
141
+ const sorted = [...histogram].sort((a, b) => a.x - b.x);
142
+ const binW = sorted.length > 1 ? sorted[1].x - sorted[0].x : 1;
143
+ const yMax = Math.max(...histogram.map(b => b.count));
144
+ const xRange = scales.x(sorted.at(-1)!.x) - scales.x(sorted[0].x) + binW;
145
+ for (const bin of sorted) {
146
+ const barW = (binW / xRange) * layout.plot.w * 0.9;
147
+ const barH = (bin.count / yMax) * layout.plot.h;
148
+ svg.appendChild(
149
+ rect(
150
+ scales.x(bin.x) - barW / 2,
151
+ layout.margin.top + layout.plot.h - barH,
152
+ barW,
153
+ barH,
154
+ { fill: stroke, opacity: "0.6" },
155
+ ),
156
+ );
157
+ }
158
+ }
159
+
160
+ function drawZeroLine(svg: SVGSVGElement, scales: Scales, layout: Layout) {
161
+ const zeroX = scales.x(0);
162
+ if (zeroX < layout.margin.left || zeroX > layout.width - layout.margin.right)
163
+ return;
164
+ const top = layout.margin.top;
165
+ const attrs = { stroke: "#666", strokeWidth: "1", strokeDasharray: "3,2" };
166
+ svg.appendChild(line(zeroX, top, zeroX, top + layout.plot.h, attrs));
167
+ }
168
+
169
+ function drawPointEstimate(
170
+ svg: SVGSVGElement,
171
+ pt: number,
172
+ scales: Scales,
173
+ layout: Layout,
174
+ stroke: string,
175
+ ) {
176
+ const x = scales.x(pt);
177
+ const top = layout.margin.top;
178
+ svg.appendChild(
179
+ line(x, top, x, top + layout.plot.h, { stroke, strokeWidth: "2" }),
180
+ );
181
+ }
182
+
183
+ function drawCILabels(
184
+ svg: SVGSVGElement,
185
+ ci: [number, number],
186
+ scales: Scales,
187
+ height: number,
188
+ ): void {
189
+ svg.appendChild(
190
+ text(scales.x(ci[0]), height - 4, formatPct(ci[0]), "middle", "12"),
191
+ );
192
+ svg.appendChild(
193
+ text(scales.x(ci[1]), height - 4, formatPct(ci[1]), "middle", "12"),
194
+ );
195
+ }
196
+
197
+ /** Apply gaussian kernel smoothing to histogram bins */
198
+ function gaussianSmooth(bins: HistogramBin[], sigma: number): HistogramBin[] {
199
+ return bins.map((bin, i) => {
200
+ let sum = 0;
201
+ let wt = 0;
202
+ for (let j = 0; j < bins.length; j++) {
203
+ const w = Math.exp(-((i - j) ** 2) / (2 * sigma ** 2));
204
+ sum += bins[j].count * w;
205
+ wt += w;
206
+ }
207
+ return { x: bin.x, count: sum / wt };
208
+ });
209
+ }
210
+
211
+ const formatPct = (v: number) => (v >= 0 ? "+" : "") + v.toFixed(0) + "%";
212
+
213
+ function createSvg(w: number, h: number): SVGSVGElement {
214
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
215
+ svg.setAttribute("width", String(w));
216
+ svg.setAttribute("height", String(h));
217
+ if (w && h) svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
218
+ return svg;
219
+ }
220
+
221
+ function rect(
222
+ x: number,
223
+ y: number,
224
+ w: number,
225
+ h: number,
226
+ attrs: Record<string, string>,
227
+ ): SVGRectElement {
228
+ const el = document.createElementNS("http://www.w3.org/2000/svg", "rect");
229
+ el.setAttribute("x", String(x));
230
+ el.setAttribute("y", String(y));
231
+ el.setAttribute("width", String(w));
232
+ el.setAttribute("height", String(h));
233
+ setAttrs(el, attrs);
234
+ return el;
235
+ }
236
+
237
+ function path(d: string, attrs: Record<string, string>): SVGPathElement {
238
+ const el = document.createElementNS("http://www.w3.org/2000/svg", "path");
239
+ el.setAttribute("d", d);
240
+ setAttrs(el, attrs);
241
+ return el;
242
+ }
243
+
244
+ function line(
245
+ x1: number,
246
+ y1: number,
247
+ x2: number,
248
+ y2: number,
249
+ attrs: Record<string, string>,
250
+ ): SVGLineElement {
251
+ const el = document.createElementNS("http://www.w3.org/2000/svg", "line");
252
+ el.setAttribute("x1", String(x1));
253
+ el.setAttribute("y1", String(y1));
254
+ el.setAttribute("x2", String(x2));
255
+ el.setAttribute("y2", String(y2));
256
+ setAttrs(el, attrs);
257
+ return el;
258
+ }
259
+
260
+ function text(
261
+ x: number,
262
+ y: number,
263
+ content: string,
264
+ anchor = "start",
265
+ size = "9",
266
+ fill = "#666",
267
+ weight = "400",
268
+ ): SVGTextElement {
269
+ const el = document.createElementNS("http://www.w3.org/2000/svg", "text");
270
+ el.setAttribute("x", String(x));
271
+ el.setAttribute("y", String(y));
272
+ el.setAttribute("text-anchor", anchor);
273
+ el.setAttribute("font-size", size);
274
+ el.setAttribute("font-weight", weight);
275
+ el.setAttribute("fill", fill);
276
+ el.textContent = content;
277
+ return el;
278
+ }
279
+
280
+ /** Set SVG attributes, converting camelCase keys to kebab-case */
281
+ function setAttrs(el: SVGElement, attrs: Record<string, string>): void {
282
+ for (const [k, v] of Object.entries(attrs))
283
+ el.setAttribute(
284
+ k.replace(/[A-Z]/g, c => "-" + c.toLowerCase()),
285
+ v,
286
+ );
287
+ }
@@ -0,0 +1,118 @@
1
+ import * as Plot from "@observablehq/plot";
2
+ import * as d3 from "d3";
3
+ import { buildLegend, type LegendItem } from "./LegendUtils.ts";
4
+ import type { Sample } from "./Types.ts";
5
+
6
+ /** Create histogram + KDE plot for sample distribution */
7
+ export function createHistogramKde(
8
+ allSamples: Sample[],
9
+ benchmarkNames: string[],
10
+ ): SVGSVGElement | HTMLElement {
11
+ const { barData, binMin, binMax, yMax } = buildBarData(
12
+ allSamples,
13
+ benchmarkNames,
14
+ );
15
+ const { colorMap, legendItems } = buildColorData(benchmarkNames);
16
+ const xMax = binMax + (binMax - binMin) * 0.45; // extend for legend
17
+
18
+ return Plot.plot({
19
+ marginTop: 24,
20
+ marginLeft: 70,
21
+ marginRight: 10,
22
+ marginBottom: 60,
23
+ width: 550,
24
+ height: 300,
25
+ style: { fontSize: "14px" },
26
+ x: {
27
+ label: "Time (ms)",
28
+ labelAnchor: "center",
29
+ domain: [binMin, xMax],
30
+ labelOffset: 45,
31
+ tickFormat: (d: number) => d.toFixed(1),
32
+ ticks: 5,
33
+ },
34
+ y: {
35
+ label: "Count",
36
+ labelAnchor: "top",
37
+ labelArrow: false,
38
+ grid: true,
39
+ domain: [0, yMax],
40
+ },
41
+ marks: [
42
+ Plot.rectY(barData, {
43
+ x1: "x1",
44
+ x2: "x2",
45
+ y: "count",
46
+ fill: (d: (typeof barData)[0]) => colorMap.get(d.benchmark),
47
+ fillOpacity: 0.6,
48
+ tip: true,
49
+ title: (d: (typeof barData)[0]) => `${d.benchmark}: ${d.count}`,
50
+ }),
51
+ Plot.ruleY([0]),
52
+ ...buildLegend({ xMin: binMin, xMax, yMax }, legendItems),
53
+ ],
54
+ });
55
+ }
56
+
57
+ function buildColorData(benchmarkNames: string[]) {
58
+ const scheme = (d3 as any).schemeObservable10;
59
+ const colorMap = new Map(
60
+ benchmarkNames.map((name, i) => [name, scheme[i % 10]]),
61
+ );
62
+ const legendItems: LegendItem[] = benchmarkNames.map((name, i) => ({
63
+ color: scheme[i % 10],
64
+ label: name,
65
+ style: "vertical-bar",
66
+ }));
67
+ return { colorMap, legendItems };
68
+ }
69
+
70
+ /** Bin samples into grouped histogram bars for each benchmark */
71
+ function buildBarData(allSamples: Sample[], benchmarkNames: string[]) {
72
+ const values = allSamples.map(d => d.value);
73
+ const sorted = values.sort((a, b) => a - b);
74
+ const binMin = d3.quantile(sorted, 0.01)!;
75
+ const binMax = d3.quantile(sorted, 0.99)!;
76
+ const binCount = 25;
77
+ const step = (binMax - binMin) / binCount;
78
+ const thresholds = d3.range(1, binCount).map(i => binMin + i * step);
79
+ const plotWidth = 550;
80
+
81
+ const bins = d3
82
+ .bin<Sample, number>()
83
+ .domain([binMin, binMax])
84
+ .thresholds(thresholds)
85
+ .value(d => d.value)(allSamples);
86
+
87
+ const barData: {
88
+ benchmark: string;
89
+ count: number;
90
+ x1: number;
91
+ x2: number;
92
+ }[] = [];
93
+ const n = benchmarkNames.length;
94
+ const unitsPerPx = (binMax - binMin) / plotWidth;
95
+ const groupGapPx = 8;
96
+
97
+ for (const bin of bins) {
98
+ const counts = new Map<string, number>();
99
+ for (const d of bin)
100
+ counts.set(d.benchmark, (counts.get(d.benchmark) || 0) + 1);
101
+
102
+ const full = bin.x1! - bin.x0!;
103
+ const groupGap = Math.min(full * 0.5, unitsPerPx * groupGapPx);
104
+ const start = bin.x0! + groupGap / 2;
105
+ const w = (full - groupGap) / n;
106
+
107
+ benchmarkNames.forEach((benchmark, i) => {
108
+ const x1 = start + i * w;
109
+ const x2 = start + (i + 1) * w;
110
+ barData.push({ benchmark, count: counts.get(benchmark) || 0, x1, x2 });
111
+ });
112
+ }
113
+
114
+ const maxCount = d3.max(barData, d => d.count)! || 1;
115
+ const yMax = maxCount * 1.15;
116
+
117
+ return { barData, binMin, binMax, yMax };
118
+ }
@@ -0,0 +1,163 @@
1
+ import * as Plot from "@observablehq/plot";
2
+
3
+ export interface LegendBounds {
4
+ xMin: number;
5
+ xMax: number;
6
+ yMax: number;
7
+ }
8
+
9
+ export interface LegendItem {
10
+ color: string;
11
+ label: string;
12
+ style:
13
+ | "filled-dot"
14
+ | "hollow-dot"
15
+ | "vertical-bar"
16
+ | "vertical-line"
17
+ | "rect";
18
+ strokeDash?: string;
19
+ }
20
+
21
+ interface LegendPos {
22
+ legendX: number;
23
+ y: number;
24
+ textX: number;
25
+ xRange: number;
26
+ yMax: number;
27
+ }
28
+
29
+ /** Draw a semi-transparent white background behind the legend area */
30
+ function legendBackground(bounds: LegendBounds): any {
31
+ const xRange = bounds.xMax - bounds.xMin;
32
+ const data = [
33
+ {
34
+ x1: bounds.xMin + xRange * 0.65,
35
+ x2: bounds.xMin + xRange * 1.05,
36
+ y1: bounds.yMax * 0.65,
37
+ y2: bounds.yMax * 1.05,
38
+ },
39
+ ];
40
+ const opts = {
41
+ x1: "x1",
42
+ x2: "x2",
43
+ y1: "y1",
44
+ y2: "y2",
45
+ fill: "white",
46
+ fillOpacity: 0.9,
47
+ stroke: "#ddd",
48
+ strokeWidth: 1,
49
+ };
50
+ return Plot.rect(data, opts);
51
+ }
52
+
53
+ function dotMark(x: number, y: number, color: string, filled: boolean): any {
54
+ return Plot.dot(
55
+ [{ x, y }],
56
+ filled
57
+ ? { x: "x", y: "y", fill: color, r: 4 }
58
+ : { x: "x", y: "y", stroke: color, fill: "none", strokeWidth: 1.5, r: 4 },
59
+ );
60
+ }
61
+
62
+ function verticalBarMark(pos: LegendPos, color: string): any {
63
+ const { legendX, y, xRange, yMax } = pos;
64
+ const w = xRange * 0.012;
65
+ const h = yMax * 0.05;
66
+ const data = [
67
+ { x1: legendX - w / 2, x2: legendX + w / 2, y1: y - h / 2, y2: y + h / 2 },
68
+ ];
69
+ return Plot.rect(data, {
70
+ x1: "x1",
71
+ x2: "x2",
72
+ y1: "y1",
73
+ y2: "y2",
74
+ fill: color,
75
+ fillOpacity: 0.6,
76
+ });
77
+ }
78
+
79
+ function verticalLineMark(
80
+ pos: LegendPos,
81
+ color: string,
82
+ strokeDash?: string,
83
+ ): any {
84
+ const { legendX, y, yMax } = pos;
85
+ return Plot.ruleX([legendX], {
86
+ y1: y - yMax * 0.025,
87
+ y2: y + yMax * 0.025,
88
+ stroke: color,
89
+ strokeWidth: 2,
90
+ strokeDasharray: strokeDash,
91
+ });
92
+ }
93
+
94
+ function rectMark(pos: LegendPos, color: string): any {
95
+ const { legendX, y, xRange, yMax } = pos;
96
+ const data = [
97
+ {
98
+ x1: legendX - xRange * 0.01,
99
+ x2: legendX + xRange * 0.03,
100
+ y1: y - yMax * 0.02,
101
+ y2: y + yMax * 0.02,
102
+ },
103
+ ];
104
+ const opts = {
105
+ x1: "x1",
106
+ x2: "x2",
107
+ y1: "y1",
108
+ y2: "y2",
109
+ fill: color,
110
+ fillOpacity: 0.3,
111
+ stroke: color,
112
+ strokeWidth: 1,
113
+ };
114
+ return Plot.rect(data, opts);
115
+ }
116
+
117
+ function symbolMark(pos: LegendPos, item: LegendItem): any {
118
+ switch (item.style) {
119
+ case "filled-dot":
120
+ return dotMark(pos.legendX, pos.y, item.color, true);
121
+ case "hollow-dot":
122
+ return dotMark(pos.legendX, pos.y, item.color, false);
123
+ case "vertical-bar":
124
+ return verticalBarMark(pos, item.color);
125
+ case "vertical-line":
126
+ return verticalLineMark(pos, item.color, item.strokeDash);
127
+ case "rect":
128
+ return rectMark(pos, item.color);
129
+ }
130
+ }
131
+
132
+ function textMark(pos: LegendPos, label: string): any {
133
+ const data = [{ x: pos.textX, y: pos.y, text: label }];
134
+ return Plot.text(data, {
135
+ x: "x",
136
+ y: "y",
137
+ text: "text",
138
+ fontSize: 11,
139
+ textAnchor: "start",
140
+ fill: "#333",
141
+ });
142
+ }
143
+
144
+ /** Build complete legend marks array */
145
+ export function buildLegend(bounds: LegendBounds, items: LegendItem[]): any[] {
146
+ const xRange = bounds.xMax - bounds.xMin;
147
+ const legendX = bounds.xMin + xRange * 0.68;
148
+ const textX = legendX + xRange * 0.04;
149
+ const getY = (i: number) => bounds.yMax * 0.98 - i * (bounds.yMax * 0.08);
150
+
151
+ const marks: any[] = [legendBackground(bounds)];
152
+ for (let i = 0; i < items.length; i++) {
153
+ const pos: LegendPos = {
154
+ legendX,
155
+ y: getY(i),
156
+ textX,
157
+ xRange,
158
+ yMax: bounds.yMax,
159
+ };
160
+ marks.push(symbolMark(pos, items[i]), textMark(pos, items[i].label));
161
+ }
162
+ return marks;
163
+ }