@wxn0brp/db-benchmark 0.0.1 → 0.20261124.1745

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.
@@ -0,0 +1,315 @@
1
+ import { adapterName, fmt } from "./utils.js";
2
+ import { state } from "./var.js";
3
+ function getPlatformsForAdapter(adapter) {
4
+ return [
5
+ ...new Set(state.entries
6
+ .filter(e => e.info.adapter === adapter)
7
+ .map(e => `${e.info.ver}__${e.info.os}`)),
8
+ ].sort((a, b) => {
9
+ const [verA, osA] = a.split("__");
10
+ const [verB, osB] = b.split("__");
11
+ if (verA === "bun" && verB !== "bun")
12
+ return -1;
13
+ if (verB === "bun" && verA !== "bun")
14
+ return 1;
15
+ if (verA !== verB)
16
+ return verB.localeCompare(verA);
17
+ return osA.localeCompare(osB);
18
+ });
19
+ }
20
+ function formatPlatform(platform) {
21
+ const [ver, os] = platform.split("__");
22
+ return ver === "bun" ? `bun / ${os}` : `node ${ver} / ${os}`;
23
+ }
24
+ let selectedBasePlatforms = new Set();
25
+ let selectedTargetPlatforms = new Set();
26
+ let currentSort = "name";
27
+ let currentFilter = "all";
28
+ export function renderCompare() {
29
+ const adapters = [
30
+ ...new Set(state.entries.map(e => e.info.adapter)),
31
+ ].sort();
32
+ const baseSel = document.querySelector("#compare-base");
33
+ const targetSel = document.querySelector("#compare-target");
34
+ const opts = adapters
35
+ .map(a => `<option value="${a}">${adapterName(a)}</option>`)
36
+ .join("");
37
+ baseSel.innerHTML = opts;
38
+ targetSel.innerHTML = opts;
39
+ if (adapters.length > 1)
40
+ targetSel.selectedIndex = 1;
41
+ function updatePlatformChips() {
42
+ const basePlatforms = getPlatformsForAdapter(baseSel.value);
43
+ const targetPlatforms = getPlatformsForAdapter(targetSel.value);
44
+ selectedBasePlatforms = new Set(basePlatforms);
45
+ selectedTargetPlatforms = new Set(targetPlatforms);
46
+ renderPlatformChips("compare-base-chips", basePlatforms, selectedBasePlatforms, (platform, checked) => {
47
+ if (checked)
48
+ selectedBasePlatforms.add(platform);
49
+ else
50
+ selectedBasePlatforms.delete(platform);
51
+ updateCompareResults();
52
+ });
53
+ renderPlatformChips("compare-target-chips", targetPlatforms, selectedTargetPlatforms, (platform, checked) => {
54
+ if (checked)
55
+ selectedTargetPlatforms.add(platform);
56
+ else
57
+ selectedTargetPlatforms.delete(platform);
58
+ updateCompareResults();
59
+ });
60
+ }
61
+ function updateCompareResults() {
62
+ doCompare(baseSel.value, targetSel.value, Array.from(selectedBasePlatforms), Array.from(selectedTargetPlatforms));
63
+ }
64
+ baseSel.addEventListener("change", () => {
65
+ updatePlatformChips();
66
+ updateCompareResults();
67
+ });
68
+ targetSel.addEventListener("change", () => {
69
+ updatePlatformChips();
70
+ updateCompareResults();
71
+ });
72
+ document.querySelectorAll("[data-sort]").forEach(btn => {
73
+ btn.addEventListener("click", () => {
74
+ document
75
+ .querySelectorAll("[data-sort]")
76
+ .forEach(b => b.classList.remove("active"));
77
+ btn.classList.add("active");
78
+ currentSort = btn.dataset.sort;
79
+ updateCompareResults();
80
+ });
81
+ });
82
+ document.querySelectorAll("[data-filter]").forEach(btn => {
83
+ btn.addEventListener("click", () => {
84
+ document
85
+ .querySelectorAll("[data-filter]")
86
+ .forEach(b => b.classList.remove("active"));
87
+ btn.classList.add("active");
88
+ currentFilter = btn.dataset.filter;
89
+ updateCompareResults();
90
+ });
91
+ });
92
+ updatePlatformChips();
93
+ updateCompareResults();
94
+ }
95
+ function renderPlatformChips(containerId, platforms, selected, onChange) {
96
+ const container = document.querySelector(`#${containerId}`);
97
+ if (!container)
98
+ return;
99
+ container.innerHTML = platforms
100
+ .map(p => {
101
+ const checked = selected.has(p) ? "checked" : "";
102
+ return `<label class="platform-chip ${checked ? "active" : ""}">
103
+ <input type="checkbox" value="${p}" ${checked} style="display:none;">
104
+ ${formatPlatform(p)}
105
+ </label>`;
106
+ })
107
+ .join("");
108
+ container.querySelectorAll("label.platform-chip").forEach(label => {
109
+ label.addEventListener("click", e => {
110
+ e.preventDefault();
111
+ const input = label.querySelector("input");
112
+ const isChecked = input.checked;
113
+ input.checked = !isChecked;
114
+ label.classList.toggle("active");
115
+ onChange(input.value, !isChecked);
116
+ });
117
+ });
118
+ }
119
+ function filterEntriesByPlatforms(entries, adapter, platforms) {
120
+ return entries.filter(e => {
121
+ if (e.info.adapter !== adapter)
122
+ return false;
123
+ const key = `${e.info.ver}__${e.info.os}`;
124
+ return platforms.includes(key);
125
+ });
126
+ }
127
+ function stddev(values) {
128
+ if (values.length < 2)
129
+ return 0;
130
+ const avg = values.reduce((a, b) => a + b, 0) / values.length;
131
+ const sq = values.map(v => (v - avg) ** 2);
132
+ return Math.sqrt(sq.reduce((a, b) => a + b, 0) / (values.length - 1));
133
+ }
134
+ function buildCompareRows(baseA, targetA, basePlatforms, targetPlatforms) {
135
+ const { entries } = state;
136
+ const allOps = [
137
+ ...new Set(entries.flatMap(e => e.data.results.map(r => r.name))),
138
+ ].sort();
139
+ const baseEntries = filterEntriesByPlatforms(entries, baseA, basePlatforms);
140
+ const targetEntries = filterEntriesByPlatforms(entries, targetA, targetPlatforms);
141
+ const rows = [];
142
+ for (const op of allOps) {
143
+ const baseTimes = baseEntries
144
+ .map(e => e.data.results.find(r => r.name === op)?.time)
145
+ .filter((t) => t !== undefined);
146
+ const targetTimes = targetEntries
147
+ .map(e => e.data.results.find(r => r.name === op)?.time)
148
+ .filter((t) => t !== undefined);
149
+ if (!baseTimes.length || !targetTimes.length)
150
+ continue;
151
+ const bAvg = baseTimes.reduce((a, b) => a + b, 0) / baseTimes.length;
152
+ const tAvg = targetTimes.reduce((a, b) => a + b, 0) / targetTimes.length;
153
+ const ratio = bAvg / tAvg;
154
+ let statClass = "stat-equal";
155
+ let text = "Equal";
156
+ const isTiny = Math.min(bAvg, tAvg) < 1;
157
+ const fastRatio = isTiny ? 1.25 : 1.05;
158
+ const slowRatio = isTiny ? 0.75 : 0.95;
159
+ if (ratio < slowRatio) {
160
+ statClass = "stat-faster";
161
+ text = `${adapterName(baseA)} ${(1 / ratio).toFixed(2)}x faster`;
162
+ }
163
+ else if (ratio > fastRatio) {
164
+ statClass = "stat-slower";
165
+ text = `${adapterName(targetA)} ${ratio.toFixed(2)}x faster`;
166
+ }
167
+ let titleText = "Adapters are equal performance-wise";
168
+ if (statClass !== "stat-equal") {
169
+ const betterAdapter = bAvg < tAvg ? baseA : targetA;
170
+ titleText = `${adapterName(betterAdapter)} is faster`;
171
+ }
172
+ rows.push({
173
+ op,
174
+ bAvg,
175
+ tAvg,
176
+ ratio,
177
+ statClass,
178
+ text,
179
+ titleText,
180
+ baseMin: Math.min(...baseTimes),
181
+ baseMax: Math.max(...baseTimes),
182
+ baseStd: stddev(baseTimes),
183
+ baseCount: baseTimes.length,
184
+ targetMin: Math.min(...targetTimes),
185
+ targetMax: Math.max(...targetTimes),
186
+ targetStd: stddev(targetTimes),
187
+ targetCount: targetTimes.length,
188
+ });
189
+ }
190
+ return rows;
191
+ }
192
+ function sortRows(rows, sort) {
193
+ const sorted = [
194
+ ...rows,
195
+ ];
196
+ switch (sort) {
197
+ case "name":
198
+ sorted.sort((a, b) => a.op.localeCompare(b.op));
199
+ break;
200
+ case "diff":
201
+ sorted.sort((a, b) => Math.abs(1 - b.ratio) - Math.abs(1 - a.ratio));
202
+ break;
203
+ case "winner": {
204
+ const order = {
205
+ "stat-faster": 0,
206
+ "stat-equal": 1,
207
+ "stat-slower": 2,
208
+ };
209
+ sorted.sort((a, b) => order[a.statClass] - order[b.statClass] || a.op.localeCompare(b.op));
210
+ break;
211
+ }
212
+ }
213
+ return sorted;
214
+ }
215
+ function filterRows(rows, filter) {
216
+ if (filter === "all")
217
+ return rows;
218
+ const map = {
219
+ faster: "stat-faster",
220
+ slower: "stat-slower",
221
+ equal: "stat-equal",
222
+ };
223
+ return rows.filter(r => r.statClass === map[filter]);
224
+ }
225
+ function buildSummaryHTML(rows, baseA, targetA) {
226
+ const baseWins = rows.filter(r => r.statClass === "stat-faster").length;
227
+ const targetWins = rows.filter(r => r.statClass === "stat-slower").length;
228
+ const equal = rows.filter(r => r.statClass === "stat-equal").length;
229
+ const total = rows.length;
230
+ let winner = "";
231
+ if (baseWins > targetWins) {
232
+ winner = `<span class="stat-faster">${adapterName(baseA)} wins overall</span>`;
233
+ }
234
+ else if (targetWins > baseWins) {
235
+ winner = `<span class="stat-slower">${adapterName(targetA)} wins overall</span>`;
236
+ }
237
+ else {
238
+ winner = `<span class="stat-equal">Tie</span>`;
239
+ }
240
+ return `
241
+ <div id="compare-summary">
242
+ <div class="summary-winner">${winner}</div>
243
+ <div class="summary-stats">
244
+ <span class="summary-stat stat-faster" title="${adapterName(baseA)}">${baseWins} wins</span>
245
+ <span class="summary-stat stat-equal">${equal} equal</span>
246
+ <span class="summary-stat stat-slower" title="${adapterName(targetA)}">${targetWins} wins</span>
247
+ </div>
248
+ <div class="summary-bar">
249
+ <div class="bar-a" style="width: ${total ? (baseWins / total) * 100 : 0}%"></div>
250
+ <div class="bar-equal" style="width: ${total ? (equal / total) * 100 : 0}%"></div>
251
+ <div class="bar-b" style="width: ${total ? (targetWins / total) * 100 : 0}%"></div>
252
+ </div>
253
+ </div>
254
+ `;
255
+ }
256
+ function progressBarHTML(value, maxValue, cssClass) {
257
+ const pct = maxValue > 0 ? Math.max((value / maxValue) * 100, 2) : 2;
258
+ return `<div class="bar-track"><div class="bar-fill ${cssClass}" style="width: ${pct}%"></div></div>`;
259
+ }
260
+ function tooltipText(row, baseA, targetA) {
261
+ const baseInfo = `${adapterName(baseA)}: avg ${fmt(row.bAvg)}`;
262
+ const targetInfo = `${adapterName(targetA)}: avg ${fmt(row.tAvg)}`;
263
+ return `${row.titleText} | ${baseInfo} | ${targetInfo}`;
264
+ }
265
+ export function doCompare(baseA, targetA, basePlatforms = [], targetPlatforms = []) {
266
+ const container = document.querySelector("#compare-results");
267
+ const summaryContainer = document.querySelector("#compare-summary-wrapper");
268
+ container.innerHTML = "";
269
+ const baseEntries = filterEntriesByPlatforms(state.entries, baseA, basePlatforms);
270
+ const targetEntries = filterEntriesByPlatforms(state.entries, targetA, targetPlatforms);
271
+ if (!basePlatforms.length || !targetPlatforms.length) {
272
+ container.innerHTML =
273
+ "<p style='color: var(--pico-muted-color); font-style: italic;'>No platforms selected</p>";
274
+ if (summaryContainer)
275
+ summaryContainer.innerHTML = "";
276
+ return;
277
+ }
278
+ if (!baseEntries.length || !targetEntries.length) {
279
+ container.innerHTML = "<p>No data available for comparison.</p>";
280
+ if (summaryContainer)
281
+ summaryContainer.innerHTML = "";
282
+ return;
283
+ }
284
+ const allRows = buildCompareRows(baseA, targetA, basePlatforms, targetPlatforms);
285
+ const rows = filterRows(sortRows(allRows, currentSort), currentFilter);
286
+ if (summaryContainer) {
287
+ summaryContainer.innerHTML = buildSummaryHTML(allRows, baseA, targetA);
288
+ }
289
+ if (!rows.length) {
290
+ container.innerHTML = "<p>No operations match the current filter.</p>";
291
+ return;
292
+ }
293
+ let html = "";
294
+ for (const row of rows) {
295
+ const cardMax = Math.max(row.bAvg, row.tAvg);
296
+ const tooltip = tooltipText(row, baseA, targetA);
297
+ html += `
298
+ <article class="compare-card" title="${tooltip}">
299
+ <div class="compare-card-header">
300
+ <code>${row.op}</code>
301
+ <span class="compare-badge ${row.statClass}">${row.text}</span>
302
+ </div>
303
+ <div class="compare-bar-row">
304
+ <span class="compare-bar-label time">${fmt(row.bAvg)}</span>
305
+ ${progressBarHTML(row.bAvg, cardMax, "bar-a")}
306
+ </div>
307
+ <div class="compare-bar-row">
308
+ <span class="compare-bar-label time">${fmt(row.tAvg)}</span>
309
+ ${progressBarHTML(row.tAvg, cardMax, "bar-b")}
310
+ </div>
311
+ </article>
312
+ `;
313
+ }
314
+ container.innerHTML = html;
315
+ }
@@ -0,0 +1,93 @@
1
+ import { clearCache, loadFromCache, saveToCache } from "./cache.js";
2
+ import { renderCompare } from "./compare.js";
3
+ import { addLocalResult, loadLocalResultsIntoState, renderLocalResultsList, } from "./local.js";
4
+ import { renderSummary } from "./summary.js";
5
+ import { renderTables, initTablesDownload } from "./tables.js";
6
+ import { normalize, parseEntry } from "./utils.js";
7
+ import { state } from "./var.js";
8
+ async function loadData() {
9
+ const cached = loadFromCache();
10
+ if (cached) {
11
+ state.adapterConfig = cached.adapterConfig;
12
+ state.entries = cached.entries;
13
+ loadLocalResultsIntoState();
14
+ document.querySelector("#loader").style.display = "none";
15
+ document.querySelector("#content").style.display = "block";
16
+ renderSummary();
17
+ renderCompare();
18
+ renderTables();
19
+ initTablesDownload();
20
+ renderLocalResultsList();
21
+ return;
22
+ }
23
+ try {
24
+ const configRes = await fetch("config.json");
25
+ if (configRes.ok)
26
+ state.adapterConfig = await configRes.json();
27
+ const treeRes = await fetch("https://api.github.com/repos/wxn0brP/ValtheraDB-benchmark/git/trees/results?recursive=1");
28
+ const treeData = await treeRes.json();
29
+ const jsonPaths = treeData.tree
30
+ .filter((item) => item.path.endsWith("/result.json"))
31
+ .map((item) => item.path);
32
+ const fetchPromises = jsonPaths.map(async (path) => {
33
+ const rawUrl = `https://raw.githubusercontent.com/wxn0brP/ValtheraDB-benchmark/results/${path}`;
34
+ const res = await fetch(rawUrl);
35
+ const data = await res.json();
36
+ const dir = path.split("/")[0];
37
+ data.results = normalize(data.results);
38
+ return {
39
+ dir,
40
+ info: parseEntry(dir),
41
+ data,
42
+ };
43
+ });
44
+ state.entries = await Promise.all(fetchPromises);
45
+ loadLocalResultsIntoState();
46
+ saveToCache();
47
+ document.querySelector("#loader").style.display = "none";
48
+ document.querySelector("#content").style.display = "block";
49
+ renderSummary();
50
+ renderCompare();
51
+ renderTables();
52
+ initTablesDownload();
53
+ renderLocalResultsList();
54
+ }
55
+ catch (e) {
56
+ console.error("Failed to load data", e);
57
+ document.querySelector("#loader").innerHTML =
58
+ `<p class="danger">Failed to load data. See console for details.</p>`;
59
+ }
60
+ }
61
+ const hamburger = document.querySelector(".hamburger");
62
+ const navLinks = document.querySelector("#nav-links");
63
+ hamburger.addEventListener("click", () => {
64
+ const isOpen = navLinks.classList.toggle("open");
65
+ hamburger.classList.toggle("open");
66
+ hamburger.setAttribute("aria-expanded", String(isOpen));
67
+ });
68
+ navLinks.querySelectorAll("a").forEach(link => {
69
+ link.addEventListener("click", () => {
70
+ navLinks.classList.remove("open");
71
+ hamburger.classList.remove("open");
72
+ hamburger.setAttribute("aria-expanded", "false");
73
+ });
74
+ });
75
+ document
76
+ .querySelector("#clear-cache")
77
+ ?.addEventListener("click", clearCache);
78
+ document
79
+ .querySelector("#upload-local-btn")
80
+ ?.addEventListener("click", async () => {
81
+ const input = document.querySelector("#local-file-input");
82
+ if (!input?.files?.length) {
83
+ alert("Please select a file first");
84
+ return;
85
+ }
86
+ const file = input.files[0];
87
+ const success = await addLocalResult(file);
88
+ if (success) {
89
+ input.value = "";
90
+ renderLocalResultsList();
91
+ }
92
+ });
93
+ loadData();
@@ -0,0 +1,157 @@
1
+ import { renderCompare } from "./compare.js";
2
+ import { renderSummary } from "./summary.js";
3
+ import { renderTables } from "./tables.js";
4
+ import { normalize, parseEntry } from "./utils.js";
5
+ import { state } from "./var.js";
6
+ const LOCAL_KEY = "benchmark-local";
7
+ function getLocalData() {
8
+ try {
9
+ const raw = localStorage.getItem(LOCAL_KEY);
10
+ if (!raw)
11
+ return {
12
+ entries: [],
13
+ adapterNames: {},
14
+ };
15
+ const parsed = JSON.parse(raw);
16
+ if (Array.isArray(parsed)) {
17
+ return {
18
+ entries: parsed,
19
+ adapterNames: {},
20
+ };
21
+ }
22
+ return {
23
+ entries: parsed.entries || [],
24
+ adapterNames: parsed.adapterNames || {},
25
+ };
26
+ }
27
+ catch {
28
+ return {
29
+ entries: [],
30
+ adapterNames: {},
31
+ };
32
+ }
33
+ }
34
+ function saveLocalData(data) {
35
+ localStorage.setItem(LOCAL_KEY, JSON.stringify(data));
36
+ }
37
+ export function getLocalResults() {
38
+ return getLocalData().entries;
39
+ }
40
+ export function saveLocalResults(entries) {
41
+ const data = getLocalData();
42
+ data.entries = entries;
43
+ saveLocalData(data);
44
+ }
45
+ function saveLocalAdapterName(adapterId, name) {
46
+ const data = getLocalData();
47
+ data.adapterNames[adapterId] = name;
48
+ saveLocalData(data);
49
+ }
50
+ function buildDirFromResult(data) {
51
+ const adapter = data.adapter || "local";
52
+ const runtime = data.bun ? "bun" : data.node ? data.node : "local";
53
+ const os = data.os || "local";
54
+ return `${adapter}-local__${runtime}__${os}`;
55
+ }
56
+ export async function addLocalResult(file) {
57
+ try {
58
+ const text = await file.text();
59
+ const data = JSON.parse(text);
60
+ if (!data.results || !Array.isArray(data.results)) {
61
+ alert("Invalid result file format: missing results array");
62
+ return false;
63
+ }
64
+ data.results = normalize(data.results);
65
+ const dir = buildDirFromResult(data);
66
+ const info = parseEntry(dir);
67
+ const baseAdapter = data.adapter || "local";
68
+ const localAdapterName = `${state.adapterConfig[baseAdapter] || baseAdapter} (Local)`;
69
+ state.adapterConfig[info.adapter] = localAdapterName;
70
+ saveLocalAdapterName(info.adapter, localAdapterName);
71
+ const entry = {
72
+ dir,
73
+ info,
74
+ data,
75
+ };
76
+ const locals = getLocalResults();
77
+ const existing = locals.findIndex(e => e.dir === dir);
78
+ if (existing >= 0) {
79
+ locals[existing] = entry;
80
+ }
81
+ else {
82
+ locals.push(entry);
83
+ }
84
+ saveLocalResults(locals);
85
+ state.entries.push(entry);
86
+ renderSummary();
87
+ renderCompare();
88
+ renderTables();
89
+ return true;
90
+ }
91
+ catch (e) {
92
+ console.error("Failed to load local result", e);
93
+ alert(`Failed to load file: ${e.message}`);
94
+ return false;
95
+ }
96
+ }
97
+ export function removeLocalResult(dir) {
98
+ const locals = getLocalResults();
99
+ const filtered = locals.filter(e => e.dir !== dir);
100
+ saveLocalResults(filtered);
101
+ state.entries = state.entries.filter(e => e.dir !== dir);
102
+ renderSummary();
103
+ renderCompare();
104
+ renderTables();
105
+ }
106
+ export function renderLocalResultsList() {
107
+ const container = document.querySelector("#local-results-list");
108
+ if (!container)
109
+ return;
110
+ const locals = getLocalResults();
111
+ if (!locals.length) {
112
+ container.innerHTML =
113
+ "<p style='color: var(--pico-muted-color); font-size: 0.9rem;'>No local results loaded</p>";
114
+ return;
115
+ }
116
+ let html = "";
117
+ for (const entry of locals) {
118
+ const adapterName = state.adapterConfig[entry.info.adapter] || entry.info.adapter;
119
+ const runtime = entry.info.ver === "bun" ? "bun" : `node ${entry.info.ver}`;
120
+ html += `
121
+ <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; margin-bottom: 0.5rem; background: var(--pico-muted-border-color); border-radius: 4px;">
122
+ <div>
123
+ <strong>${adapterName}</strong>
124
+ <span style="color: var(--pico-muted-color); margin-left: 0.5rem;">${runtime} / ${entry.info.os}</span>
125
+ </div>
126
+ <button class="outline contrast" style="padding: 0.15rem 0.5rem; font-size: 0.75rem;" data-dir="${entry.dir}">
127
+ Remove
128
+ </button>
129
+ </div>
130
+ `;
131
+ }
132
+ container.innerHTML = html;
133
+ container.querySelectorAll("button[data-dir]").forEach(btn => {
134
+ btn.addEventListener("click", () => {
135
+ const dir = btn.getAttribute("data-dir");
136
+ if (dir) {
137
+ removeLocalResult(dir);
138
+ renderLocalResultsList();
139
+ }
140
+ });
141
+ });
142
+ }
143
+ export function loadLocalResultsIntoState() {
144
+ const localData = getLocalData();
145
+ for (const [adapterId, name] of Object.entries(localData.adapterNames)) {
146
+ state.adapterConfig[adapterId] = name;
147
+ }
148
+ for (const local of localData.entries) {
149
+ const existing = state.entries.findIndex(e => e.dir === local.dir);
150
+ if (existing >= 0) {
151
+ state.entries[existing] = local;
152
+ }
153
+ else {
154
+ state.entries.push(local);
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,123 @@
1
+ import { adapterName, fmt, parseEntry, threshold } from "./utils.js";
2
+ import { state } from "./var.js";
3
+ function groupByThreshold(sorted) {
4
+ if (!sorted.length)
5
+ return [];
6
+ const groups = [];
7
+ let cur = [
8
+ sorted[0],
9
+ ];
10
+ for (let i = 1; i < sorted.length; i++) {
11
+ const prev = cur[cur.length - 1];
12
+ const t = threshold(prev.time);
13
+ if ((sorted[i].time - prev.time) / prev.time <= t) {
14
+ cur.push(sorted[i]);
15
+ }
16
+ else {
17
+ groups.push(cur);
18
+ cur = [
19
+ sorted[i],
20
+ ];
21
+ }
22
+ }
23
+ groups.push(cur);
24
+ return groups;
25
+ }
26
+ export function renderSummary() {
27
+ const notRanked = [
28
+ "memory",
29
+ ];
30
+ const rankingEntries = state.entries.filter(e => !notRanked.includes(e.info.adapter));
31
+ const allOps = [
32
+ ...new Set(rankingEntries.flatMap(e => e.data.results.map(r => r.name))),
33
+ ].sort();
34
+ const container = document.querySelector("#summary-cards");
35
+ container.innerHTML = "";
36
+ const modal = document.querySelector("#summary-modal");
37
+ const modalTitle = document.querySelector("#summary-modal-title");
38
+ const modalContent = document.querySelector("#summary-modal-content");
39
+ const modalClose = document.querySelector("#summary-modal-close");
40
+ modalClose?.addEventListener("click", () => modal?.close());
41
+ modal?.addEventListener("click", e => {
42
+ if (e.target === modal)
43
+ modal.close();
44
+ });
45
+ for (const op of allOps) {
46
+ const withTime = rankingEntries
47
+ .map(e => ({
48
+ dir: e.dir,
49
+ time: e.data.results.find(r => r.name === op)?.time,
50
+ }))
51
+ .filter((x) => x.time !== undefined);
52
+ if (!withTime.length)
53
+ continue;
54
+ let cardHTML = `<article><header><strong>${op}</strong></header>`;
55
+ const sorted = withTime.sort((a, b) => a.time - b.time);
56
+ const groups = groupByThreshold(sorted);
57
+ const visibleCount = Math.min(3, groups.length);
58
+ const visibleGroups = groups.slice(0, visibleCount);
59
+ const visibleMax = Math.max(...visibleGroups.map(g => g.reduce((s, x) => s + x.time, 0) / g.length));
60
+ for (let i = 0; i < visibleCount; i++) {
61
+ const avg = visibleGroups[i].reduce((s, x) => s + x.time, 0) /
62
+ visibleGroups[i].length;
63
+ const barWidth = visibleMax > 0 ? (avg / visibleMax) * 100 : 0;
64
+ const names = visibleGroups[i]
65
+ .map(x => {
66
+ const info = parseEntry(x.dir);
67
+ return `${adapterName(info.adapter)}/${info.ver}`;
68
+ })
69
+ .join(", ");
70
+ cardHTML += `
71
+ <div style="margin-bottom: 0.75rem;">
72
+ <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
73
+ <span class="adapter">${names}</span>
74
+ <span class="time">${fmt(avg)}</span>
75
+ </div>
76
+ <div class="bar-track">
77
+ <div class="bar-fill" style="width: ${barWidth}%; background: var(--pico-primary);"></div>
78
+ </div>
79
+ </div>`;
80
+ }
81
+ if (groups.length > 3) {
82
+ const allData = JSON.stringify(groups.map(g => ({
83
+ names: g
84
+ .map(x => {
85
+ const info = parseEntry(x.dir);
86
+ return `${adapterName(info.adapter)}/${info.ver}`;
87
+ })
88
+ .join(", "),
89
+ avg: g.reduce((s, x) => s + x.time, 0) / g.length,
90
+ })));
91
+ cardHTML += `<button class="outline contrast show-all-btn" data-op="${op}" data-all='${allData}'>Show all (${groups.length})</button>`;
92
+ }
93
+ cardHTML += `</article>`;
94
+ container.innerHTML += cardHTML;
95
+ }
96
+ container.querySelectorAll(".show-all-btn").forEach(btn => {
97
+ btn.addEventListener("click", () => {
98
+ const op = btn.getAttribute("data-op");
99
+ const allData = JSON.parse(btn.getAttribute("data-all") || "[]");
100
+ const maxTime = Math.max(...allData.map((d) => d.avg));
101
+ if (modalTitle)
102
+ modalTitle.textContent = op ?? "";
103
+ if (modalContent) {
104
+ modalContent.innerHTML = allData
105
+ .map((d) => {
106
+ const barWidth = maxTime > 0 ? (d.avg / maxTime) * 100 : 0;
107
+ return `
108
+ <div style="margin-bottom: 0.75rem;">
109
+ <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
110
+ <span class="adapter">${d.names}</span>
111
+ <span class="time">${fmt(d.avg)}</span>
112
+ </div>
113
+ <div class="bar-track">
114
+ <div class="bar-fill" style="width: ${barWidth}%; background: var(--pico-primary);"></div>
115
+ </div>
116
+ </div>`;
117
+ })
118
+ .join("");
119
+ }
120
+ modal?.showModal();
121
+ });
122
+ });
123
+ }