doodle/pkg/wasm/localstorage_js.go
Noah Petherbridge 35a89e5dbe WASM: Store User Files in localStorage
* In WASM build, user levels and doodads are written to localStorage
  using their userdir path as keys (".config/levels/test.level")
* LoadFile() and WriteFile() for both Levels and Doodads interact with
  the localStorage for WASM build instead of filesystem for desktop.
* userdir.ListLevels() and ListDoodads() for WASM scan the localStorage
  keys for file names.
* userdir.ResolvePath() now works for WASM (previously was dummied out),
  checks for the file in localStorage.
2019-06-27 15:59:18 -07:00

40 lines
986 B
Go

// +build js,wasm
package wasm
import (
"strings"
"syscall/js"
"git.kirsle.net/apps/doodle/pkg/log"
)
// StorageKeys returns the list of localStorage keys matching a prefix.
func StorageKeys(prefix string) []string {
keys := js.Global().Get("Object").Call("keys", js.Global().Get("localStorage"))
var result []string
for i := 0; i < keys.Length(); i++ {
value := keys.Index(i).String()
if strings.HasPrefix(value, prefix) {
result = append(result,
strings.TrimPrefix(keys.Index(i).String(), prefix),
)
}
}
log.Info("LS KEYS: %+v", result)
return result
}
// SetSession sets a text value on sessionStorage.
func SetSession(key string, value string) {
js.Global().Get("localStorage").Call("setItem", key, value)
}
// GetSession retrieves a text value from sessionStorage.
func GetSession(key string) (string, bool) {
var value js.Value
value = js.Global().Get("localStorage").Call("getItem", key)
return value.String(), value.Type() == js.TypeString
}