table = (data) => {
const node = htl.html`<div style=${{
maxHeight: "500px",
overflowY: "scroll"
}}></div>`;
const cols = Object.keys(data[0]);
let sort = cols[0];
let reverse = false;
function setSort(key) {
if (sort === key) {
reverse = !reverse;
} else {
reverse = false;
}
sort = key;
render();
}
function render() {
const sorted = data.sort((_a, _b) => {
let a, b;
if (reverse) {
a = _b;
b = _a;
} else {
a = _a;
b = _b;
}
return typeof a[sort] === "string"
? a[sort].localeCompare(b[sort])
: d3.ascending(a[sort] || 0, b[sort] || 0);
});
const table = htl.html`<table style=${{ maxWidth: "800px", marginTop: 0 }}>
<thead><tr>${cols.map((col) => {
return htl.html`<th
style=${{ cursor: "pointer" }}
onClick=${() => setSort(col)}
><div style=${{ display: "flex" }}>
<div style=${{ color: sort === col ? "black" : "#aaa" }}>${miniplot(
sorted.map((d) =>
typeof d[col] === "string" ? strToNumber(d[col]) : d[col]
)
)}</div>
<span style=${{
paddingLeft: "5px"
}}>${col}</span>
</div></th>`;
})}</tr></thead>
<tbody>
${data.map(
(row) =>
htl.html`<tr>${cols.map(
(col) =>
htl.html`<td style=${{
textAlign: typeof row[col] === "number" ? "right" : "left",
fontVariant: "tabular-nums"
}}>${row[col]}</td>`
)}</tr>`
)}
</tbody>
</table>`;
if (node.querySelector("table"))
node.removeChild(node.querySelector("table"));
node.appendChild(table);
}
render();
return node;
}