[egui_web] Auto-save app state to Local Storage every 30 seconds

This commit is contained in:
Emil Ernerfeldt
2020-12-19 20:50:00 +01:00
parent 2fe1e99218
commit 89937bf636
8 changed files with 59 additions and 34 deletions
+14 -3
View File
@@ -19,6 +19,20 @@ pub trait App {
crate::Srgba::from_rgb(16, 16, 16).into()
}
/// Called once on start. Allows you to restore state.
fn load(&mut self, _storage: &dyn Storage) {}
/// Called on shutdown, and perhaps at regular intervals. Allows you to save state.
fn save(&mut self, _storage: &mut dyn Storage) {}
/// Time between automatic calls to `save()`
fn auto_save_interval(&self) -> std::time::Duration {
std::time::Duration::from_secs(30)
}
/// Called once on shutdown (before or after `save()`)
fn on_exit(&mut self) {}
/// Called once before the first frame.
/// Allows you to do setup code and to call `ctx.set_fonts()`.
/// Optional.
@@ -27,9 +41,6 @@ pub trait App {
/// Called each time the UI needs repainting, which may be many times per second.
/// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`.
fn ui(&mut self, ctx: &crate::CtxRef, integration_context: &mut IntegrationContext<'_>);
/// Called once on shutdown. Allows you to save state.
fn on_exit(&mut self, _storage: &mut dyn Storage) {}
}
pub struct IntegrationContext<'a> {
+10 -5
View File
@@ -281,6 +281,16 @@ impl app::App for DemoApp {
"Egui Demo"
}
#[cfg(feature = "serde_json")]
fn load(&mut self, storage: &dyn crate::app::Storage) {
*self = crate::app::get_value(storage, crate::app::APP_KEY).unwrap_or_default()
}
#[cfg(feature = "serde_json")]
fn save(&mut self, storage: &mut dyn crate::app::Storage) {
crate::app::set_value(storage, crate::app::APP_KEY, self);
}
fn ui(&mut self, ctx: &CtxRef, integration_context: &mut crate::app::IntegrationContext<'_>) {
self.frame_history
.on_new_frame(ctx.input().time, integration_context.info.cpu_usage);
@@ -339,9 +349,4 @@ impl app::App for DemoApp {
ctx.request_repaint();
}
}
#[cfg(feature = "serde_json")]
fn on_exit(&mut self, storage: &mut dyn app::Storage) {
app::set_value(storage, app::APP_KEY, self);
}
}