From 1604f876a89ec29b31fcb96ee6a78b3394480b67 Mon Sep 17 00:00:00 2001 From: Daniel Schmidt Date: Sat, 31 Aug 2024 09:20:37 +0200 Subject: [PATCH] feat: optimize file loading in WASM --- cmd/game_wasm/index.html | 62 +++++++++++++++++++++++++++++++++++++++- internal/fs/fs_js.go | 6 +++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/cmd/game_wasm/index.html b/cmd/game_wasm/index.html index 6c2cabc..f24b0e7 100644 --- a/cmd/game_wasm/index.html +++ b/cmd/game_wasm/index.html @@ -197,6 +197,65 @@ term.onData((data) => bubbletea_write(data)); } + function ensureAllFiles() { + // Wait for WASM to be loaded + if (!globalThis.version) { + setTimeout(ensureAllFiles, 100); + return; + } + + // Clear cache if version mismatch + const lastVersion = globalThis.settings.getString("lastCachedVersion"); + if (!lastVersion || lastVersion === "" || globalThis.version !== lastVersion) { + console.log("Clearing file cache due to version mismatch"); + + const keys = Object.keys(window.localStorage); + for (const key of keys) { + if (key.indexOf("assets") !== -1) { + window.localStorage.removeItem(key); + } + } + } + + // Cache files if they don't exist + fetch("./assets/file_index.json") + .then((index) => index.json()) + .then((index) => { + const promises = []; + for (const file of index) { + if (!file.isFile) { + continue; + } + + // only ensure files that end in .lua or .text + if (!file.path.endsWith(".lua") && !file.path.endsWith(".txt")) { + continue; + } + + if (window.fsRead(file.path)) { + continue; + } + + promises.push( + fetch(file.path) + .then((response) => response.text()) + .then((text) => { + window.fsWrite(file.path, text); + }), + ); + } + + if (promises.length === 0) { + return; + } + + Promise.all(promises).then(() => { + console.log("All files loaded"); + globalThis.settings.set("lastCachedVersion", globalThis.version); + }); + }); + } + function init() { const go = new Go(); WebAssembly.instantiateStreaming(fetch("./eoe.wasm"), go.importObject).then((result) => { @@ -206,10 +265,11 @@ }); // Init terminal. This should be done after bubbletea is initialized. For now, I use a timeout. - document.fonts.load((globalThis.settings.getInt("font_size") ?? 14) + 'px "IosevkaTermNerdFontMono"').then(() => initTerminal()); + document.fonts.load((globalThis.settings.getInt("font_size") ?? 12) + 'px "IosevkaTermNerdFontMono"').then(() => initTerminal()); }); } + ensureAllFiles(); init(); diff --git a/internal/fs/fs_js.go b/internal/fs/fs_js.go index 75bd221..9dce056 100644 --- a/internal/fs/fs_js.go +++ b/internal/fs/fs_js.go @@ -8,7 +8,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/samber/lo" "io" "net/http" "os" @@ -16,6 +15,9 @@ import ( "sort" "strings" "syscall/js" + + "github.com/BigJk/end_of_eden/internal/git" + "github.com/samber/lo" ) type noOpWriteCloser struct{} @@ -51,6 +53,8 @@ func init() { } return nil })) + + js.Global().Set("version", git.Tag) } func ReadDir(path string) ([]FileInfo, error) {