From e3c3233b3a4e520f37f48d539663505243690859 Mon Sep 17 00:00:00 2001 From: iTrooz Date: Wed, 31 Jan 2024 22:15:23 +0100 Subject: [PATCH] feat: Add progress bar to web version (#1523) --- dist/web/source/index.html | 3 +- dist/web/source/wasm-config.js | 54 ++++++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/dist/web/source/index.html b/dist/web/source/index.html index ec26e1a3f..a981d8311 100644 --- a/dist/web/source/index.html +++ b/dist/web/source/index.html @@ -72,7 +72,8 @@

Not loading in your Browser? Try the native version

-
+

+
diff --git a/dist/web/source/wasm-config.js b/dist/web/source/wasm-config.js index 8e635cd0b..31ae5e4aa 100644 --- a/dist/web/source/wasm-config.js +++ b/dist/web/source/wasm-config.js @@ -1,3 +1,50 @@ +// Monkeypatch WebAssembly to have a progress bar +// inspired from: https://github.com/WordPress/wordpress-playground/pull/46 (but had to be modified) +function monkeyPatch(progressFun) { + const _instantiateStreaming = WebAssembly.instantiateStreaming; + WebAssembly.instantiateStreaming = (response, ...args) => { + const file = response.url.substring( + new URL(response.url).origin.length + 1 + ); + const reportingResponse = new Response( + new ReadableStream({ + async start(controller) { + const contentLength = response.headers.get("content-length"); + const total = parseInt(contentLength, 10); + const reader = response.clone().body.getReader(); + let loaded = 0; + for (; ;) { + const { done, value } = await reader.read(); + if (done) { + progressFun(file, total, total); + break; + } + loaded += value.byteLength; + progressFun(file, loaded, total); + controller.enqueue(value); + } + controller.close(); + } + }, + { + status: response.status, + statusText: response.statusText + } + ) + ); + for (const pair of response.headers.entries()) { + reportingResponse.headers.set(pair[0], pair[1]); + } + + return _instantiateStreaming(reportingResponse, ...args); + } +} +monkeyPatch((file, done, total) => { + let percent = ((done/total)*100).toFixed(2); + let mib = (done/1024**2).toFixed(2); + document.getElementById("progress").innerHTML = `Downloading: ${percent}% (${mib}MiB)`; +}); + function glfwSetCursorCustom(wnd, shape) { let body = document.getElementsByTagName("body")[0] switch (shape) { @@ -57,11 +104,14 @@ var Module = { })(), setStatus: function(text) { }, totalDependencies: 0, - monitorRunDependencies: function(left) { }, + monitorRunDependencies: function(left) { + }, instantiateWasm: function(imports, successCallback) { imports.env.glfwSetCursor = glfwSetCursorCustom imports.env.glfwCreateStandardCursor = glfwCreateStandardCursorCustom - instantiateAsync(wasmBinary, wasmBinaryFile, imports, (result) => successCallback(result.instance, result.module)); + instantiateAsync(wasmBinary, wasmBinaryFile, imports, (result) => { + successCallback(result.instance, result.module) + }); } };