Skip to content

Commit

Permalink
feat: implement theme persistence using local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
lemorage committed Jan 14, 2025
1 parent 347ab61 commit 2ca6a94
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion wasm-frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition = "2021"
js-sys = "0.3"
sycamore = "0.8"
wasm-bindgen = "=0.2.93"
web-sys = { version = "0.3", features = ["Window", "Document", "Element"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Storage"] }

[lib]
crate-type = ["cdylib"]
35 changes: 34 additions & 1 deletion wasm-frontend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use web_sys::{window, Document, Element};
pub fn start() {
web_sys::console::log_1(&"Wasm and Sycamore app starting...".into());

apply_theme_from_local_storage();

let document = window().unwrap().document().unwrap();
if let Some(root_element) = document.get_element_by_id("sycamore-root") {
sycamore::render_to(
Expand All @@ -27,7 +29,7 @@ pub fn start() {
// Define the ThemeSwitcher component
#[component]
fn ThemeSwitcher<G: Html>(cx: Scope) -> View<G> {
let is_dark = create_signal(cx, false);
let is_dark = create_signal(cx, load_theme_from_local_storage());

// Toggle theme logic that modifies body class
let toggle_theme = move |_| {
Expand All @@ -39,9 +41,11 @@ fn ThemeSwitcher<G: Html>(cx: Scope) -> View<G> {
if *is_dark.get() {
web_sys::console::log_1(&"Switching to light theme.".into());
body.set_class_name("light");
save_theme_to_local_storage(false);
} else {
web_sys::console::log_1(&"Switching to dark theme.".into());
body.set_class_name("dark");
save_theme_to_local_storage(true);
}
is_dark.set(!*is_dark.get());

Expand Down Expand Up @@ -69,3 +73,32 @@ fn ThemeSwitcher<G: Html>(cx: Scope) -> View<G> {
}
}
}

// Helper function to apply the theme from local storage
fn apply_theme_from_local_storage() {
if let Some(storage) = window().unwrap().local_storage().unwrap() {
if let Ok(Some(theme)) = storage.get_item("theme") {
let document = window().unwrap().document().unwrap();
let body = document.body().unwrap();
body.set_class_name(&theme);
}
}
}

// Helper function to load the theme from local storage
fn load_theme_from_local_storage() -> bool {
if let Some(storage) = window().unwrap().local_storage().unwrap() {
if let Ok(Some(theme)) = storage.get_item("theme") {
return theme == "dark";
}
}
false
}

// Helper function to save the theme in local storage
fn save_theme_to_local_storage(is_dark: bool) {
if let Some(storage) = window().unwrap().local_storage().unwrap() {
let theme = if is_dark { "dark" } else { "light" };
storage.set_item("theme", theme).unwrap();
}
}

0 comments on commit 2ca6a94

Please sign in to comment.