diff --git a/common/Cargo.toml b/common/Cargo.toml index 5e51ad4..c4f1283 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "chargrid_common" description = "Common utilities for making text UIs with chargrid" -version = "0.7.3" +version = "0.7.4" authors = ["Stephen Sherratt "] license = "MIT" readme = "README.md" diff --git a/common/src/control_flow/boxed.rs b/common/src/control_flow/boxed.rs index f29d88d..a3b3013 100644 --- a/common/src/control_flow/boxed.rs +++ b/common/src/control_flow/boxed.rs @@ -454,6 +454,11 @@ impl CF, S> { pub fn on_each_tick_with_state(self, f: F) -> Self { self.0.on_each_tick_with_state(f).boxed() } + + /// Call a function on the state when the window is closed. + pub fn on_exit_with_state(self, f: F) -> Self { + self.0.on_exit_with_state(f).boxed() + } } impl CF { diff --git a/common/src/control_flow/unboxed.rs b/common/src/control_flow/unboxed.rs index e48b095..fd8b2ac 100644 --- a/common/src/control_flow/unboxed.rs +++ b/common/src/control_flow/unboxed.rs @@ -414,6 +414,13 @@ impl>> CF { f, }) } + + pub fn on_exit_with_state(self, f: F) -> CF> { + cf(OnExitWithState { + component: self.0, + f, + }) + } } impl> CF { @@ -1381,6 +1388,28 @@ where } } +pub struct OnExitWithState { + component: C, + f: F, +} + +impl Component for OnExitWithState { + type Output = C::Output; + type State = C::State; + fn render(&self, state: &Self::State, ctx: Ctx, fb: &mut FrameBuffer) { + self.component.render(state, ctx, fb); + } + fn update(&mut self, state: &mut Self::State, ctx: Ctx, event: Event) -> Self::Output { + if let Event::Input(input::Input::Keyboard(input::keys::ETX)) = event { + (self.f)(state); + } + self.component.update(state, ctx, event) + } + fn size(&self, state: &Self::State, ctx: Ctx) -> Size { + self.component.size(state, ctx) + } +} + /// Component decorator that yields `Err(Escape)` when the escape key is pressed /// rather than passing the escape key event to its child pub struct CatchEscape(pub C);