Skip to main content

day_pieces/
containers.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Layout containers that arrange child pieces: `column`, `row`, `grid`/`grid_row`, `scroll`,
5//! and `zstack`, together with the `HAlign`/`VAlign` alignment enums.
6
7use std::rc::Rc;
8
9use day_core::*;
10use day_reactive::{AnyBinding, Binding, watch};
11use day_spec::kinds;
12use day_spec::props::*;
13
14use crate::Decorated;
15
16// ---------------------------------------------------------------------------
17// Containers
18// ---------------------------------------------------------------------------
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum HAlign {
22    Leading,
23    #[default]
24    Center,
25    Trailing,
26}
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum VAlign {
29    Top,
30    #[default]
31    Center,
32    Bottom,
33    /// Sit the children's text on one line rather than centering their boxes
34    /// (docs/baseline.md), which is what a label beside a bordered field or a larger-type value
35    /// wants, since those put their text at different heights inside their boxes. A child with no
36    /// text (an image, a slider) has no baseline and stays centered. Rows only; on a `column`
37    /// it reads as `Center`.
38    FirstBaseline,
39}
40
41pub struct Column<C: PieceSeq> {
42    children: C,
43    spacing: f64,
44    align: CrossAlign,
45}
46
47pub fn column<C: PieceSeq>(children: C) -> Column<C> {
48    Column {
49        children,
50        spacing: 0.0,
51        align: CrossAlign::Center,
52    }
53}
54
55#[day_macros::builder(ColumnBuilder)]
56impl<C: PieceSeq> Column<C> {
57    /// The gap between children: a [`Space`](crate::Space) step or points.
58    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
59        self.spacing = s.into();
60        self
61    }
62    pub fn align(mut self, a: HAlign) -> Self {
63        self.align = match a {
64            HAlign::Leading => CrossAlign::Leading,
65            HAlign::Center => CrossAlign::Center,
66            HAlign::Trailing => CrossAlign::Trailing,
67        };
68        self
69    }
70}
71
72impl<C: PieceSeq> Piece for Column<C> {
73    fn build(self, cx: &mut BuildCx) -> RNode {
74        let node = cx.native(
75            kinds::CONTAINER,
76            &ContainerProps::default(),
77            Rc::new(StackLayout {
78                axis: Axis::Vertical,
79                spacing: self.spacing,
80                align: self.align,
81            }),
82            Flex::default(),
83            Boundary::No,
84        );
85        cx.under(node, |cx| self.children.build_each(cx));
86        node
87    }
88}
89
90/// How a [`row`] treats content wider than the window it is in
91/// (docs/size-classes.md "Row fit policies").
92///
93/// A row's children negotiate one line; the fit policy is what happens when that line is
94/// wider than the space the row is given. Every policy keeps the same children and the same
95/// call shape, `row((…)).fit(…)`, so a page can move between them as its needs change. A row
96/// that should become a column on a narrow window is [`adaptive`](crate::adaptive), a piece of
97/// its own.
98#[derive(Clone, Copy, Debug, Default, PartialEq)]
99pub enum RowFit {
100    /// One line at natural sizes; what does not fit lands offscreen. The default, and the
101    /// right contract for a label beside a value. Debug builds log the overflow once per
102    /// container, naming the dayscript ids in reach.
103    #[default]
104    Clip,
105    /// Break onto additional lines where the next child would overflow, like wrapped text:
106    /// the shape a chip row or button strip wants. `run_spacing` is the vertical gap between
107    /// lines. Wrapping replaces main-axis negotiation, so `.grow(Dimension::Both)` and `spacer()` are inert.
108    Wrap { run_spacing: f64 },
109    /// Wrap into aligned columns rather than ragged lines: every cell takes the widest
110    /// child's width, and each line holds as many as the window fits. The tidier arm of
111    /// [`Wrap`](RowFit::Wrap): same wrapping, but the lines stack into a grid, which is what
112    /// a set of peer choices (a keypad, a palette, evenly-weighted chips) wants. The column
113    /// count follows the available width. When any child grows (`.grow(Dimension::Width)`), the widest child
114    /// becomes the narrowest a column gets and the columns stretch to share the whole width,
115    /// the adaptive grid a gallery of tiles wants. No cell is wider than the line: on a window
116    /// narrower than the widest child, the cells take its width and their text wraps. An
117    /// authored, fixed column count with
118    /// per-cell spans is [`grid`]'s job instead (docs/grid.md).
119    WrapColumns { run_spacing: f64 },
120    /// Keep the single line and make it a horizontal scroll strip instead of clipping. The
121    /// strip stays one row tall and fills the width it is given.
122    Scroll,
123}
124
125pub struct Row<C: PieceSeq> {
126    children: C,
127    spacing: f64,
128    align: CrossAlign,
129    fit: RowFit,
130}
131
132pub fn row<C: PieceSeq>(children: C) -> Row<C> {
133    Row {
134        children,
135        spacing: 0.0,
136        align: CrossAlign::Center,
137        fit: RowFit::Clip,
138    }
139}
140
141#[day_macros::builder(RowBuilder)]
142impl<C: PieceSeq> Row<C> {
143    /// The gap between children: a [`Space`](crate::Space) step or points.
144    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
145        self.spacing = s.into();
146        self
147    }
148    pub fn align(mut self, a: VAlign) -> Self {
149        self.align = match a {
150            VAlign::Top => CrossAlign::Leading,
151            VAlign::Center => CrossAlign::Center,
152            VAlign::Bottom => CrossAlign::Trailing,
153            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
154        };
155        self
156    }
157    /// What happens when the children outgrow the row's width (docs/size-classes.md).
158    pub fn fit(mut self, fit: RowFit) -> Self {
159        self.fit = fit;
160        self
161    }
162}
163
164impl<C: PieceSeq> Row<C> {
165    /// The plain one-line container every policy bottoms out in.
166    fn build_line(self, cx: &mut BuildCx, axis: Axis, align: CrossAlign) -> RNode {
167        let node = cx.native(
168            kinds::CONTAINER,
169            &ContainerProps::default(),
170            Rc::new(StackLayout {
171                axis,
172                spacing: self.spacing,
173                align,
174            }),
175            Flex::default(),
176            Boundary::No,
177        );
178        cx.under(node, |cx| self.children.build_each(cx));
179        node
180    }
181}
182
183impl<C: PieceSeq> Piece for Row<C> {
184    fn build(self, cx: &mut BuildCx) -> RNode {
185        match self.fit {
186            RowFit::Clip => {
187                let align = self.align;
188                self.build_line(cx, Axis::Horizontal, align)
189            }
190            RowFit::Wrap { run_spacing } | RowFit::WrapColumns { run_spacing } => {
191                let node = cx.native(
192                    kinds::CONTAINER,
193                    &ContainerProps::default(),
194                    Rc::new(FlowLayout {
195                        spacing: self.spacing,
196                        run_spacing,
197                        align: self.align,
198                        uniform: matches!(self.fit, RowFit::WrapColumns { .. }),
199                    }),
200                    Flex::default(),
201                    Boundary::No,
202                );
203                cx.under(node, |cx| self.children.build_each(cx));
204                node
205            }
206            RowFit::Scroll => {
207                // The row keeps its natural one-line measure inside a horizontal scroll
208                // viewport. `grow_h` stays off: the strip is as tall as the row, not as
209                // tall as whatever pane it happens to sit in.
210                let strip = cx.native(
211                    kinds::SCROLL,
212                    &day_spec::props::ScrollProps { horizontal: true },
213                    Rc::new(ScrollLayout {
214                        axis: Axis::Horizontal,
215                    }),
216                    Flex {
217                        grow_w: true,
218                        ..Default::default()
219                    },
220                    Boundary::Yes, // scroll viewports are layout boundaries (§7.4)
221                );
222                cx.under(strip, |cx| {
223                    let align = self.align;
224                    let _ = self.build_line(cx, Axis::Horizontal, align);
225                });
226                strip
227            }
228        }
229    }
230}
231
232pub struct Grid<C: PieceSeq> {
233    children: C,
234    row_spacing: f64,
235    column_spacing: f64,
236    align: Alignment,
237}
238
239/// A SwiftUI-style eager grid (docs/grid.md): columns are inferred from [`grid_row`] children.
240/// A column is as wide as its widest cell, a `grow_w` cell makes its column share the leftover
241/// width evenly, and a non-row child becomes a full-width cell spanning every column. `spacer()`
242/// inside a row is an inert empty cell that still occupies its column (a grid has explicit
243/// gutters, so stack-style push-apart spacers don't apply). Cells opt into spans and per-cell
244/// alignment with [`Decorated::grid_span`](crate::decorators::Decorated::grid_span) / [`Decorate::grid_align`](crate::decorators::Decorate::grid_align).
245pub fn grid<C: PieceSeq>(children: C) -> Grid<C> {
246    Grid {
247        children,
248        row_spacing: 0.0,
249        column_spacing: 0.0,
250        align: Alignment::Center,
251    }
252}
253
254#[day_macros::builder(GridBuilder)]
255impl<C: PieceSeq> Grid<C> {
256    /// Set both the row and column gutters: a [`Space`](crate::Space) step or points.
257    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
258        let s = s.into();
259        self.row_spacing = s;
260        self.column_spacing = s;
261        self
262    }
263    pub fn row_spacing(mut self, s: impl Into<f64>) -> Self {
264        self.row_spacing = s.into();
265        self
266    }
267    pub fn column_spacing(mut self, s: impl Into<f64>) -> Self {
268        self.column_spacing = s.into();
269        self
270    }
271    /// Default alignment of every cell within its cell rect (cell/row overrides win).
272    pub fn align(mut self, a: Alignment) -> Self {
273        self.align = a;
274        self
275    }
276}
277
278impl<C: PieceSeq> Piece for Grid<C> {
279    fn build(self, cx: &mut BuildCx) -> RNode {
280        let node = cx.native(
281            kinds::CONTAINER,
282            &ContainerProps::default(),
283            Rc::new(GridLayout {
284                row_spacing: self.row_spacing,
285                column_spacing: self.column_spacing,
286                align: self.align,
287            }),
288            Flex::default(),
289            Boundary::No,
290        );
291        cx.under(node, |cx| self.children.build_each(cx));
292        node
293    }
294}
295
296pub struct GridRow<C: PieceSeq> {
297    children: C,
298    valign: Option<CrossAlign>,
299}
300
301/// One row of a [`grid`]: each child is a cell, assigned to columns left to right. Outside a
302/// grid a row degrades gracefully to a plain [`row`]. Rows are transparent carriers (the grid
303/// places their cells directly), so decorating a `grid_row` itself is unsupported (decorate the
304/// cells, or the grid).
305pub fn grid_row<C: PieceSeq>(children: C) -> GridRow<C> {
306    GridRow {
307        children,
308        valign: None,
309    }
310}
311
312#[day_macros::builder(GridRowBuilder)]
313impl<C: PieceSeq> GridRow<C> {
314    /// Vertical alignment override for this row's cells (the grid's alignment applies otherwise).
315    pub fn align(mut self, a: VAlign) -> Self {
316        self.valign = Some(match a {
317            VAlign::Top => CrossAlign::Leading,
318            VAlign::Center => CrossAlign::Center,
319            VAlign::Bottom => CrossAlign::Trailing,
320            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
321        });
322        self
323    }
324}
325
326impl<C: PieceSeq> Piece for GridRow<C> {
327    fn build(self, cx: &mut BuildCx) -> RNode {
328        // A layout-only node whose StackLayout only runs when the row is not inside a grid
329        // (the graceful-degrade path); a grid introspects the cells and places them itself.
330        let node = cx.layout_only(
331            Rc::new(StackLayout {
332                axis: Axis::Horizontal,
333                spacing: 0.0,
334                align: self.valign.unwrap_or_default(),
335            }),
336            Flex {
337                grid: GridFacts {
338                    is_row: true,
339                    row_valign: self.valign,
340                    ..Default::default()
341                },
342                ..Default::default()
343            },
344            Boundary::No,
345        );
346        cx.under(node, |cx| self.children.build_each(cx));
347        node
348    }
349}
350
351pub struct Scroll<P: Piece> {
352    child: P,
353    axis: Axis,
354    target: Option<AnyBinding<Option<day_core::ScrollTarget>>>,
355}
356
357pub fn scroll<P: Piece>(child: P) -> Scroll<P> {
358    Scroll {
359        child,
360        axis: Axis::Vertical,
361        target: None,
362    }
363}
364
365#[day_macros::builder(ScrollBuilder)]
366impl<P: Piece> Scroll<P> {
367    /// Scroll horizontally instead of vertically (a filmstrip of cards, a chip row). The content
368    /// is measured unconstrained on the horizontal axis and the native view scrolls sideways.
369    pub fn horizontal(mut self) -> Self {
370        self.axis = Axis::Horizontal;
371        self
372    }
373    /// Set the scroll axis explicitly.
374    pub fn axis(mut self, axis: Axis) -> Self {
375        self.axis = axis;
376        self
377    }
378
379    /// Programmatic scrolling (docs/scroll.md): each `Some(target)` written to `sig` scrolls
380    /// there (animated), then the signal resets to `None`. Write-and-forget, so the same
381    /// target can be sent twice in a row.
382    ///
383    /// ```ignore
384    /// let jump = Signal::new(None);
385    /// scroll(rows).scroll_target(jump);
386    /// button("Bottom").action(move || jump.set(Some(ScrollTarget::Bottom)));
387    /// ```
388    pub fn scroll_target(mut self, target: impl Binding<Option<day_core::ScrollTarget>>) -> Self {
389        self.target = Some(AnyBinding::new(target));
390        self
391    }
392}
393
394impl<P: Piece> Piece for Scroll<P> {
395    fn build(self, cx: &mut BuildCx) -> RNode {
396        let node = cx.native(
397            kinds::SCROLL,
398            &day_spec::props::ScrollProps {
399                horizontal: matches!(self.axis, Axis::Horizontal),
400            },
401            Rc::new(ScrollLayout { axis: self.axis }),
402            Flex {
403                grow_w: true,
404                grow_h: true,
405                ..Default::default()
406            },
407            Boundary::Yes, // scroll viewports are layout boundaries (§7.4)
408        );
409        cx.under(node, |cx| {
410            let _ = self.child.build(cx);
411        });
412        if let Some(sig) = self.target {
413            watch(
414                move || sig.get(),
415                move |now, _| {
416                    if let Some(t) = now.clone() {
417                        // Deferred one main-loop turn: this watch runs inside the reactive
418                        // flush, before the turn-end layout that resizes the scroll content;
419                        // an edge target (Bottom/Trailing) computed now would land on the
420                        // stale content size.
421                        day_reactive::on_main(move || {
422                            day_core::with_tree(|tr| {
423                                tr.scroll_to_target(node, &t, true);
424                            });
425                        });
426                        sig.set(None); // consumed, ready for the next command
427                    }
428                },
429            );
430        }
431        node
432    }
433}
434
435/// A z-stack: children are layered back-to-front (the first child sits at the bottom), all
436/// sharing the container bounds and positioned by the stack's [`Alignment`]. The stack sizes to
437/// the union (max width/height) of its children; contrast [`Decorate::overlay`](crate::decorators::Decorate::overlay), which sizes to
438/// its content and treats the overlaid piece as a non-sizing annotation. Pure composition: it is
439/// the same native panel as [`column()`]/[`row()`], so there is no per-backend work.
440pub struct ZStack<C: PieceSeq> {
441    children: C,
442    align: Alignment,
443}
444
445/// Build a [`ZStack`] from a tuple, `Vec` or array of children.
446pub fn zstack<C: PieceSeq>(children: C) -> ZStack<C> {
447    ZStack {
448        children,
449        align: Alignment::Center,
450    }
451}
452
453#[day_macros::builder(ZStackBuilder)]
454impl<C: PieceSeq> ZStack<C> {
455    /// Where children sit within the stack's bounds (default [`Alignment::Center`]).
456    pub fn align(mut self, a: Alignment) -> Self {
457        self.align = a;
458        self
459    }
460}
461
462impl<C: PieceSeq> Piece for ZStack<C> {
463    fn build(self, cx: &mut BuildCx) -> RNode {
464        let node = cx.native(
465            kinds::CONTAINER,
466            &ContainerProps::default(),
467            Rc::new(OverlayLayout {
468                align: self.align,
469                size_to_first: false,
470            }),
471            Flex::default(),
472            Boundary::No,
473        );
474        cx.under(node, |cx| self.children.build_each(cx));
475        node
476    }
477}
478
479// ---------------------------------------------------------------------------
480// Conformance cases (docs/testing.md)
481// ---------------------------------------------------------------------------
482
483/// The containers' `#[day::test]` cases, next to their constructors.
484#[cfg(feature = "conformance")]
485pub(crate) mod conformance {
486    use day_core::conformance::{Case, Drive, FrameExpect};
487    use day_core::{AnyPiece, ScrollTarget};
488    use day_reactive::Signal;
489    use day_spec::{Color, kinds};
490
491    use crate::*;
492
493    fn block(color: Color, id: day_core::ElementId, w: f64, h: f64) -> AnyPiece {
494        rectangle().fill(color).id(id).frame(w, h).any()
495    }
496
497    fn at(relative_to: &str, x: Option<f64>, y: Option<f64>) -> FrameExpect {
498        FrameExpect {
499            x,
500            y,
501            relative_to: Some(relative_to.into()),
502            ..Default::default()
503        }
504    }
505
506    /// A column stacks its children with the spacing it is given.
507    #[day_macros::test(day_core)]
508    fn column_spacing() -> Case {
509        Case::new()
510            .proves_duty("realize")
511            .proves_duty("insert")
512            .proves_duty("set_frame")
513            .proves_duty("measure")
514            .proves(kinds::CONTAINER)
515            .page(|| {
516                column((
517                    block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 50.0, 20.0),
518                    block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 50.0, 20.0),
519                ))
520                .spacing(10.0)
521                .align(HAlign::Leading)
522            })
523            .drive(
524                |d: Drive| async move { d.assert_frame("b", at("a", Some(0.0), Some(30.0))).await },
525            )
526    }
527
528    /// A row lays its children side by side and centers them on its cross axis.
529    #[day_macros::test(day_core)]
530    fn row_alignment() -> Case {
531        Case::new()
532            .proves(kinds::CONTAINER)
533            .page(|| {
534                row((block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 50.0, 20.0), block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 50.0, 40.0)))
535                    .spacing(8.0)
536                    .align(VAlign::Center)
537            })
538            .drive(|d: Drive| async move {
539                d.assert_frame("b", at("a", Some(58.0), Some(-10.0))).await
540            })
541    }
542
543    /// A grid aligns its rows' cells into shared columns.
544    #[day_macros::test(day_core)]
545    fn grid_columns() -> Case {
546        Case::new()
547            .proves(kinds::CONTAINER)
548            .page(|| {
549                grid((
550                    grid_row((
551                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 40.0, 20.0),
552                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 60.0, 20.0),
553                    )),
554                    grid_row((
555                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(c), 30.0, 20.0),
556                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(d), 30.0, 20.0),
557                    )),
558                ))
559                .spacing(0.0)
560                .align(day_core::Alignment::TopLeading)
561            })
562            .drive(|d: Drive| async move {
563                // The second column starts after the first column's widest cell; cells sit at
564                // their column's leading edge (they center by default).
565                d.assert_frame("d", at("a", Some(40.0), Some(20.0))).await?;
566                d.assert_frame("b", at("a", Some(40.0), Some(0.0))).await
567            })
568    }
569
570    /// A zstack draws its children over each other, the last on top, centered by default.
571    #[day_macros::test(day_core)]
572    fn zstack_layers() -> Case {
573        Case::new()
574            .proves(kinds::CONTAINER)
575            .proves_cap(day_spec::Cap::Snapshot)
576            .page(|| {
577                zstack((
578                    block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(under), 100.0, 60.0),
579                    block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(over), 50.0, 30.0),
580                ))
581                .id(day_core::id!(stack))
582            })
583            .shot("default")
584            .drive(|d: Drive| async move {
585                d.assert_frame("over", at("under", Some(25.0), Some(15.0)))
586                    .await?;
587                d.sample_pixel("under", 0.5, 0.5, "#0000ff").await?;
588                d.sample_pixel("under", 0.05, 0.1, "#ff0000").await
589            })
590    }
591
592    /// A scroll view scrolls natively to the target the app sets: the window shows what was
593    /// out of view.
594    #[day_macros::test(day_core)]
595    fn scroll_to_target() -> Case {
596        let jump = Signal::new(None::<ScrollTarget>);
597        Case::new()
598            .proves(kinds::SCROLL)
599            .proves_duty("scroll_to")
600            .proves_duty("set_scroll_content")
601            .page(move || {
602                let rows: Vec<AnyPiece> = (0..30)
603                    .map(|i| {
604                        let color = if i < 20 {
605                            Color::rgb(1.0, 0.0, 0.0)
606                        } else {
607                            Color::rgb(0.0, 0.0, 1.0)
608                        };
609                        rectangle().fill(color).frame(120.0, 40.0).any()
610                    })
611                    .collect();
612                column((
613                    scroll(column(rows).spacing(0.0))
614                        .scroll_target(jump)
615                        .id(day_core::id!(scroll))
616                        .frame(120.0, 120.0),
617                    button("Bottom")
618                        .action(move || jump.set(Some(ScrollTarget::Bottom)))
619                        .id(day_core::id!(bottom)),
620                ))
621                .spacing(8.0)
622            })
623            .drive(|d: Drive| async move {
624                d.sample_pixel("scroll", 0.5, 0.5, "#ff0000").await?;
625                d.tap("bottom").await?;
626                d.sample_pixel("scroll", 0.5, 0.5, "#0000ff").await
627            })
628    }
629}