1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//! Defines traits for building widgets.

use std::any::{type_name, Any, TypeId};
use std::fmt;

use glam::Vec2;

use crate::dom::Dom;
use crate::event::EventResponse;
use crate::event::{EventInterest, WidgetEvent};
use crate::geometry::{Constraints, FlexFit};
use crate::input::InputState;
use crate::layout::LayoutDom;
use crate::paint::PaintDom;
use crate::WidgetId;

/// Trait that's automatically implemented for all widget props.
///
/// This trait is used by yakui to enforce that props implement `Debug`.
pub trait Props: fmt::Debug {}
impl<T> Props for T where T: fmt::Debug {}

/// Information available to a widget during the layout phase.
#[non_exhaustive]
#[allow(missing_docs)]
pub struct LayoutContext<'dom> {
    pub dom: &'dom Dom,
    pub input: &'dom InputState,
    pub layout: &'dom mut LayoutDom,
}

impl<'dom> LayoutContext<'dom> {
    /// Calculate the layout for the given widget with the given constraints.
    ///
    /// This method currently must only be called once per widget per layout
    /// phase.
    pub fn calculate_layout(&mut self, widget: WidgetId, constraints: Constraints) -> Vec2 {
        self.layout
            .calculate(self.dom, self.input, widget, constraints)
    }
}

/// Information available to a widget during the paint phase.
#[non_exhaustive]
#[allow(missing_docs)]
pub struct PaintContext<'dom> {
    pub dom: &'dom Dom,
    pub layout: &'dom LayoutDom,
    pub paint: &'dom mut PaintDom,
}

impl<'dom> PaintContext<'dom> {
    /// Paint the given widget.
    pub fn paint(&mut self, widget: WidgetId) {
        self.paint.paint(self.dom, self.layout, widget);
    }
}

/// Information available to a widget when it has received an event.
#[non_exhaustive]
#[allow(missing_docs)]
pub struct EventContext<'dom> {
    pub dom: &'dom Dom,
    pub layout: &'dom LayoutDom,
    pub input: &'dom InputState,
}

/// A yakui widget. Implement this trait to create a custom widget if composing
/// existing widgets does not solve your use case.
pub trait Widget: 'static + fmt::Debug {
    /// The props that this widget needs to be created or updated. Props define
    /// all of the values that a widget's user can specify every render.
    type Props: Props;

    /// The type that the widget will return to the user when it is created or
    /// updated. This type should contain information like whether the widget
    /// was clicked, had keyboard input, or other info that might be useful.
    type Response;

    /// Create the widget.
    fn new() -> Self;

    /// Update the widget with new props.
    fn update(&mut self, props: Self::Props) -> Self::Response;

    /// Returns whether this widget should grow to fill a flexible layout, and
    /// if so, what weight should be applied to it if other widgets also want to
    /// grow.
    ///
    /// A value of `0` indicates that this widget should not grow, while `1`
    /// means that it should stretch to take the available space.
    fn flex(&self) -> (u32, FlexFit) {
        (0, FlexFit::Loose)
    }

    /// Calculate this widget's layout with the given constraints and return its
    /// size. The returned size must fit within the given constraints, which can
    /// be done using `constraints.constrain(size)`.
    ///
    /// The default implementation will lay out all of this widget's children on
    /// top of each other, and fit the widget tightly around them.
    fn layout(&self, mut ctx: LayoutContext<'_>, constraints: Constraints) -> Vec2 {
        let node = ctx.dom.get_current();
        let mut size = Vec2::ZERO;
        for &child in &node.children {
            let child_size = ctx.calculate_layout(child, constraints);
            size = size.max(child_size);
        }

        constraints.constrain_min(size)
    }

    /// Paint the widget based on its current state.
    ///
    /// The default implementation will paint all of the widget's children.
    fn paint(&self, mut ctx: PaintContext<'_>) {
        let node = ctx.dom.get_current();
        for &child in &node.children {
            ctx.paint(child);
        }
    }

    /// Tells which events the widget is interested in receiving.
    ///
    /// The default implementation will register interest in no events.
    fn event_interest(&self) -> EventInterest {
        EventInterest::empty()
    }

    /// Handle the given event and update the widget's state.
    ///
    /// The default implementation will bubble all events.
    #[allow(unused)]
    fn event(&mut self, ctx: EventContext<'_>, event: &WidgetEvent) -> EventResponse {
        EventResponse::Bubble
    }
}

/// A type-erased version of [`Widget`].
pub trait ErasedWidget: Any + fmt::Debug {
    /// See [`Widget::layout`].
    fn layout(&self, ctx: LayoutContext<'_>, constraints: Constraints) -> Vec2;

    /// See [`Widget::flex`].
    fn flex(&self) -> (u32, FlexFit);

    /// See [`Widget::paint`].
    fn paint(&self, ctx: PaintContext<'_>);

    /// See [`Widget::event_interest`].
    fn event_interest(&self) -> EventInterest;

    /// See [`Widget::event`].
    fn event(&mut self, ctx: EventContext<'_>, event: &WidgetEvent) -> EventResponse;

    /// Returns the type name of the widget, usable only for debugging.
    fn type_name(&self) -> &'static str;
}

impl<T> ErasedWidget for T
where
    T: Widget,
{
    fn layout(&self, ctx: LayoutContext<'_>, constraints: Constraints) -> Vec2 {
        <T as Widget>::layout(self, ctx, constraints)
    }

    fn flex(&self) -> (u32, FlexFit) {
        <T as Widget>::flex(self)
    }

    fn paint(&self, ctx: PaintContext<'_>) {
        <T as Widget>::paint(self, ctx)
    }

    fn event_interest(&self) -> EventInterest {
        <T as Widget>::event_interest(self)
    }

    fn event(&mut self, ctx: EventContext<'_>, event: &WidgetEvent) -> EventResponse {
        log::debug!("Event on {}: {event:?}", type_name::<T>());

        <T as Widget>::event(self, ctx, event)
    }

    fn type_name(&self) -> &'static str {
        type_name::<T>()
    }
}

mopmopafy!(ErasedWidget);