Debian Codegraph @

playground/src/parse.ts

raw
1 import { type MessageToWorker, debounce } from './utilities.js';
2
3 // TODO replace this function once https://github.com/tc39/proposal-arraybuffer-base64 ships
4 function base64(bytes: Uint8Array) {
5 // @ts-expect-error it's fine to pass a Uint8Array here
6 return btoa(String.fromCharCode.apply(null, bytes));
7 }
8
9 let input: HTMLTextAreaElement = document.querySelector('#input')!;
10 let output: HTMLTextAreaElement = document.querySelector('#output')!;
11 let downloadButton: HTMLButtonElement = document.querySelector('#download')!;
12
13 let worker = new Worker('worker.js', { type: 'module' });
14
15 let lastBytes: Uint8Array;
16 let sent = '';
17 let statusMessageTimeout = 0;
18
19 // we can't just postmessage to the worker right away because it has a top-level await
20 // so we need to wait for it to tell us it's ready
21 worker.addEventListener('message', () => {
22 worker.addEventListener('message', gotMessage);
23 update();
24 }, { once: true });
25
26 function gotMessage({ data }: { data: { success: true, bytes: Uint8Array } | { success: false, error: string }}) {
27 clearTimeout(statusMessageTimeout);
28 if (input.value === sent) {
29 if (data.success) {
30 lastBytes = data.bytes;
31 output.value = base64(lastBytes);
32 downloadButton.disabled = false;
33 output.style.color = '';
34 } else {
35 output.value = data.error;
36 downloadButton.disabled = true;
37 output.style.color = '#a00';
38 }
39 } else {
40 // the user has already moved on, ignore this result and re-run
41 update();
42 }
43 }
44
45 function update() {
46 sent = input.value;
47 worker.postMessage({ kind: 'parse', source: input.value } satisfies MessageToWorker);
48
49 // wait a bit before updating the output to avoid rapid changes when the output can be parsed quickly
50 statusMessageTimeout = setTimeout(() => {
51 output.value = 'working...';
52 downloadButton.disabled = true;
53 }, 200);
54 }
55
56 input.addEventListener('input', debounce(update, 100));
57
58 downloadButton.addEventListener('click', () => {
59 let blob = new Blob([lastBytes], { type: 'application/wasm' });
60 let link = document.createElement('a');
61 let url = URL.createObjectURL(blob);
62 link.href = url;
63 link.download = 'wasm-tools-parse-output.wasm';
64 link.click();
65 URL.revokeObjectURL(url);
66 });