Skip to content

Commit

Permalink
Add on_each_tick combinator
Browse files Browse the repository at this point in the history
  • Loading branch information
gridbugs committed Feb 29, 2024
1 parent 0be5996 commit fcce895
Show file tree
Hide file tree
Showing 3 changed files with 32 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.0"
version = "0.7.1"
authors = ["Stephen Sherratt <stephen@sherra.tt>"]
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 @@ -444,6 +444,11 @@ impl<T: 'static, S: 'static> CF<Option<T>, S> {
pub fn pause(self) -> CF<Option<T>, S> {
self.0.pause().boxed()
}

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

impl<O: 'static> CF<O, ()> {
Expand Down
26 changes: 26 additions & 0 deletions common/src/control_flow/unboxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,13 @@ impl<T, C: Component<Output = Option<T>>> CF<C> {
pub fn pause(self) -> CF<Pause<C>> {
cf(Pause(self.0))
}

pub fn on_each_tick<F: FnMut()>(self, f: F) -> CF<OnEachTick<C, F>> {
cf(OnEachTick {
component: self.0,
f,
})
}
}

impl<C: Component<State = ()>> CF<C> {
Expand Down Expand Up @@ -1907,3 +1914,22 @@ where
Size::new(width, height)
}
}

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

0 comments on commit fcce895

Please sign in to comment.