Skip to main content

serge_core/
builder.rs

1//! What `ui!` and `#[component]` expand to. Not for direct use; the names
2//! are stable for macro output only.
3//!
4//! One closure rule covers everything `ui!` creates — property expressions,
5//! regions, handlers, `paint`: each is `FnOnce + Clone` and every run calls a
6//! fresh clone. Captured values must be `Clone` (handles like `Signal<T>` and
7//! `Ctx<T>` are cheap to clone); state that must survive between runs lives
8//! in signals.
9
10use std::hash::Hash;
11use std::rc::Rc;
12
13use crate::element::{Element, Keyed, KeyedItem, Node, key_hash};
14
15/// A literal or a plain path in property position: evaluated once.
16pub struct Lit<V>(pub V);
17
18/// Any other property expression: re-evaluated when the signals it reads
19/// change.
20pub struct Dyn<F>(pub F);
21
22/// What a built-in widget's property accepts.
23pub trait IntoProp<T> {
24    /// The property.
25    fn into_prop(self) -> crate::element::Prop<T>;
26}
27
28/// A builder that takes child elements: built-in containers and components
29/// with a `children: Element` argument.
30#[diagnostic::on_unimplemented(
31    message = "`{Self}` takes no child elements",
32    label = "this widget takes no children",
33    note = "containers (`View`, `Stack`, `Card`) and components with a `children: Element` argument take children"
34)]
35pub trait Children: Sized {
36    /// Appends a child.
37    fn __child(self, child: Element) -> Self;
38}
39
40/// A child in `ui!`: `Card { Text { .. } }`.
41pub fn child<B: Children>(builder: B, child: Element) -> B {
42    builder.__child(child)
43}
44
45/// A value a property of type `T` takes: `T` itself, or a string slice for
46/// `String`. Deliberately narrower than `Into`, so that unsuffixed literals
47/// take the property's type (`font_weight: 700` is a `u16`, `grow: 1.0` an
48/// `f32`) instead of defaulting to `i32`/`f64`.
49#[diagnostic::on_unimplemented(
50    message = "`{Self}` is not a value for this property, which takes `{T}`",
51    label = "expected a `{T}` value"
52)]
53pub trait PropValue<T> {
54    /// The value.
55    fn into_value(self) -> T;
56}
57
58impl<T> PropValue<T> for T {
59    fn into_value(self) -> T {
60        self
61    }
62}
63
64impl PropValue<String> for &str {
65    fn into_value(self) -> String {
66        self.to_owned()
67    }
68}
69
70impl PropValue<String> for &String {
71    fn into_value(self) -> String {
72        self.clone()
73    }
74}
75
76/// A source literal in `ui!` (`16px`, `"Save"`, `true`): like [`Lit`], and
77/// the same wherever this place is built (see [`crate::element::Site`]).
78#[doc(hidden)]
79#[derive(Clone, Copy, Debug)]
80pub struct Const<V>(pub V);
81
82impl<T, V: PropValue<T>> IntoProp<T> for Const<V> {
83    fn into_prop(self) -> crate::element::Prop<T> {
84        crate::element::Prop::Const(self.0.into_value())
85    }
86}
87
88impl<T, V: PropValue<T>> IntoArg<T> for Const<V> {
89    fn into_arg(self) -> T {
90        self.0.into_value()
91    }
92}
93
94/// A builder that records where it was written (built-in widgets; a
95/// component's builder ignores it — its own `ui!` has its own places).
96pub trait Sited: Sized {
97    /// Records the place.
98    fn __site(self, site: &'static crate::element::Site) -> Self;
99}
100
101/// The place of a widget in `ui!`.
102pub fn site<B: Sited>(builder: B, site: &'static crate::element::Site) -> B {
103    builder.__site(site)
104}
105
106impl<T, V: PropValue<T>> IntoProp<T> for Lit<V> {
107    fn into_prop(self) -> crate::element::Prop<T> {
108        crate::element::Prop::Static(self.0.into_value())
109    }
110}
111
112impl<T: 'static, V: PropValue<T>, F: FnOnce() -> V + Clone + 'static> IntoProp<T> for Dyn<F> {
113    fn into_prop(self) -> crate::element::Prop<T> {
114        let f = self.0;
115        crate::element::Prop::Dynamic(Rc::new(move || (f.clone())().into_value()))
116    }
117}
118
119/// What a component's property accepts: evaluated when the component is
120/// (re)built, inside its region, so reading a signal rebuilds it.
121pub trait IntoArg<T> {
122    /// The value.
123    fn into_arg(self) -> T;
124}
125
126impl<T, V: PropValue<T>> IntoArg<T> for Lit<V> {
127    fn into_arg(self) -> T {
128        self.0.into_value()
129    }
130}
131
132impl<T, V: PropValue<T>, F: FnOnce() -> V> IntoArg<T> for Dyn<F> {
133    fn into_arg(self) -> T {
134        (self.0)().into_value()
135    }
136}
137
138/// A finished widget or component builder.
139pub trait Build {
140    /// Whether the builder is a component (rebuilt as a region when its
141    /// properties change) rather than a built-in widget (whose properties
142    /// update in place).
143    const REGION: bool;
144
145    /// The element.
146    fn build(self) -> Element;
147}
148
149/// `Tag { .. }` in `ui!`.
150pub fn element<B: Build, F: FnOnce() -> B + Clone + 'static>(f: F) -> Element {
151    if B::REGION {
152        Element(Node::Region(Rc::new(move || (f.clone())().build())))
153    } else {
154        f().build()
155    }
156}
157
158/// `if` in `ui!` (and any reactive region).
159pub fn region<F: FnOnce() -> Element + Clone + 'static>(f: F) -> Element {
160    Element(Node::Region(Rc::new(move || (f.clone())())))
161}
162
163/// `for pat in items { key: k, .. }` in `ui!`. Items keep their view while
164/// their key and value stay the same; a changed value under the same key
165/// rebuilds that item only.
166pub fn keyed<T, I, K, FI, FK, FR>(items: FI, key: FK, render: FR) -> Element
167where
168    T: Clone + PartialEq + 'static,
169    I: IntoIterator<Item = T>,
170    K: Hash,
171    FI: FnOnce() -> I + Clone + 'static,
172    FK: Fn(&T) -> K + 'static,
173    FR: FnOnce(T) -> Element + Clone + 'static,
174{
175    Element(Node::Keyed(Rc::new(Keyed {
176        items: Box::new(move || {
177            let mut seen = std::collections::HashMap::<u64, u32>::new();
178            (items.clone())()
179                .into_iter()
180                .map(|item| {
181                    let mut k = key_hash(&key(&item));
182                    // A repeated key gets a distinct identity per occurrence.
183                    let n = seen.entry(k).or_default();
184                    if *n > 0 {
185                        k = key_hash(&(k, *n));
186                    }
187                    *n += 1;
188                    let render = render.clone();
189                    KeyedItem {
190                        key: k,
191                        value: Rc::new(item.clone()),
192                        same: same::<T>,
193                        build: Box::new(move || render(item)),
194                    }
195                })
196                .collect()
197        }),
198    })))
199}
200
201fn same<T: PartialEq + 'static>(a: &dyn std::any::Any, b: &dyn std::any::Any) -> bool {
202    matches!((a.downcast_ref::<T>(), b.downcast_ref::<T>()), (Some(a), Some(b)) if a == b)
203}
204
205/// Several `ui!` nodes.
206pub fn fragment(children: Vec<Element>) -> Element {
207    Element::fragment(children)
208}
209
210/// Typestate marker: a required component property not set yet.
211#[derive(Debug, Clone, Copy, Default)]
212pub struct Unset;
213
214/// Typestate marker: a required component property set.
215#[derive(Debug, Clone, Copy, Default)]
216pub struct Set;
217
218/// Wraps a `FnOnce + Clone` closure as a reusable `Fn`.
219pub fn reuse0(f: impl FnOnce() + Clone + 'static) -> Rc<dyn Fn()> {
220    Rc::new(move || (f.clone())())
221}
222
223/// Wraps a one-argument `FnOnce + Clone` closure as a reusable `Fn`.
224pub fn reuse1<A: 'static>(f: impl FnOnce(A) + Clone + 'static) -> Rc<dyn Fn(A)> {
225    Rc::new(move |a| (f.clone())(a))
226}