substrate-rendernoderesults.web.val.run
Readme

Render streaming node results

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
export default function renderNodeResults(stream: any) {
return new Response(
ReadableStream.from((async function*() {
// Yield the initial HTML structure with the persistent badge
yield new TextEncoder().encode(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: sans-serif; margin: 0; padding: 0; }
#content { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px; padding: 0px; }
</style>
</head>
<body>
<div id="content">
`);
let i = 0;
for await (const event of await stream) {
if (event.object === "node.result" && ++i <= 3) {
console.log(JSON.stringify(event.data, null, 2));
yield new TextEncoder().encode(`
<div style="position:relative;background-color:#f0f0f0;border-radius:4px;padding:8px;box-shadow:0 1px 2px rgba(0,0,0,0.1);">
<span style="position:absolute;top:4px;right:4px;font-family:monospace;font-size:0.7rem;padding:2px 4px;border-radius:2px;background-color:${
getBadgeColor(event.node_id)
};color:white;">${event.node_id}</span>
${
event.data.image_uri
? `<img src="${event.data.image_uri}" style="width:100%;height:auto;object-fit:contain;" alt="Generated image"/>`
: `<div style="height:200px;overflow-y:auto;"><p style="font-size:0.8rem;margin:0;">${
event.data.text || ""
}</p></div>`
}
</div>
`);
}
}
// Yield the closing tags
yield new TextEncoder().encode(`
</div>
<script>
function source() {
const currentUrl = window.location.href;
return currentUrl.replace(
/^https:\\/\\/([\\w-]+)\\.web\\.val\\.run/,
'https://www.val.town/v/$1'
);
}
</script>
</body>
</html>
`);
})()),
{ headers: { "Content-Type": "text/html" } },
);
}
function getBadgeColor(nodeId: string): string {
const colors = ["#007bff", "#28a745", "#dc3545", "#ffc107", "#17a2b8"];
const index = nodeId.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0) % colors.length;
return colors[index];
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 2, 2024