Skip to main content

day_core/
build.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The build layer (DESIGN.md §5.1–§5.2): pieces are descriptions consumed exactly once.
5//! `BuildCx` holds no tree borrow; every operation goes through `with_tree`, so bindings
6//! and structural effects created during build can re-enter safely.
7
8use std::any::Any;
9use std::rc::Rc;
10
11use day_reactive::Scope;
12use day_spec::{Event, PieceKind};
13
14use crate::layout::Layout;
15use crate::tree::{Flex, RNode, with_tree};
16
17/// Measure-invalidation boundary (§7.4): `Yes` stops upward needs-measure propagation
18/// (scroll viewports, nav pages). Named enum instead of a bare bool at call sites
19/// (docs/api-style.md).
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub enum Boundary {
22    No,
23    Yes,
24}
25
26pub struct BuildCx {
27    parent: RNode,
28}
29
30impl BuildCx {
31    #[must_use]
32    pub fn new(parent: RNode) -> Self {
33        BuildCx { parent }
34    }
35
36    #[must_use]
37    pub fn parent(&self) -> RNode {
38        self.parent
39    }
40
41    /// Create + attach a native leaf.
42    pub fn leaf(&mut self, kind: PieceKind, props: &dyn Any, flex: Flex) -> RNode {
43        let n = with_tree(|t| {
44            t.create_node(
45                kind,
46                props,
47                Rc::new(crate::layout::LeafLayout),
48                flex,
49                true,
50                false,
51                Scope::current(),
52            )
53        });
54        with_tree(|t| t.attach(self.parent, n));
55        n
56    }
57
58    /// Create + attach a native node with a custom layout (containers, scroll).
59    pub fn native(
60        &mut self,
61        kind: PieceKind,
62        props: &dyn Any,
63        layout: Rc<dyn Layout>,
64        flex: Flex,
65        boundary: Boundary,
66    ) -> RNode {
67        let n = with_tree(|t| {
68            t.create_node(
69                kind,
70                props,
71                layout,
72                flex,
73                true,
74                boundary == Boundary::Yes,
75                Scope::current(),
76            )
77        });
78        with_tree(|t| t.attach(self.parent, n));
79        n
80    }
81
82    /// Create + attach a layout-only node (wrappers, groups, spacer).
83    pub fn layout_only(&mut self, layout: Rc<dyn Layout>, flex: Flex, boundary: Boundary) -> RNode {
84        let n = with_tree(|t| {
85            t.create_node(
86                "day.layout",
87                &(),
88                layout,
89                flex,
90                false,
91                boundary == Boundary::Yes,
92                Scope::current(),
93            )
94        });
95        with_tree(|t| t.attach(self.parent, n));
96        n
97    }
98
99    /// Build `f` with `node` as the parent.
100    pub fn under<R>(&mut self, node: RNode, f: impl FnOnce(&mut BuildCx) -> R) -> R {
101        let mut cx = BuildCx { parent: node };
102        f(&mut cx)
103    }
104
105    /// Register a native-event handler for a node (runs under the registration scope, §4.3).
106    pub fn on(&mut self, node: RNode, h: impl Fn(&Event) + 'static) {
107        let scope = Scope::current();
108        let wrapped: Rc<dyn Fn(&Event)> = Rc::new(move |ev| {
109            if scope.is_alive() {
110                let ev = ev.clone();
111                scope.enter(|| h(&ev));
112            }
113        });
114        with_tree(|t| t.on_event(node, wrapped));
115    }
116}
117
118// ---------------------------------------------------------------------------
119// Piece
120// ---------------------------------------------------------------------------
121
122/// A UI description consumed once (§5.2). Returns the root realized node it created.
123pub trait Piece: 'static {
124    fn build(self, cx: &mut BuildCx) -> RNode;
125}
126
127/// Type-erased piece for heterogeneous branches and dynamic construction.
128#[must_use]
129pub struct AnyPiece(Box<dyn FnOnce(&mut BuildCx) -> RNode>);
130
131impl AnyPiece {
132    pub fn new<P: Piece>(p: P) -> Self {
133        AnyPiece(Box::new(move |cx| p.build(cx)))
134    }
135
136    /// Already erased: hands itself back instead of boxing a box.
137    ///
138    /// Inherent so it shadows the blanket `Decorate::any` (inherent methods win method
139    /// resolution). Every `Decorate` modifier returns an erased piece, so `.padding(8.0).any()`
140    /// and friends are common in app code and would otherwise pay a second allocation and a
141    /// second indirect call for nothing.
142    pub fn any(self) -> AnyPiece {
143        self
144    }
145}
146
147impl Piece for AnyPiece {
148    fn build(self, cx: &mut BuildCx) -> RNode {
149        (self.0)(cx)
150    }
151}
152
153/// A closure kept as a concrete piece: the deferral primitive (§5.2).
154///
155/// A piece that must read something only available at build time (an ambient `environment`, a
156/// scope, the laid-out size) defers its body into a closure. Deferring is not erasing: this
157/// newtype carries the closure inline, so the constructors built on [`piece_fn`] can return
158/// `impl Piece` and keep the caller's type concrete. Erase with `.any()` where a
159/// heterogeneous collection or a stored callback needs it.
160pub struct PieceFn<F>(F);
161
162impl<F: FnOnce(&mut BuildCx) -> RNode + 'static> Piece for PieceFn<F> {
163    fn build(self, cx: &mut BuildCx) -> RNode {
164        (self.0)(cx)
165    }
166}
167
168/// A piece from a closure, built when the tree reaches it.
169pub fn piece_fn<F: FnOnce(&mut BuildCx) -> RNode + 'static>(f: F) -> PieceFn<F> {
170    PieceFn(f)
171}
172
173/// A build-time branch between two piece TYPES, without erasing either (§5.1).
174///
175/// `if compact { a.any() } else { b.any() }` boxes whichever arm it takes; `Either` keeps both
176/// concrete, so the branch costs nothing and the chosen arm's type survives into the parent:
177///
178/// ```ignore
179/// if compact { Either::Left(row(children)) } else { Either::Right(column(children)) }
180/// ```
181///
182/// For a branch on a signal, one that must re-evaluate, use `when(…).otherwise(…)` instead.
183/// This is a plain `if` resolved once at build.
184pub enum Either<A, B> {
185    Left(A),
186    Right(B),
187}
188
189impl<A: Piece, B: Piece> Piece for Either<A, B> {
190    fn build(self, cx: &mut BuildCx) -> RNode {
191        match self {
192            Either::Left(a) => a.build(cx),
193            Either::Right(b) => b.build(cx),
194        }
195    }
196}
197
198/// An optional piece (§5.1): `Some` builds the piece, `None` builds the same zero-size,
199/// layout-transparent anchor a false [`when`](/api/day_pieces/fn.when.html) leaves behind, so
200/// the slot keeps its place in a tuple without drawing anything.
201///
202/// ```ignore
203/// let precip = (d.precip > 0).then(|| label(format!("{}%", d.precip)));
204/// row((icon, precip))
205/// ```
206///
207/// Resolved once at build. For an `Option` that changes while the piece lives, use
208/// `keyed(move || state.get(), |v| …)`.
209impl<P: Piece> Piece for Option<P> {
210    fn build(self, cx: &mut BuildCx) -> RNode {
211        match self {
212            Some(p) => p.build(cx),
213            None => cx.layout_only(
214                Rc::new(crate::layout::PassThrough),
215                Flex {
216                    is_group: true,
217                    ..Default::default()
218                },
219                Boundary::No,
220            ),
221        }
222    }
223}
224
225#[cfg(test)]
226mod any_piece_tests {
227    use super::*;
228    use slotmap::Key as _;
229
230    fn box_addr(p: &AnyPiece) -> *const () {
231        std::ptr::from_ref::<dyn FnOnce(&mut BuildCx) -> RNode>(&*p.0).cast::<()>()
232    }
233
234    /// `.any()` on an already-erased piece hands the same allocation back. Guards the inherent
235    /// method against being deleted as "redundant with `Decorate::any`": it is what stops a
236    /// second box, and method resolution silently falls back to the blanket trait without it.
237    #[test]
238    fn any_on_an_erased_piece_reuses_its_box() {
239        let p = AnyPiece::new(piece_fn(|_| RNode::null()));
240        let before = box_addr(&p);
241        let p = p.any();
242        assert_eq!(before, box_addr(&p));
243    }
244}
245
246// ---------------------------------------------------------------------------
247// PieceSeq: tuple children (§5.1), flattening recursively.
248// ---------------------------------------------------------------------------
249
250/// Children of a container (§5.1): a tuple of pieces (the floem `ViewTuple` pattern), a
251/// `Vec` or array of one piece type, or an `Option` of a piece. Implemented for exactly those
252/// shapes, never via a blanket, to stay coherent. All of them are build-time children:
253/// evaluated once when the parent builds, with no keyed identity or reconciliation. A child
254/// that must come and go at runtime is a [`when`](/api/day_pieces/fn.when.html), a
255/// `keyed`, or an `each`.
256pub trait PieceSeq: 'static {
257    fn build_each(self, cx: &mut BuildCx);
258}
259
260impl PieceSeq for () {
261    fn build_each(self, _cx: &mut BuildCx) {}
262}
263
264/// A homogeneous list of children, which is also how a runtime-heterogeneous list reads:
265/// `row(items.iter().map(cell).collect::<Vec<_>>())`, or a `Vec<AnyPiece>` when the children
266/// differ in type.
267impl<P: Piece> PieceSeq for Vec<P> {
268    fn build_each(self, cx: &mut BuildCx) {
269        for p in self {
270            let _ = p.build(cx);
271        }
272    }
273}
274
275impl<P: Piece, const N: usize> PieceSeq for [P; N] {
276    fn build_each(self, cx: &mut BuildCx) {
277        for p in self {
278            let _ = p.build(cx);
279        }
280    }
281}
282
283/// A child that may be absent: `None` builds nothing at all (no node).
284impl<P: Piece> PieceSeq for Option<P> {
285    fn build_each(self, cx: &mut BuildCx) {
286        if let Some(p) = self {
287            let _ = p.build(cx);
288        }
289    }
290}
291
292macro_rules! impl_piece_seq {
293    ($($name:ident),+) => {
294        impl<$($name: Piece),+> PieceSeq for ($($name,)+) {
295            #[allow(non_snake_case)]
296            fn build_each(self, cx: &mut BuildCx) {
297                let ($($name,)+) = self;
298                $(let _ = $name.build(cx);)+
299            }
300        }
301    };
302}
303
304impl_piece_seq!(A);
305impl_piece_seq!(A, B);
306impl_piece_seq!(A, B, C);
307impl_piece_seq!(A, B, C, D);
308impl_piece_seq!(A, B, C, D, E);
309impl_piece_seq!(A, B, C, D, E, F);
310impl_piece_seq!(A, B, C, D, E, F, G);
311impl_piece_seq!(A, B, C, D, E, F, G, H);
312impl_piece_seq!(A, B, C, D, E, F, G, H, I);
313impl_piece_seq!(A, B, C, D, E, F, G, H, I, J);
314impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K);
315impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L);
316impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M);
317impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
318impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
319impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, Q);