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. Inside a `grid_row` the
201/// anchor keeps its column as an empty cell (docs/grid.md "Spanning and empty cells"), so an
202/// absent value does not shift the cells after it.
203///
204/// ```ignore
205/// let precip = (d.precip > 0).then(|| label(format!("{}%", d.precip)));
206/// row((icon, precip))
207/// ```
208///
209/// Resolved once at build. For an `Option` that changes while the piece lives, use
210/// `keyed(move || state.get(), |v| …)`.
211impl<P: Piece> Piece for Option<P> {
212 fn build(self, cx: &mut BuildCx) -> RNode {
213 match self {
214 Some(p) => p.build(cx),
215 None => cx.layout_only(
216 Rc::new(crate::layout::PassThrough),
217 Flex {
218 is_group: true,
219 grid: crate::tree::GridFacts {
220 holds_cell: true,
221 ..Default::default()
222 },
223 ..Default::default()
224 },
225 Boundary::No,
226 ),
227 }
228 }
229}
230
231#[cfg(test)]
232mod any_piece_tests {
233 use super::*;
234 use slotmap::Key as _;
235
236 fn box_addr(p: &AnyPiece) -> *const () {
237 std::ptr::from_ref::<dyn FnOnce(&mut BuildCx) -> RNode>(&*p.0).cast::<()>()
238 }
239
240 /// `.any()` on an already-erased piece hands the same allocation back. Guards the inherent
241 /// method against being deleted as "redundant with `Decorate::any`": it is what stops a
242 /// second box, and method resolution silently falls back to the blanket trait without it.
243 #[test]
244 fn any_on_an_erased_piece_reuses_its_box() {
245 let p = AnyPiece::new(piece_fn(|_| RNode::null()));
246 let before = box_addr(&p);
247 let p = p.any();
248 assert_eq!(before, box_addr(&p));
249 }
250}
251
252// ---------------------------------------------------------------------------
253// PieceSeq: tuple children (§5.1), flattening recursively.
254// ---------------------------------------------------------------------------
255
256/// Children of a container (§5.1): a tuple of pieces (the floem `ViewTuple` pattern), a
257/// `Vec` or array of one piece type, or an `Option` of a piece. Implemented for exactly those
258/// shapes, never via a blanket, to stay coherent. All of them are build-time children:
259/// evaluated once when the parent builds, with no keyed identity or reconciliation. A child
260/// that must come and go at runtime is a [`when`](/api/day_pieces/fn.when.html), a
261/// `keyed`, or an `each`.
262pub trait PieceSeq: 'static {
263 fn build_each(self, cx: &mut BuildCx);
264}
265
266impl PieceSeq for () {
267 fn build_each(self, _cx: &mut BuildCx) {}
268}
269
270/// A homogeneous list of children, which is also how a runtime-heterogeneous list reads:
271/// `row(items.iter().map(cell).collect::<Vec<_>>())`, or a `Vec<AnyPiece>` when the children
272/// differ in type.
273impl<P: Piece> PieceSeq for Vec<P> {
274 fn build_each(self, cx: &mut BuildCx) {
275 for p in self {
276 let _ = p.build(cx);
277 }
278 }
279}
280
281impl<P: Piece, const N: usize> PieceSeq for [P; N] {
282 fn build_each(self, cx: &mut BuildCx) {
283 for p in self {
284 let _ = p.build(cx);
285 }
286 }
287}
288
289/// A child that may be absent: `None` builds nothing at all (no node).
290impl<P: Piece> PieceSeq for Option<P> {
291 fn build_each(self, cx: &mut BuildCx) {
292 if let Some(p) = self {
293 let _ = p.build(cx);
294 }
295 }
296}
297
298macro_rules! impl_piece_seq {
299 ($($name:ident),+) => {
300 impl<$($name: Piece),+> PieceSeq for ($($name,)+) {
301 #[allow(non_snake_case)]
302 fn build_each(self, cx: &mut BuildCx) {
303 let ($($name,)+) = self;
304 $(let _ = $name.build(cx);)+
305 }
306 }
307 };
308}
309
310impl_piece_seq!(A);
311impl_piece_seq!(A, B);
312impl_piece_seq!(A, B, C);
313impl_piece_seq!(A, B, C, D);
314impl_piece_seq!(A, B, C, D, E);
315impl_piece_seq!(A, B, C, D, E, F);
316impl_piece_seq!(A, B, C, D, E, F, G);
317impl_piece_seq!(A, B, C, D, E, F, G, H);
318impl_piece_seq!(A, B, C, D, E, F, G, H, I);
319impl_piece_seq!(A, B, C, D, E, F, G, H, I, J);
320impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K);
321impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L);
322impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M);
323impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
324impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
325impl_piece_seq!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, Q);