Skip to main content

eternal_ui/
element.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 declarative description of an element, before it is mounted.
6
7use eternal_styler::DeclarationBlock;
8
9use crate::layout::Align;
10use crate::shortcut::Shortcut;
11use crate::widget::{Handler, Handlers, Widget};
12use crate::widgets::{Blank, Button, Checkbox, Container, Label, TextInput, parse_bool};
13
14/// An element waiting to be mounted: a widget, its attributes, handlers
15/// and children.
16///
17/// Built by the [`ui!`](crate::ui) macro or by hand from the constructors
18/// in [`elements`], then handed to [`Ui::set_root`](crate::Ui::set_root) or
19/// [`Ui::mount`](crate::Ui::mount).
20pub struct Element<M> {
21    pub(crate) tag: &'static str,
22    pub(crate) widget: Box<dyn Widget<M>>,
23    pub(crate) id: Option<String>,
24    pub(crate) classes: Vec<String>,
25    pub(crate) attrs: Vec<(String, String)>,
26    pub(crate) custom_states: Vec<String>,
27    pub(crate) inline_style: Option<DeclarationBlock>,
28    pub(crate) handlers: Handlers<M>,
29    pub(crate) children: Vec<Element<M>>,
30    pub(crate) grow: f32,
31    pub(crate) align: Option<Align>,
32    pub(crate) disabled: bool,
33    pub(crate) shortcut: Option<Shortcut>,
34}
35
36impl<M: 'static> Element<M> {
37    /// An element of your own widget type. `tag` is what selectors match it
38    /// by, so use something distinct like `color-picker`.
39    pub fn new(tag: &'static str, widget: impl Widget<M>) -> Self {
40        Self {
41            tag,
42            widget: Box::new(widget),
43            id: None,
44            classes: Vec::new(),
45            attrs: Vec::new(),
46            custom_states: Vec::new(),
47            inline_style: None,
48            handlers: Handlers::default(),
49            children: Vec::new(),
50            grow: 0.0,
51            align: None,
52            disabled: false,
53            shortcut: None,
54        }
55    }
56
57    /// Sets an attribute, the way `name="value"` does in the macro.
58    ///
59    /// `id`, `class`, `style`, `grow`, `align`, `disabled`, `shortcut` and
60    /// `state` are understood by the framework; anything else goes to the
61    /// widget (containers take `align_items` and `justify`, for example). An attribute nobody understands, an inline style that does
62    /// not parse or a bad shortcut is a mistake in the template, and panics
63    /// with a message saying which.
64    ///
65    /// # Panics
66    ///
67    /// On an attribute the element does not accept, or a value it cannot
68    /// parse.
69    pub fn attr(mut self, name: &str, value: impl ToString) -> Self {
70        let value = value.to_string();
71        match name {
72            "id" => self.id = Some(value),
73            "class" => self
74                .classes
75                .extend(value.split_whitespace().map(str::to_owned)),
76            "style" => match DeclarationBlock::parse(&value) {
77                Ok(block) => self.inline_style = Some(block),
78                Err(error) => panic!("<{}> style=\"{value}\": {error}", self.tag),
79            },
80            "grow" => {
81                self.grow = value
82                    .trim()
83                    .parse()
84                    .unwrap_or_else(|_| panic!("<{}> grow=\"{value}\": not a number", self.tag))
85            }
86            "align" => {
87                self.align = Some(Align::parse(&value).unwrap_or_else(|| {
88                    panic!(
89                        "<{}> align=\"{value}\": expected start, center, end or stretch",
90                        self.tag
91                    )
92                }))
93            }
94            "disabled" => self.disabled = parse_bool(&value),
95            "shortcut" => match Shortcut::parse(&value) {
96                Ok(shortcut) => self.shortcut = Some(shortcut),
97                Err(error) => panic!("<{}> shortcut=\"{value}\": {error}", self.tag),
98            },
99            "state" => self
100                .custom_states
101                .extend(value.split_whitespace().map(str::to_owned)),
102            _ => {
103                if !self.widget.set_attribute(name, &value) {
104                    panic!("<{}> does not accept the attribute `{name}`", self.tag);
105                }
106                self.attrs.push((name.to_owned(), value));
107            }
108        }
109        self
110    }
111
112    /// Attaches a handler made by the functions in [`on`](crate::on).
113    pub fn on(mut self, handler: Handler<M>) -> Self {
114        match handler {
115            Handler::Click(f) => self.handlers.click = Some(f),
116            Handler::Change(f) => self.handlers.change = Some(f),
117            Handler::Toggle(f) => self.handlers.toggle = Some(f),
118            Handler::Submit(f) => self.handlers.submit = Some(f),
119        }
120        self
121    }
122
123    /// Appends children: an element, a list of them, an option, or text.
124    ///
125    /// Text goes to the widget if it takes a `text` attribute (a label does)
126    /// and otherwise becomes a child label, so `<button>"Save"</button>` is a
127    /// button containing a label.
128    pub fn child(mut self, child: impl IntoChildren<M>) -> Self {
129        for child in child.into_children() {
130            match child {
131                Child::Element(element) => self.children.push(*element),
132                Child::Text(text) => {
133                    if !self.widget.set_attribute("text", &text) {
134                        self.children.push(elements::label().attr("text", text));
135                    }
136                }
137            }
138        }
139        self
140    }
141
142    pub fn tag(&self) -> &'static str {
143        self.tag
144    }
145
146    pub fn children(&self) -> &[Element<M>] {
147        &self.children
148    }
149
150    pub fn id(&self) -> Option<&str> {
151        self.id.as_deref()
152    }
153
154    pub fn classes(&self) -> &[String] {
155        &self.classes
156    }
157}
158
159/// A child as the macro sees it: an element or a run of text.
160pub enum Child<M> {
161    Element(Box<Element<M>>),
162    Text(String),
163}
164
165/// Anything that can appear as a child in the [`ui!`](crate::ui) macro.
166pub trait IntoChildren<M> {
167    fn into_children(self) -> Vec<Child<M>>;
168}
169
170impl<M> IntoChildren<M> for Element<M> {
171    fn into_children(self) -> Vec<Child<M>> {
172        vec![Child::Element(Box::new(self))]
173    }
174}
175
176impl<M> IntoChildren<M> for Vec<Element<M>> {
177    fn into_children(self) -> Vec<Child<M>> {
178        self.into_iter()
179            .map(|e| Child::Element(Box::new(e)))
180            .collect()
181    }
182}
183
184impl<M> IntoChildren<M> for Option<Element<M>> {
185    fn into_children(self) -> Vec<Child<M>> {
186        self.into_iter()
187            .map(|e| Child::Element(Box::new(e)))
188            .collect()
189    }
190}
191
192impl<M> IntoChildren<M> for Child<M> {
193    fn into_children(self) -> Vec<Child<M>> {
194        vec![self]
195    }
196}
197
198impl<M> IntoChildren<M> for &str {
199    fn into_children(self) -> Vec<Child<M>> {
200        vec![Child::Text(self.to_owned())]
201    }
202}
203
204impl<M> IntoChildren<M> for String {
205    fn into_children(self) -> Vec<Child<M>> {
206        vec![Child::Text(self)]
207    }
208}
209
210impl<M> IntoChildren<M> for &String {
211    fn into_children(self) -> Vec<Child<M>> {
212        vec![Child::Text(self.clone())]
213    }
214}
215
216/// Constructors for the built-in elements, one per tag the
217/// [`ui!`](crate::ui) macro understands.
218pub mod elements {
219    use super::Element;
220    use super::*;
221
222    /// Lays children out top to bottom.
223    pub fn column<M: 'static>() -> Element<M> {
224        Element::new("column", Container::column())
225    }
226
227    /// Lays children out left to right.
228    pub fn row<M: 'static>() -> Element<M> {
229        Element::new("row", Container::row())
230    }
231
232    /// A column meant to be framed by the theme.
233    pub fn panel<M: 'static>() -> Element<M> {
234        Element::new("panel", Container::column())
235    }
236
237    /// A line of text. Takes a `text` attribute or a text child.
238    pub fn label<M: 'static>() -> Element<M> {
239        Element::new("label", Label::default())
240    }
241
242    /// A push button. Text children become its label.
243    pub fn button<M: 'static>() -> Element<M> {
244        Element::new("button", Button)
245    }
246
247    /// A checkbox: a `check` element followed by any children. Takes
248    /// `checked`.
249    pub fn checkbox<M: 'static>() -> Element<M> {
250        Element::new("checkbox", Checkbox::default()).child(Element::new("check", Blank))
251    }
252
253    /// A single-line text field. Takes `value` and `placeholder`.
254    pub fn input<M: 'static>() -> Element<M> {
255        Element::new("input", TextInput::default())
256    }
257
258    /// A thin line between things; the theme gives it a size and colour.
259    pub fn separator<M: 'static>() -> Element<M> {
260        Element::new("separator", Blank)
261    }
262
263    /// An empty element that grows to take up spare room, pushing what
264    /// follows it to the far end.
265    pub fn spacer<M: 'static>() -> Element<M> {
266        Element::new("spacer", Blank).attr("grow", 1)
267    }
268}
269
270/// Marker types the [`ui!`](crate::ui) macro uses to check that a closing
271/// tag matches its opening tag. Not for use directly.
272#[doc(hidden)]
273#[allow(non_camel_case_types)]
274pub mod tags {
275    pub struct column;
276    pub struct row;
277    pub struct panel;
278    pub struct label;
279    pub struct button;
280    pub struct checkbox;
281    pub struct input;
282    pub struct separator;
283    pub struct spacer;
284}