eframe/web/storage.rs
1fn local_storage() -> Option<web_sys::Storage> {
2 web_sys::window()?.local_storage().ok()?
3}
4
5/// Read data from local storage.
6pub fn local_storage_get(key: &str) -> Option<String> {
7 local_storage().map(|storage| storage.get_item(key).ok())??
8}
9
10/// Write data to local storage.
11pub fn local_storage_set(key: &str, value: &str) {
12 match local_storage() {
13 Some(storage) => {
14 if let Err(err) = storage.set_item(key, value) {
15 log::warn!(
16 "local_storage_set failed: key={key}, err={}",
17 crate::web::string_from_js_value(&err)
18 );
19 }
20 }
21 None => {
22 log::warn!("local_storage unavailable");
23 }
24 }
25}
26
27/// Remove data from local storage.
28pub fn local_storage_remove(key: &str) {
29 match local_storage() {
30 Some(storage) => {
31 if let Err(err) = storage.remove_item(key) {
32 log::warn!(
33 "local_storage_remove failed: key={key}, err={}",
34 crate::web::string_from_js_value(&err)
35 );
36 }
37 }
38 None => {
39 log::warn!("local_storage unavailable");
40 }
41 }
42}
43
44#[cfg(feature = "persistence")]
45pub(crate) fn load_memory(ctx: &egui::Context) {
46 if let Some(memory_string) = local_storage_get("egui_memory_ron") {
47 match ron::from_str(&memory_string) {
48 Ok(memory) => {
49 ctx.memory_mut(|m| *m = memory);
50 }
51 Err(err) => {
52 log::warn!("Failed to parse memory RON: {err}");
53 }
54 }
55 }
56}
57
58#[cfg(not(feature = "persistence"))]
59pub(crate) fn load_memory(_: &egui::Context) {}
60
61#[cfg(feature = "persistence")]
62pub(crate) fn save_memory(ctx: &egui::Context) {
63 match ctx.memory(ron::to_string) {
64 Ok(ron) => {
65 local_storage_set("egui_memory_ron", &ron);
66 }
67 Err(err) => {
68 log::warn!("Failed to serialize memory as RON: {err}");
69 }
70 }
71}
72
73#[cfg(not(feature = "persistence"))]
74pub(crate) fn save_memory(_: &egui::Context) {}