commit c59a0e19630c91da1126d9f88494e83ec969d6c7
parent aebb418093209a0b9123a8318d34f3ad9186efdd
Author: Sylvia Ivory <git@sivory.net>
Date: Fri, 20 Jun 2025 01:35:35 -0700
Save config to LocalStorage on web
Diffstat:
3 files changed, 33 insertions(+), 4 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
@@ -1350,6 +1350,7 @@ dependencies = [
"serde_json",
"strum",
"tokio",
+ "web-sys",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
@@ -12,7 +12,6 @@ edition = "2024"
[dependencies]
anyhow = "1.0.98"
chrono = "0.4.41"
-directories = "6.0.0"
fjordgard-unsplash = { version = "0.1.0", path = "crates/unsplash" }
fjordgard-weather = { version = "0.1.0", path = "crates/weather" }
log = "0.4.27"
@@ -24,6 +23,7 @@ strum = { version = "0.27.1", features = ["derive"] }
[target.'cfg(not(target_arch="wasm32"))'.dependencies]
iced = { version = "0.13.1", features = ["canvas", "image", "svg", "tokio"] }
tokio = { version = "1.45.1", features = ["fs", "time"] }
+directories = "6.0.0"
env_logger = "0.11.8"
open = "5.3.2"
rust-embed = "8.7.2"
@@ -35,5 +35,6 @@ console_error_panic_hook = "0.1.7"
console_log = { version = "1.0.0", features = ["color"] }
send_wrapper = "0.6.0"
rust-embed = { version = "8.7.2", features = ["debug-embed"] }
+web-sys = { version = "0.3.77", features = ["Storage", "Window"] }
# will not work without this
instant = { version = "0.1", features = ["wasm-bindgen"] }
diff --git a/src/config.rs b/src/config.rs
@@ -1,5 +1,4 @@
-use std::fs;
-
+#[cfg(not(target_arch = "wasm32"))]
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
@@ -48,6 +47,7 @@ pub struct Config {
}
impl Config {
+ #[cfg(not(target_arch = "wasm32"))]
pub fn load() -> anyhow::Result<Config> {
if let Some(dir) = ProjectDirs::from("net.sivory", "", "fjordgard") {
let config_file = dir.config_dir().join("config.json");
@@ -56,7 +56,7 @@ impl Config {
return Ok(Config::default());
}
- let data = fs::read_to_string(config_file)?;
+ let data = std::fs::read_to_string(config_file)?;
Ok(serde_json::from_str(&data)?)
} else {
@@ -81,7 +81,34 @@ impl Config {
}
#[cfg(target_arch = "wasm32")]
+ fn get_storage() -> anyhow::Result<web_sys::Storage> {
+ let window = web_sys::window()
+ .ok_or_else(|| anyhow::anyhow!("expected window"))?;
+
+ window.local_storage()
+ .map_err(|_| anyhow::anyhow!("expected local_storage"))?
+ .ok_or_else(|| anyhow::anyhow!("expected local_storage"))
+ }
+
+ #[cfg(target_arch = "wasm32")]
+ pub fn load() -> anyhow::Result<Config> {
+ let storage = Self::get_storage()?;
+
+ if let Some(config) = storage.get_item("config").ok().flatten() {
+ Ok(serde_json::from_str(&config)?)
+ } else {
+ Ok(Config::default())
+ }
+ }
+
+ #[cfg(target_arch = "wasm32")]
pub async fn save(&self) -> anyhow::Result<()> {
+ let storage = Self::get_storage()?;
+ let config = serde_json::to_string(self)?;
+
+ storage.set_item("config", &config)
+ .map_err(|_| anyhow::anyhow!("failed to save config"))?;
+
Ok(())
}
}