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