Skip to content

Commit

Permalink
Output HTML tables in hello demo.
Browse files Browse the repository at this point in the history
  • Loading branch information
shoestringresearch committed May 28, 2024
1 parent 1af11e6 commit ac2a9b5
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions demo/hello/hello.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@
<head>
<meta charset="UTF-8">
<title>Hello wa-sqlite</title>
<style>
table {
border-collapse: collapse;
display: inline-block;
margin: 0.3em;
}

th, td {
border: 1px solid black;
padding: 4px;
}

th {
background-color: lightblue;
}
</style>
</head>
<body>
<h1></h1>
Expand All @@ -11,7 +27,7 @@ <h1></h1>
SELECT * FROM t;
</textarea>
<button id="submit">Submit query</button>
<pre id="output"></pre>
<div id="output"></div>

<script type="module">
// Load script in the Window or in a Worker, depending on whether
Expand All @@ -36,9 +52,43 @@ <h1></h1>

// Handle query results.
port1.addEventListener('message', (event) => {
document.getElementById('output').textContent = JSON.stringify(event.data, null, 2);
console.log(event.data);
const output = document.getElementById('output');
output.innerHTML = '';
if (Array.isArray(event.data)) {
for (const { columns, rows } of event.data) {
output.appendChild(buildHTMLTable(columns, rows));
}
} else {
output.textContent = 'Error: ' + event.data.error;
}
});
port1.start();

function buildHTMLTable(columns, rows) {
function tx(tag, data) {
const tx = document.createElement(tag);
tx.textContent = data.toString();
return tx;
}

const table = document.createElement('table');
const thead = document.createElement('thead');
const tr = document.createElement('tr');
columns.forEach(column => tr.appendChild(tx('th', column)));
thead.appendChild(tr);
table.appendChild(thead);

const tbody = document.createElement('tbody');
rows.forEach(row => {
const tr = document.createElement('tr');
row.forEach(cell => tr.appendChild(tx('td', cell)));
tbody.appendChild(tr);
});
table.appendChild(tbody);

return table;
}
</script>
</body>
</html>

0 comments on commit ac2a9b5

Please sign in to comment.