use core::fmt::Debug;
use crate::{MessageContext, MessageResult, Mut, NoElement, View, ViewMarker, ViewPathTracker};
pub fn run_once<F>(once: F) -> RunOnce<F>
where
F: Fn() + 'static,
{
const {
assert!(
size_of::<F>() == 0,
"`run_once` will not be ran again when its captured variables are updated.\n\
To ignore this warning, use `run_once_raw`."
);
};
RunOnce { once }
}
pub fn run_once_raw<F>(once: F) -> RunOnce<F>
where
F: Fn() + 'static,
{
RunOnce { once }
}
#[must_use = "View values do nothing unless provided to Xilem."]
pub struct RunOnce<F> {
once: F,
}
impl<F> Debug for RunOnce<F> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RunOnce").finish_non_exhaustive()
}
}
impl<F> ViewMarker for RunOnce<F> {}
impl<F, State, Action, Context> View<State, Action, Context> for RunOnce<F>
where
Context: ViewPathTracker,
F: Fn() + 'static,
{
type Element = NoElement;
type ViewState = ();
fn build(&self, _: &mut Context, _: &mut State) -> (Self::Element, Self::ViewState) {
(self.once)();
(NoElement, ())
}
fn rebuild(
&self,
_: &Self,
(): &mut Self::ViewState,
_: &mut Context,
(): Mut<'_, Self::Element>,
_: &mut State,
) {
}
fn teardown(&self, (): &mut Self::ViewState, _: &mut Context, _: Mut<'_, Self::Element>) {
}
fn message(
&self,
(): &mut Self::ViewState,
message: &mut MessageContext,
_: Mut<'_, Self::Element>,
_: &mut State,
) -> MessageResult<Action> {
panic!("Message should not have been sent to a `RunOnce` View: {message:?}");
}
}