Skip to main content

eternal_ui/
widget.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The behaviour side of an element.
6
7use std::any::Any;
8
9use eternal_styler::{ComputedStyle, ElementState};
10
11use crate::event::Event;
12use crate::geometry::{Axis, Rect, Size};
13use crate::render::{Fonts, Renderer};
14
15/// What an element does: how it measures, reacts to input and paints.
16///
17/// Composition is declarative (the [`ui!`](crate::ui) macro builds a tree of
18/// elements) but behaviour is imperative: a widget is a plain struct with
19/// methods, and you can reach it through
20/// [`Ui::widget_mut`](crate::Ui::widget_mut) to change it.
21///
22/// The framework draws backgrounds and borders from the computed style and
23/// lays children out; a widget only paints its own content and handles
24/// events aimed at it. Every method has a default, so a container is an
25/// empty impl plus [`axis`](Self::axis).
26pub trait Widget<M>: Any {
27    /// Takes an attribute from the element description, returning `false`
28    /// for one the widget does not know. `id`, `class`, `style`, `grow`,
29    /// `align`, `disabled`, `shortcut` and `state` never reach here.
30    fn set_attribute(&mut self, name: &str, value: &str) -> bool {
31        let _ = (name, value);
32        false
33    }
34
35    /// `Some` for a container: the direction it lays its children out in.
36    fn axis(&self) -> Option<Axis> {
37        None
38    }
39
40    /// The natural size of the widget's own content, without padding or
41    /// border. Containers are measured from their children instead.
42    fn measure(&self, fonts: &dyn Fonts, style: &ComputedStyle) -> Size {
43        let _ = (fonts, style);
44        Size::ZERO
45    }
46
47    /// State the widget owns, such as `CHECKED`, merged into the element's
48    /// state for styling.
49    fn state(&self) -> ElementState {
50        ElementState::empty()
51    }
52
53    /// Whether the widget can take keyboard focus.
54    fn focusable(&self) -> bool {
55        false
56    }
57
58    /// Handles an event aimed at this element. Returning `true` stops the
59    /// event from bubbling to the parent.
60    fn event(&mut self, cx: &mut EventCx<'_, M>, event: &Event) -> bool {
61        let _ = (cx, event);
62        false
63    }
64
65    /// Paints the widget's own content inside `content`, after the
66    /// framework has painted the background and border and before it paints
67    /// the children.
68    fn paint(&self, renderer: &mut dyn Renderer, cx: &PaintCx<'_>, content: Rect) {
69        let _ = (renderer, cx, content);
70    }
71
72    fn as_any(&self) -> &dyn Any;
73
74    fn as_any_mut(&mut self) -> &mut dyn Any;
75}
76
77/// The handlers an element was declared with.
78///
79/// Each kind of event has one slot. Widgets fire them through [`EventCx`].
80pub struct Handlers<M> {
81    pub(crate) click: Option<Box<dyn FnMut() -> M>>,
82    pub(crate) change: Option<Box<dyn FnMut(String) -> M>>,
83    pub(crate) toggle: Option<Box<dyn FnMut(bool) -> M>>,
84    pub(crate) submit: Option<Box<dyn FnMut(String) -> M>>,
85}
86
87impl<M> Default for Handlers<M> {
88    fn default() -> Self {
89        Self {
90            click: None,
91            change: None,
92            toggle: None,
93            submit: None,
94        }
95    }
96}
97
98/// One handler, made by the functions in [`on`](crate::on) and attached with
99/// [`Element::on`](crate::Element::on).
100pub enum Handler<M> {
101    Click(Box<dyn FnMut() -> M>),
102    Change(Box<dyn FnMut(String) -> M>),
103    Toggle(Box<dyn FnMut(bool) -> M>),
104    Submit(Box<dyn FnMut(String) -> M>),
105}
106
107/// Constructors for handlers. In the [`ui!`](crate::ui) macro,
108/// `on:click={|| Msg::Save}` becomes `.on(on::click(|| Msg::Save))`.
109pub mod on {
110    use super::Handler;
111
112    /// A button was clicked, or activated from the keyboard, or its
113    /// shortcut was pressed.
114    pub fn click<M>(f: impl FnMut() -> M + 'static) -> Handler<M> {
115        Handler::Click(Box::new(f))
116    }
117
118    /// A text field's text changed. Fired on every edit.
119    pub fn change<M>(f: impl FnMut(String) -> M + 'static) -> Handler<M> {
120        Handler::Change(Box::new(f))
121    }
122
123    /// A checkbox was checked or unchecked.
124    pub fn toggle<M>(f: impl FnMut(bool) -> M + 'static) -> Handler<M> {
125        Handler::Toggle(Box::new(f))
126    }
127
128    /// Enter was pressed in a text field.
129    pub fn submit<M>(f: impl FnMut(String) -> M + 'static) -> Handler<M> {
130        Handler::Submit(Box::new(f))
131    }
132}
133
134/// What a widget can do while handling an event.
135pub struct EventCx<'a, M> {
136    pub(crate) handlers: &'a mut Handlers<M>,
137    pub(crate) messages: &'a mut Vec<M>,
138    pub(crate) fonts: &'a dyn Fonts,
139    pub(crate) focus_requested: bool,
140    pub(crate) changed: bool,
141    /// The element's border box.
142    pub rect: Rect,
143    /// The element's content box.
144    pub content: Rect,
145    /// The element's state at the time of the event.
146    pub state: ElementState,
147    /// The element's computed style.
148    pub style: &'a ComputedStyle,
149}
150
151impl<M> EventCx<'_, M> {
152    /// Sends a message to the application.
153    pub fn emit(&mut self, message: M) {
154        self.messages.push(message);
155    }
156
157    /// Fires the element's `click` handler, if it has one.
158    pub fn click(&mut self) {
159        if let Some(handler) = &mut self.handlers.click {
160            self.messages.push(handler());
161        }
162    }
163
164    pub fn change(&mut self, text: String) {
165        if let Some(handler) = &mut self.handlers.change {
166            self.messages.push(handler(text));
167        }
168    }
169
170    pub fn toggle(&mut self, checked: bool) {
171        if let Some(handler) = &mut self.handlers.toggle {
172            self.messages.push(handler(checked));
173        }
174    }
175
176    pub fn submit(&mut self, text: String) {
177        if let Some(handler) = &mut self.handlers.submit {
178            self.messages.push(handler(text));
179        }
180    }
181
182    /// Asks for keyboard focus to move to this element.
183    pub fn request_focus(&mut self) {
184        self.focus_requested = true;
185    }
186
187    /// Tells the framework the widget's appearance or size changed, so
188    /// styles and layout are recomputed before the next paint.
189    pub fn mark_changed(&mut self) {
190        self.changed = true;
191    }
192
193    /// For measuring text, for example to place a caret under the pointer.
194    pub fn fonts(&self) -> &dyn Fonts {
195        self.fonts
196    }
197}
198
199/// What a widget can see while painting.
200pub struct PaintCx<'a> {
201    pub style: &'a ComputedStyle,
202    pub state: ElementState,
203}