|
| 1 | +import { resultDiv } from "./dom"; |
| 2 | +import { ui } from "./main"; |
| 3 | + |
| 4 | +let WASM = "secretary.wasm" |
| 5 | + |
| 6 | +declare const Go: any; |
| 7 | + |
| 8 | +export interface Func { |
| 9 | + add: (a: number, b: number) => number |
| 10 | + allTree: () => string |
| 11 | + set: (v: string) => null |
| 12 | +} |
| 13 | + |
| 14 | +interface Window { |
| 15 | + lib: Func; |
| 16 | +} |
| 17 | + |
| 18 | +declare let window: Window; |
| 19 | + |
| 20 | +const go = new Go(); |
| 21 | +let mod: WebAssembly.Module, inst: WebAssembly.Instance; |
| 22 | +WebAssembly.instantiateStreaming(fetch(WASM), go.importObject).then(async (result) => { |
| 23 | + mod = result.module; |
| 24 | + inst = result.instance; |
| 25 | + |
| 26 | + go.run(inst); // Start Go runtime |
| 27 | + |
| 28 | + ui.func = window.lib |
| 29 | + |
| 30 | +}).catch((err) => { |
| 31 | + console.error(err); |
| 32 | +}); |
| 33 | + |
| 34 | +export function SetupWASM() { |
| 35 | + document.getElementById("add-btn")?.addEventListener("click", async () => { |
| 36 | + add() |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +async function add() { |
| 41 | + |
| 42 | + if (!inst) { |
| 43 | + console.error("WebAssembly instance not loaded yet!"); |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + if (typeof ui.func.add === "function") { |
| 48 | + resultDiv.innerText = "Result: " + ui.func.add(10, 20); |
| 49 | + } else { |
| 50 | + console.error("ui.func.add is undefined!"); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +async function allTree() { |
| 55 | + if (!inst) { |
| 56 | + console.error("WebAssembly instance not loaded yet!"); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + if (typeof ui.func.allTree === "function") { |
| 61 | + resultDiv.innerText = "Result: " + ui.func.allTree(); |
| 62 | + } else { |
| 63 | + console.error("ui.func.allTree is undefined!"); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +async function set() { |
| 68 | + if (!inst) { |
| 69 | + console.error("WebAssembly instance not loaded yet!"); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + if (typeof ui.func.set === "function") { |
| 74 | + resultDiv.innerText = "Result: " + ui.func.set("hello"); |
| 75 | + } else { |
| 76 | + console.error("ui.func.set is undefined!"); |
| 77 | + } |
| 78 | +} |
0 commit comments