Repository navigation
Expand file tree
/
Copy pathvisuals.ts
More file actions
563 lines (539 loc) · 22.4 KB
/
Copy pathvisuals.ts
File metadata and controls
563 lines (539 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import workbench from "../content/workbench.json";
import { escapeHtml as e, type Feature } from "./content";
import { highlightCode } from "./highlight";
import { icon } from "./icons";
const buttons = (label: string, content: string) =>
`<div class="choices" role="group" aria-label="${e(label)}" data-controls hidden>${content}</div>`;
function choice(
attribute: string,
value: string,
label: string,
selected: boolean,
) {
return `<button type="button" data-${attribute}="${e(value)}" aria-pressed="${selected}">${e(label)}</button>`;
}
function svg(
width: number,
height: number,
title: string,
body: string,
cls = "",
interactive = false,
) {
return `<svg class="drawing ${cls}" viewBox="0 0 ${width} ${height}" role="${interactive ? "group" : "img"}" aria-label="${e(title)}"><title>${e(title)}</title>${body}</svg>`;
}
function label(
x: number | string,
y: number,
text: string,
cls = "",
anchor = "middle",
) {
return `<text x="${x}" y="${y}" class="${cls}" text-anchor="${anchor}">${e(text)}</text>`;
}
type Sample = typeof workbench.a7_to_zig;
type Construct = {
name: string;
source: [RegExp, RegExp?];
zig: [RegExp, RegExp?];
};
const lowering: Construct[] = [
{
name: "Person struct",
source: [/^Person ::/, /^}/],
zig: [/^const Person =/, /^};/],
},
{
name: "Employee struct",
source: [/^Employee ::/, /^}/],
zig: [/^const Employee =/, /^};/],
},
{
name: "main",
source: [/^main ::/, /emp :=/],
zig: [/^fn __a7_user_main/, /const emp =/],
},
{
name: "io.println",
source: [/io.println\("===/, /io.println\("Employee name/],
zig: [/__a7_stdout_print\("===/, /__a7_stdout_print\("Employee name/],
},
];
const safety: Construct[] = [
{
name: "?ref Box",
source: [/value_box := new Box/],
zig: [/value_box = __a7_new/],
},
{
name: "Nil guard",
source: [/if value_box == nil/, /^ }/],
zig: [/if \(value_box == null/, /^ }/],
},
{
name: "Field access",
source: [/value_box.value = 42/],
zig: [/value_box\.\?\.value = 42/],
},
{
name: "Deferred delete",
source: [/defer del value_box/],
zig: [/^ defer \{/, /^ }/],
},
];
type Listing = { lines: string[]; keys: string[]; first: number; last: number };
function listing(
sample: Sample,
constructs: Construct[],
lang: "a7" | "zig",
): Listing {
const source = lang === "a7" ? sample.a7_source : sample.zig_code;
const lines = source.trimEnd().split("\n");
const keys = Array<string>(lines.length).fill("");
constructs.forEach((construct, index) => {
const [first, last] = lang === "a7" ? construct.source : construct.zig;
const start = lines.findIndex((line) => first.test(line));
const end = last
? lines.findIndex((line, i) => i >= start && last.test(line))
: start;
if (start < 0 || end < start)
throw new Error(
`Missing ${construct.name} in ${sample.source_path} (${lang})`,
);
keys.fill(String(index), start, end + 1);
});
const first = keys.findIndex(Boolean);
let last = keys.findLastIndex(Boolean);
if (lines[last + 1] === "}") last++;
return { lines, keys, first, last };
}
function lineMap(source: Listing, zig: Listing, constructs: Construct[]) {
// Each tick marks a line boundary in the core excerpt.
const length = 343;
const boundary = (i: number, file: Listing) =>
(length * (i - file.first)) / (file.last - file.first + 1);
const rails = [source, zig]
.map((file, row) => {
const y = row ? 42 : 4;
const ticks = Array.from({ length: file.last - file.first + 2 },
(_, i) => `M${boundary(file.first + i, file)} ${y - 3}v6`)
.join(" ");
return `<path class="wire" d="M0 ${y}h${length} ${ticks}"/>`;
})
.join("");
const ribbons = constructs
.map((construct, i) => {
const key = String(i);
const [a, b] = [source, zig].map((file) => [
boundary(file.keys.indexOf(key), file),
boundary(file.keys.lastIndexOf(key) + 1, file),
]);
return `<g data-map-key="${key}" aria-label="${e(construct.name)}">
<title>${e(construct.name)}</title><path class="ribbon" d="M${a[0]} 4H${a[1]}L${b[1]} 42H${b[0]}Z"/>
<path class="map-ends" d="M${a[0]} 4H${a[1]} M${b[0]} 42H${b[1]}"/></g>`;
})
.join("");
function captions(file: Listing, language: string) {
const labels = constructs.map((_, i) => {
const start = file.keys.indexOf(String(i));
const end = file.keys.lastIndexOf(String(i));
const mid = (100 * boundary((start + end + 1) / 2, file)) / length;
return `<span data-map-label="${i}" style="--mid: ${mid}%"${i ? " hidden" : ""}>${language} L${start + 1}–${end + 1}</span>`;
});
return `<div class="map-labels">${labels.join("")}</div>`;
}
return `<div class="line-map">${captions(source, "A7")}
<svg viewBox="-1 0 345 46" preserveAspectRatio="none" role="group" aria-label="Source lines mapped to emitted Zig lines">${rails}${ribbons}</svg>
${captions(zig, "Zig")}</div>`;
}
function proofTrace() {
const steps = [
["?ref Box", "Allocate"],
["value_box == nil", "Guard"],
["value_box.?.value", "Unwrap"],
["defer del value_box", "Scope exit"],
];
const coords = [
[3, 3],
[194, 3],
[194, 73],
[3, 73],
];
const route =
'<path class="trace" d="M168 29h26 M177 26l3 3 -3 3 M276 55v18 M273 62l3 3 3 -3 M194 99h-26 M182 96l-3 3 3 3"/>';
const nodes = steps
.map(([code, action], i) => {
const [x, y] = coords[i];
return `<g data-map-key="${i}" aria-label="${e(action)}" transform="translate(${x} ${y})">
<rect class="slot" width="165" height="52"/>${label(82, 20, action, "minor")}${label(82, 40, code, "mono")}</g>`;
})
.join("");
const stacked = steps
.map(
([code, action], i) =>
`<g data-map-key="${i}" aria-label="${e(action)}" transform="translate(4 ${3 + i * 60})">
<rect class="slot" width="212" height="50"/>${label(106, 19, action, "minor")}${label(106, 38, code, "mono")}</g>`,
)
.join("");
const title =
"Nullable allocation, nil guard, non-nil unwrap and deferred deletion";
return (
svg(362, 128, title, route + nodes, "proof-map wide-drawing", true) +
svg(
220,
236,
title,
'<path class="trace" d="M110 50v143"/>' + stacked,
"proof-map narrow-drawing",
true,
)
);
}
function codePane(sample: Sample, file: Listing, lang: "a7" | "zig") {
const source = lang === "a7" ? sample.a7_source : sample.zig_code;
const { lines, keys } = file;
const rows = lines
.map(
(line, i) =>
`<span class="code-line" data-line="${i + 1}"${i >= file.first && i <= file.last ? " data-core" : ""}${keys[i] ? ` data-construct="${keys[i]}"` : ""}>${highlightCode(line, lang) || " "}</span>`,
)
.join("\n");
const title = lang === "a7" ? sample.source_path : "Emitted Zig excerpt";
return `<div class="code-pane"><div class="pane-title">${e(title)}
<button class="copy" data-copy-text="${e(source)}" aria-label="Copy ${e(title)}" hidden>${icon("copy", 14)}${icon("check", 14)}</button></div>
<pre><code>${rows}</code></pre></div>`;
}
function codePair(sample: Sample, constructs: Construct[], proof = false) {
const source = listing(sample, constructs, "a7");
const zig = listing(sample, constructs, "zig");
return `<div data-pair>
<div class="sample-controls">${buttons("Language constructs", constructs.map((c, i) => choice("pick", String(i), c.name, i === 0)).join(""))}
<button type="button" class="toggle-btn" data-full aria-pressed="false" data-controls hidden>Full file</button></div>
${proof ? proofTrace() : lineMap(source, zig, constructs)}
<div class="code-pair">${codePane(sample, source, "a7")}${codePane(sample, zig, "zig")}</div>
<div class="stdout"><b>stdout</b><samp>${e(sample.stdout.trimEnd().split("\n").join(" · "))}</samp></div></div>`;
}
type Struct = Sample["layout"]["structs"][number];
function cacheLine(struct: Struct, capacity: number) {
const pattern = `pad-${struct.name}`;
const segments: string[] = [];
const selectors: string[] = [];
const percent = (offset: number) => 2 + (96 * offset) / capacity + "%";
let cursor = 0;
function segment(end: number, kind: string, name: string, detail: string) {
if (end <= cursor) return;
const size = end - cursor;
selectors.push(choice("field", detail, name, cursor === 0));
const fill = kind === "pad" ? `fill="url(#${e(pattern)})"` : "";
segments.push(`<g data-segment data-detail="${e(detail)}" aria-label="${e(detail)}">
<title>${e(detail)}</title><rect x="${percent(cursor)}" y="39" width="${(96 * size) / capacity}%" height="50" class="byte-${kind}" ${fill}/>
${size >= capacity / 5 ? label(percent(cursor + size / 2), 70, name, "byte-label") : ""}</g>`);
cursor = end;
}
const fieldDetail = (f: Struct["fields"][number]) =>
`${f.name} · ${f.type} · ${f.offset}..${f.offset + f.size}B · size ${f.size}B · align ${f.align}B · ${f.touched} touches`;
for (const field of struct.fields) {
segment(
field.offset,
"pad",
"Padding",
`Interior padding · ${cursor}..${field.offset}B · ${field.offset - cursor}B`,
);
segment(
field.offset + field.size,
field.touched ? "hot" : "cold",
field.name,
fieldDetail(field),
);
}
segment(
struct.size,
"pad",
"Padding",
`Tail padding · ${cursor}..${struct.size}B · ${struct.size - cursor}B`,
);
segment(
capacity,
"free",
"Free",
`Free · ${cursor}..${capacity}B · ${capacity - cursor}B`,
);
const ticks = Array.from({ length: capacity + 1 }, (_, i) => {
const x = percent(i);
const major = i % 16 === 0;
return `<line class="wire" x1="${x}" x2="${x}" y1="35" y2="${major ? 27 : i % 4 === 0 ? 30 : 33}"/>${major ? label(x, 20, i + "B", "mono", i === 0 ? "start" : i === capacity ? "end" : "middle") : ""}`;
}).join("");
const defs = `<defs><pattern id="${e(pattern)}" width="6" height="6" patternUnits="userSpaceOnUse"><rect width="6" height="6" class="pad-base"/><path d="M-1 1l2 -2 M0 6l6 -6 M5 7l2 -2" class="wire"/></pattern></defs>`;
return `<section data-struct-view="${e(struct.name)}"><h3 class="fallback-title">${e(struct.name)} · ${struct.size}B</h3>
<svg class="drawing cache-drawing" width="100%" height="102" role="group" aria-label="${e(struct.name)} across a ${capacity}-byte cache line">${defs}${ticks}${segments.join("")}</svg>
${buttons("Inspect a segment", selectors.join(""))}
<output class="readout" data-inspector>${e(fieldDetail(struct.fields[0]))}</output></section>`;
}
function memoryLayout() {
const { structs, line_bytes } = workbench.memory_layout.layout;
const all = [...structs, ...workbench.a7_to_zig.layout.structs];
return `<div class="viz-body" data-cache><div class="figure-head"><h3>${line_bytes}-byte cache line</h3>
${buttons("Structure", all.map((s, i) => choice("struct", s.name, `${s.name} · ${s.size}B`, i === 0)).join(""))}</div>
${all.map((s) => cacheLine(s, line_bytes)).join("")}
<div class="legend">${["Hot", "Cold", "Padding", "Free"].map((name) => `<span><i class="key-${name.toLowerCase()}"></i>${name}</span>`).join("")}</div></div>`;
}
export function renderWorkbench() {
const panels = [
["zig", "A7 → Zig", codePair(workbench.a7_to_zig, lowering)],
["layout", "Memory layout", memoryLayout()],
[
"safety",
"Explicit safety",
codePair(workbench.explicit_safety, safety, true),
],
];
return `<section class="studio" data-workbench aria-label="Compiler workbench"><div class="studio-bar">
<div role="tablist" aria-label="Compiler workbench" data-controls hidden>${panels
.map(
([key, title], i) =>
`<button role="tab" id="tab-${key}" aria-controls="panel-${key}" aria-selected="${i === 0}" data-wb-tab="${key}">${title}</button>`,
)
.join("")}</div></div>
${panels.map(([key, title, body]) => `<section id="panel-${key}" data-wb-panel="${key}" aria-label="${title}"><h2 class="fallback-title">${title}</h2>${body}</section>`).join("")}</section>`;
}
const stages = [
["Source", ".a7", "Read the entry file and its imports."],
[
"Lex & parse",
"Tokens → AST",
"Tokenize the source and parse its syntax tree.",
],
[
"Resolve names",
"and imports",
"Bind declarations and resolve file-backed modules.",
],
[
"Type check",
"Safety proof",
"Check types and discharge safety obligations.",
],
["Preprocess", "AST", "Prepare the checked syntax tree for Zig emission."],
[
"Generate Zig",
"In memory",
"Generate one Zig translation unit for the program.",
],
[
"Write .zig",
"File boundary",
"Write the translation unit to disk for inspection or a native build.",
],
["zig build-exe", "Zig 0.17.1", "Compile and link the generated Zig source."],
[
"Native binary",
"Executable",
"Write the executable for the target platform.",
],
["Run", "Process", "Start the executable and return its exit status."],
];
const modes = [
["check", 5, "a7 check FILE", "Zig generated in memory. No file written."],
["emit", 6, "a7 FILE", "Write the generated .zig file."],
["build", 8, "a7 build FILE", "Keep the native executable."],
["run", 9, "a7 run FILE", "Build a temporary executable and run it."],
] as const;
function pipelineDrawing(compact: boolean, narrow: boolean) {
const nodes = compact
? [
["Source", ".a7"],
["Python", "Check + safety"],
["Zig source", ".zig"],
["Zig 0.17.1", "build-exe"],
["Native binary", "Executable"],
]
: stages;
const step = compact ? 132 : 118;
const columns = compact ? nodes.length : 6;
const width = narrow ? 256 : step * columns;
const coords = nodes.map((_, i) => {
if (narrow) return [26, 18 + i * 44];
if (i < columns) return [step / 2 + i * step, compact ? 34 : 62];
const spacing = (width - step) / (nodes.length - columns - 1);
return [step / 2 + (i - columns) * spacing, 184];
});
let paths = "";
const rendered = nodes.map(([name, note, detail], i) => {
const [x, y] = coords[i];
if (i > 0) {
const [prevX, prevY] = coords[i - 1];
const fold = !narrow && i === columns;
// Return through the gutter and enter the file boundary from the left.
const d = fold
? `H${width - 6}V108H6V${y}H${x}`
: `L${x} ${y}`;
const mx = fold ? (6 + x) / 2 : (x + prevX) / 2;
const my = narrow ? (y + prevY) / 2 : y;
const angle = narrow ? 90 : 0;
paths += `<g data-rail="${i}"><path class="rail" d="M${prevX} ${prevY}${d}"/>
<path class="rail" transform="translate(${mx} ${my}) rotate(${angle})" d="M-3 -3l3 3 -3 3"/></g>`;
}
const seam = i === (compact ? 2 : 6);
const group = compact
? ""
: `data-stage="${i}" data-detail="${e(detail)}" aria-label="${e(name + ". " + detail)}"`;
const node = seam
? '<path class="station seam" d="M0 -9l9 9 -9 9 -9 -9Z"/>'
: '<rect class="station" x="-5" y="-5" width="10" height="10"/>';
const texts = narrow
? label(25, 4, name, "stage-name", "start") +
label(25, 21, note, "minor", "start")
: label(0, -18, name, "stage-name") + label(0, 25, note, "minor");
return `<g class="stage" transform="translate(${x} ${y})" ${group}>
<rect class="hit" x="${narrow ? -21 : -step / 2 + 1}" y="${narrow ? -18 : -30}" width="${narrow ? 250 : step - 2}" height="${narrow ? 44 : 55}"/>${node}${texts}
${!compact ? `<path class="stop-mark" d="${narrow ? "M-14 -8v16" : "M-8 35h16"}"/>` : ""}</g>`;
});
const groupLabels =
compact || narrow
? ""
: label(12, 14, "Python frontend", "group-label", "start") +
label(16, 138, ".zig boundary & Native backend · Zig 0.17.1", "group-label", "start");
return svg(
width,
narrow ? nodes.length * 44 : compact ? 68 : 225,
compact
? "A7 source to native binary"
: "Python frontend, emitted Zig and native backend",
groupLabels + paths + rendered.join(""),
narrow ? "narrow-drawing" : "wide-drawing",
!compact,
);
}
export function renderPipelineSvg(compact = false) {
const selectors = buttons(
"CLI mode",
modes
.map(
([mode, end, cmd, note], i) =>
`<button data-mode="${mode}" data-end="${end}" data-command="${e(cmd)}" data-note="${e(note)}" aria-pressed="${i === 0}">${mode}</button>`,
)
.join(""),
);
return `<div class="figure" data-pipeline>${compact ? "" : selectors}
${pipelineDrawing(compact, false)}${pipelineDrawing(compact, true)}
${
compact
? ""
: `<div class="mode-caption"><code data-command-out>a7 check FILE</code><span data-mode-note>${modes[0][3]}</span></div>
<output class="readout" data-stage-out>${stages[5][2]}</output>`
}</div>`;
}
export function renderArraySliceSvg() {
const presets = [
[1, 3],
[0, 4],
[2, 4],
[0, 2],
[2, 2],
];
const array = [10, 20, 30, 40];
const cells = array
.map((n, i) => {
const x = 20 + i * 72;
return `<g data-cell="${i}" class="${i === 1 || i === 2 ? "in-view" : ""}"><rect class="slot" x="${x}" y="120" width="72" height="46"/>
${label(x + 36, 149, String(n), "large")}${label(x + 36, 111, String(i), "minor")}
<path class="wire" d="M${x} 166v6"/></g>`;
})
.join("");
const header = `<rect class="slot" x="20" y="25" width="288" height="42"/><path class="wire" d="M208 25v42"/>
${label(20, 16, "Slice header", "group-label", "start")}<text x="34" y="51" class="mono" data-ptr>ptr = &array[1]</text><text x="220" y="51" class="mono" data-len>len = 2</text>`;
const arrow = `<defs><marker id="ptr-head" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto"><path class="arrowhead" d="M0 0l7 3.5L0 7Z"/></marker></defs>
<path data-pointer class="trace" d="M60 68C60 91 104 85 104 117" marker-end="url(#ptr-head)"/>`;
const bracket =
'<path class="trace" data-bracket d="M92 177v8h144v-8"/><g data-endpoints><text x="92" y="201" text-anchor="middle" class="minor" data-start>start 1</text><text x="236" y="201" text-anchor="middle" class="minor" data-end>end 3</text></g><text x="164" y="225" text-anchor="middle" class="mono" data-view>[1..3) → [20, 30] (len = 2)</text>';
return `<div class="figure" data-slice>${buttons("Slice range", presets.map(([s, t], i) => choice("range", s + "," + t, `array[${s}..${t}]`, i === 0)).join(""))}
${svg(328, 236, "Slice header and four backing array elements", header + cells + '<path class="wire" d="M308 166v6"/>' + arrow + bracket)}
<output class="readout" data-bounds>0 ≤ 1 ≤ 3 ≤ 4 · 0 ≤ start ≤ end ≤ 4</output></div>`;
}
export function renderMemoryFlowSvg() {
const box = (x: number, y: number, w: number, name: string, note: string, radius = 0) =>
`<rect class="slot" x="${x}" y="${y}" width="${w}" height="44" rx="${radius}"/>${label(x + w / 2, y + 18, name, "mono")}${label(x + w / 2, y + 35, note, "minor")}`;
const arrow = 'marker-end="url(#branch-head)"';
const shared =
'<defs><marker id="branch-head" markerWidth="7" markerHeight="7" refX="7" refY="3.5" orient="auto"><path fill="context-stroke" d="M0 0l7 3.5L0 7Z"/></marker></defs>' +
box(52, 5, 198, "new Box", "?ref Box") +
'<path class="wire" d="M151 49v27"/><path class="decision" d="M151 76l91 34 -91 34 -91 -34Z"/>' +
label(151, 114, "value_box == nil", "mono");
const nil =
`<path class="branch-line" d="M60 110H47v63" ${arrow}/>` +
label(40, 150, "true", "minor", "end") +
box(4, 174, 86, "ret", "No box", 18);
const live =
`<path class="branch-line" d="M242 110h13v63" ${arrow}/><path class="branch-line" d="M255 218v23" ${arrow}/>` +
label(262, 150, "false", "minor", "start") +
box(150, 174, 210, "value_box.value = 42", "non-nil ref Box") +
box(150, 242, 210, "defer del value_box", "Free at scope exit");
return `<div class="figure" data-lifetime>${buttons(
"Trace allocation",
[
["all", "Both paths"],
["nil", "Nil"],
["live", "Non-nil"],
]
.map(([k, n], i) => choice("branch", k, n, i === 0))
.join(""),
)}
${svg(365, 294, "Allocation, nil guard and deferred cleanup", shared + `<g data-path="nil">${nil}</g><g data-path="live">${live}</g>`)}
<output class="readout" data-lifetime-out>Cleanup is registered after the nil guard succeeds.</output></div>`;
}
const statuses: Feature["status"][] = [
"supported",
"limited",
"planned",
"unavailable",
"unverified",
];
type StatusCounts = Record<Feature["status"], number>;
function countStatuses(records: Feature[]): StatusCounts {
const counts = {
supported: 0,
limited: 0,
planned: 0,
unavailable: 0,
unverified: 0,
};
for (const record of records) counts[record.status]++;
return counts;
}
function statusBar(counts: StatusCounts, name: string) {
let offset = 0;
const segments = statuses.map((status) => {
const count = counts[status];
if (!count) return "";
const rect = `<rect data-status="${status}" data-records="${count}" x="${offset}" width="${count}" height="12"><title>${count} ${status}</title></rect>`;
offset += count;
return rect;
});
const description = statuses
.map((status) => `${counts[status]} ${status}`)
.join(", ");
return `<svg class="status-bar" viewBox="0 0 ${Math.max(1, offset)} 12" preserveAspectRatio="none" role="img" aria-label="${e(name)}: ${description}">${segments.join("")}</svg>`;
}
export function renderStatusBreakdownSvg(features: Feature[]) {
const counts = countStatuses(features);
const groups = Map.groupBy(features, (feature) =>
feature.topic.startsWith("language/") ? "language/*" : feature.topic,
);
const groupsHtml = [...groups]
.sort((a, b) => b[1].length - a[1].length)
.map(
([name, records]) =>
`<div class="topic-row"><span>${e(name)}</span>${statusBar(countStatuses(records), name)}<output data-total="${records.length}">${records.length}</output></div>`,
)
.join("");
const legend = statuses
.map(
(status) =>
`<span><i data-status="${status}"></i><strong>${counts[status]}</strong> ${status}</span>`,
)
.join("");
return `<div class="figure status-figure" data-breakdown><div class="figure-head"><h3>Feature coverage</h3><output data-count>${features.length} records</output></div>
${statusBar(counts, "All feature records")}<div class="legend">${legend}</div>
${buttons("Filter features", ["all", ...statuses].map((s, i) => choice("filter", s, s[0].toUpperCase() + s.slice(1), i === 0)).join(""))}
${groupsHtml}</div>`;
}