Skip to content

Commit

Permalink
Add on_each_tick_with_state
Browse files Browse the repository at this point in the history
  • Loading branch information
gridbugs committed Mar 3, 2024
1 parent 9815690 commit 9aa85bc
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "chargrid_common"
description = "Common utilities for making text UIs with chargrid"
version = "0.7.1"
version = "0.7.2"
authors = ["Stephen Sherratt <[email protected]>"]
license = "MIT"
readme = "README.md"
Expand Down
5 changes: 5 additions & 0 deletions common/src/control_flow/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,11 @@ impl<T: 'static, S: 'static> CF<Option<T>, S> {
pub fn on_each_tick<F: FnMut() + 'static>(self, f: F) -> Self {
self.0.on_each_tick(f).boxed()
}

/// Call a given function on the state on each tick of the component.
pub fn on_each_tick_with_state<F: FnMut(&mut S) + 'static>(self, f: F) -> Self {
self.0.on_each_tick_with_state(f).boxed()
}
}

impl<O: 'static> CF<O, ()> {
Expand Down
29 changes: 29 additions & 0 deletions common/src/control_flow/unboxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,16 @@ impl<T, C: Component<Output = Option<T>>> CF<C> {
f,
})
}

pub fn on_each_tick_with_state<F: FnMut(&mut C::State)>(
self,
f: F,
) -> CF<OnEachTickWithState<C, F>> {
cf(OnEachTickWithState {
component: self.0,
f,
})
}
}

impl<C: Component<State = ()>> CF<C> {
Expand Down Expand Up @@ -1933,3 +1943,22 @@ impl<C: Component, F: FnMut()> Component for OnEachTick<C, F> {
self.component.size(state, ctx)
}
}

pub struct OnEachTickWithState<C: Component, F: FnMut(&mut C::State)> {
component: C,
f: F,
}
impl<C: Component, F: FnMut(&mut C::State)> Component for OnEachTickWithState<C, F> {
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 {
(self.f)(state);
self.component.update(state, ctx, event)
}
fn size(&self, state: &Self::State, ctx: Ctx) -> Size {
self.component.size(state, ctx)
}
}

0 comments on commit 9aa85bc

Please sign in to comment.