waterui_core/
event.rs

1//! Event handling components and utilities.
2
3use crate::{
4    handler::{BoxHandlerOnce, HandlerFnOnce, HandlerOnce, into_handler_once},
5    metadata::MetadataKey,
6};
7use alloc::boxed::Box;
8/// An enumeration of events that can occur within the UI framework.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum Event {
12    /// The event representing when a component appears.
13    Appear,
14    /// The event representing when a component disappears.
15    Disappear,
16}
17
18/// An event handler that triggers a specified action when a certain event occurs.
19#[derive(Debug)]
20pub struct OnEvent {
21    event: Event,
22    handler: BoxHandlerOnce<()>,
23}
24
25impl MetadataKey for OnEvent {}
26
27impl OnEvent {
28    /// Creates a new `OnEvent` handler for the specified event and action.
29    ///
30    /// # Arguments
31    ///
32    /// * `event` - The event to listen for.
33    /// * `handler` - The action to execute when the event occurs.
34    #[must_use]
35    pub fn new<H: 'static>(event: Event, handler: impl HandlerFnOnce<H, ()>) -> Self {
36        Self {
37            event,
38            handler: Box::new(into_handler_once(handler)),
39        }
40    }
41
42    /// Returns the event associated with this handler.
43    #[must_use]
44    pub const fn event(&self) -> Event {
45        self.event
46    }
47
48    /// Consumes the `OnEvent` and returns the boxed handler.
49    #[must_use]
50    pub fn into_handler(self) -> BoxHandlerOnce<()> {
51        self.handler
52    }
53
54    /// Handles the event by invoking the stored handler.
55    pub fn handle(self, env: &crate::Environment) {
56        (self.handler).handle(env);
57    }
58}