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::props::*;
12use day_spec::{Event, Insets, Point, ScrollPhase, kinds};
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. A line breaks on the children's natural widths; a child that grows
109    /// (`.grow(Dimension::Width)`) then takes a share of what its line has left, by weight.
110    /// A `spacer()` contributes nothing.
111    Wrap { run_spacing: f64 },
112    /// Wrap into aligned columns rather than ragged lines: every cell takes the widest
113    /// child's width, and each line holds as many as the window fits. The tidier arm of
114    /// [`Wrap`](RowFit::Wrap): same wrapping, but the lines stack into a grid, which is what
115    /// a set of peer choices (a keypad, a palette, evenly-weighted chips) wants. The column
116    /// count follows the available width. When any child grows (`.grow(Dimension::Width)`), the widest child
117    /// becomes the narrowest a column gets and the columns stretch to share the whole width,
118    /// the adaptive grid a gallery of tiles wants. No cell is wider than the line: on a window
119    /// narrower than the widest child, the cells take its width and their text wraps. An
120    /// authored, fixed column count with
121    /// per-cell spans is [`grid`]'s job instead (docs/grid.md).
122    WrapColumns { run_spacing: f64 },
123    /// Keep the single line and make it a horizontal scroll strip instead of clipping. The
124    /// strip stays one row tall and fills the width it is given.
125    Scroll,
126}
127
128#[must_use]
129pub struct Row<C: PieceSeq> {
130    children: C,
131    spacing: f64,
132    align: CrossAlign,
133    fit: RowFit,
134}
135
136pub fn row<C: PieceSeq>(children: C) -> Row<C> {
137    Row {
138        children,
139        spacing: 0.0,
140        align: CrossAlign::Center,
141        fit: RowFit::Clip,
142    }
143}
144
145#[day_macros::builder(RowBuilder)]
146impl<C: PieceSeq> Row<C> {
147    /// The gap between children: a [`Space`](crate::Space) step or points.
148    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
149        self.spacing = s.into();
150        self
151    }
152    pub fn align(mut self, a: VAlign) -> Self {
153        self.align = match a {
154            VAlign::Top => CrossAlign::Leading,
155            VAlign::Center => CrossAlign::Center,
156            VAlign::Bottom => CrossAlign::Trailing,
157            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
158        };
159        self
160    }
161    /// What happens when the children outgrow the row's width (docs/size-classes.md).
162    pub fn fit(mut self, fit: RowFit) -> Self {
163        self.fit = fit;
164        self
165    }
166}
167
168impl<C: PieceSeq> Row<C> {
169    /// The plain one-line container every policy bottoms out in.
170    fn build_line(self, cx: &mut BuildCx, axis: Axis, align: CrossAlign) -> RNode {
171        let node = cx.native(
172            kinds::CONTAINER,
173            &ContainerProps::default(),
174            Rc::new(StackLayout {
175                axis,
176                spacing: self.spacing,
177                align,
178            }),
179            Flex::default(),
180            Boundary::No,
181        );
182        cx.under(node, |cx| self.children.build_each(cx));
183        node
184    }
185}
186
187impl<C: PieceSeq> Piece for Row<C> {
188    fn build(self, cx: &mut BuildCx) -> RNode {
189        match self.fit {
190            RowFit::Clip => {
191                let align = self.align;
192                self.build_line(cx, Axis::Horizontal, align)
193            }
194            RowFit::Wrap { run_spacing } | RowFit::WrapColumns { run_spacing } => {
195                let node = cx.native(
196                    kinds::CONTAINER,
197                    &ContainerProps::default(),
198                    Rc::new(FlowLayout {
199                        spacing: self.spacing,
200                        run_spacing,
201                        align: self.align,
202                        uniform: matches!(self.fit, RowFit::WrapColumns { .. }),
203                    }),
204                    Flex::default(),
205                    Boundary::No,
206                );
207                cx.under(node, |cx| self.children.build_each(cx));
208                node
209            }
210            RowFit::Scroll => {
211                // The row keeps its natural one-line measure inside a horizontal scroll
212                // viewport. `grow_h` stays off: the strip is as tall as the row, not as
213                // tall as whatever pane it happens to sit in.
214                let strip = cx.native(
215                    kinds::SCROLL,
216                    &day_spec::props::ScrollProps {
217                        horizontal: true,
218                        ..Default::default()
219                    },
220                    Rc::new(ScrollLayout {
221                        axis: Axis::Horizontal,
222                        padding: Insets::ZERO,
223                    }),
224                    Flex {
225                        grow_w: true,
226                        ..Default::default()
227                    },
228                    Boundary::Yes, // scroll viewports are layout boundaries (§7.4)
229                );
230                cx.under(strip, |cx| {
231                    let align = self.align;
232                    let _ = self.build_line(cx, Axis::Horizontal, align);
233                });
234                strip
235            }
236        }
237    }
238}
239
240#[must_use]
241pub struct Grid<C: PieceSeq> {
242    children: C,
243    row_spacing: f64,
244    column_spacing: f64,
245    align: Alignment,
246}
247
248/// A SwiftUI-style eager grid (docs/grid.md): columns are inferred from [`grid_row`] children.
249/// A column is as wide as its widest cell, a `grow_w` cell makes its column share the leftover
250/// width evenly, and a non-row child becomes a full-width cell spanning every column. `spacer()`
251/// inside a row is an inert empty cell that still occupies its column (a grid has explicit
252/// gutters, so stack-style push-apart spacers don't apply). Cells opt into spans and per-cell
253/// alignment with [`Decorated::grid_span`](crate::decorators::Decorated::grid_span) / [`Decorate::grid_align`](crate::decorators::Decorate::grid_align).
254pub fn grid<C: PieceSeq>(children: C) -> Grid<C> {
255    Grid {
256        children,
257        row_spacing: 0.0,
258        column_spacing: 0.0,
259        align: Alignment::Center,
260    }
261}
262
263#[day_macros::builder(GridBuilder)]
264impl<C: PieceSeq> Grid<C> {
265    /// Set both the row and column gutters: a [`Space`](crate::Space) step or points.
266    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
267        let s = s.into();
268        self.row_spacing = s;
269        self.column_spacing = s;
270        self
271    }
272    pub fn row_spacing(mut self, s: impl Into<f64>) -> Self {
273        self.row_spacing = s.into();
274        self
275    }
276    pub fn column_spacing(mut self, s: impl Into<f64>) -> Self {
277        self.column_spacing = s.into();
278        self
279    }
280    /// Default alignment of every cell within its cell rect (cell/row overrides win).
281    pub fn align(mut self, a: Alignment) -> Self {
282        self.align = a;
283        self
284    }
285}
286
287impl<C: PieceSeq> Piece for Grid<C> {
288    fn build(self, cx: &mut BuildCx) -> RNode {
289        let node = cx.native(
290            kinds::CONTAINER,
291            &ContainerProps::default(),
292            Rc::new(GridLayout {
293                row_spacing: self.row_spacing,
294                column_spacing: self.column_spacing,
295                align: self.align,
296            }),
297            Flex::default(),
298            Boundary::No,
299        );
300        cx.under(node, |cx| self.children.build_each(cx));
301        node
302    }
303}
304
305#[must_use]
306pub struct GridRow<C: PieceSeq> {
307    children: C,
308    valign: Option<CrossAlign>,
309}
310
311/// One row of a [`grid`]: each child is a cell, assigned to columns left to right. Outside a
312/// grid a row degrades gracefully to a plain [`row`]. Rows are transparent carriers (the grid
313/// places their cells directly), so decorating a `grid_row` itself is unsupported (decorate the
314/// cells, or the grid).
315pub fn grid_row<C: PieceSeq>(children: C) -> GridRow<C> {
316    GridRow {
317        children,
318        valign: None,
319    }
320}
321
322#[day_macros::builder(GridRowBuilder)]
323impl<C: PieceSeq> GridRow<C> {
324    /// Vertical alignment override for this row's cells (the grid's alignment applies otherwise).
325    pub fn align(mut self, a: VAlign) -> Self {
326        self.valign = Some(match a {
327            VAlign::Top => CrossAlign::Leading,
328            VAlign::Center => CrossAlign::Center,
329            VAlign::Bottom => CrossAlign::Trailing,
330            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
331        });
332        self
333    }
334}
335
336impl<C: PieceSeq> Piece for GridRow<C> {
337    fn build(self, cx: &mut BuildCx) -> RNode {
338        // A layout-only node whose StackLayout only runs when the row is not inside a grid
339        // (the graceful-degrade path); a grid introspects the cells and places them itself.
340        let node = cx.layout_only(
341            Rc::new(StackLayout {
342                axis: Axis::Horizontal,
343                spacing: 0.0,
344                align: self.valign.unwrap_or_default(),
345            }),
346            Flex {
347                grid: GridFacts {
348                    is_row: true,
349                    row_valign: self.valign,
350                    ..Default::default()
351                },
352                ..Default::default()
353            },
354            Boundary::No,
355        );
356        cx.under(node, |cx| self.children.build_each(cx));
357        node
358    }
359}
360
361/// A native scroll view around one child (docs/scroll.md). Built by [`scroll`].
362#[must_use]
363pub struct Scroll<P: Piece> {
364    child: P,
365    axis: Axis,
366    target: Option<AnyBinding<Option<day_core::ScrollTarget>>>,
367    indicators: ScrollIndicators,
368    bounce: Option<bool>,
369    snap: ScrollSnap,
370    keyboard_dismiss: KeyboardDismiss,
371    keyboard_taps: KeyboardTaps,
372    padding: Insets,
373    offset: Option<AnyBinding<Point>>,
374    phase: Option<AnyBinding<ScrollPhase>>,
375    zoom: Option<ZoomRange>,
376    zoom_scale: Option<AnyBinding<f64>>,
377}
378
379/// Scroll `child` in the platform's own scroll view: vertical unless
380/// [`horizontal`](ScrollBuilder::horizontal) says otherwise (docs/scroll.md).
381pub fn scroll<P: Piece>(child: P) -> Scroll<P> {
382    Scroll {
383        child,
384        axis: Axis::Vertical,
385        target: None,
386        indicators: ScrollIndicators::Automatic,
387        bounce: None,
388        snap: ScrollSnap::None,
389        keyboard_dismiss: KeyboardDismiss::Never,
390        keyboard_taps: KeyboardTaps::Deliver,
391        padding: Insets::ZERO,
392        offset: None,
393        phase: None,
394        zoom: None,
395        zoom_scale: None,
396    }
397}
398
399/// How long a scroll view's offset must hold still before day-core calls the scrolling over,
400/// on a toolkit that does not report scroll phases itself (`Cap::ScrollPhases`).
401const SCROLL_IDLE_MS: u32 = 150;
402
403#[day_macros::builder(ScrollBuilder)]
404impl<P: Piece> Scroll<P> {
405    /// Scroll horizontally instead of vertically (a filmstrip of cards, a chip row). The content
406    /// is measured unconstrained on the horizontal axis and the native view scrolls sideways.
407    pub fn horizontal(mut self) -> Self {
408        self.axis = Axis::Horizontal;
409        self
410    }
411    /// Set the scroll axis explicitly.
412    pub fn axis(mut self, axis: Axis) -> Self {
413        self.axis = axis;
414        self
415    }
416
417    /// Programmatic scrolling (docs/scroll.md): each `Some(target)` written to `sig` scrolls
418    /// there, then the signal resets to `None`. Write-and-forget, so the same target can be
419    /// sent twice in a row. The scroll is animated with the platform's own scroll animation,
420    /// and jumps instead while the system's reduce-motion setting is on.
421    ///
422    /// ```ignore
423    /// let jump = Signal::new(None);
424    /// scroll(rows).scroll_target(jump);
425    /// button("Bottom").action(move || jump.set(Some(ScrollTarget::Bottom)));
426    /// ```
427    pub fn scroll_target(mut self, target: impl Binding<Option<day_core::ScrollTarget>>) -> Self {
428        self.target = Some(AnyBinding::new(target));
429        self
430    }
431
432    /// Hide the scroll indicators (scroll bars). The content still scrolls.
433    pub fn hide_indicators(mut self) -> Self {
434        self.indicators = ScrollIndicators::Hidden;
435        self
436    }
437
438    /// Stop at the content's edges: no rubber band on Apple platforms, no edge glow or
439    /// stretch on Android. A preference: a toolkit without an overscroll effect ignores it.
440    pub fn no_bounce(mut self) -> Self {
441        self.bounce = Some(false);
442        self
443    }
444
445    /// Show the platform's overscroll effect even when the content fits the viewport, so a
446    /// short page still answers a pull. A preference, as [`Self::no_bounce`] is.
447    pub fn always_bounce(mut self) -> Self {
448        self.bounce = Some(true);
449        self
450    }
451
452    /// Come to rest on whole pages: each swipe moves one viewport along the scroll axis
453    /// (probe `Cap::ScrollSnap`; where it is unsupported the view scrolls freely).
454    pub fn paging(mut self) -> Self {
455        self.snap = ScrollSnap::Page;
456        self
457    }
458
459    /// Come to rest on multiples of `interval` points along the scroll axis: a strip of
460    /// equal cards that always stops with one at the leading edge (probe `Cap::ScrollSnap`).
461    pub fn snap_interval(mut self, interval: f64) -> Self {
462        self.snap = ScrollSnap::Interval(interval);
463        self
464    }
465
466    /// When scrolling dismisses the software keyboard (docs/scroll.md "Keyboard"; probe
467    /// `Cap::ScrollKeyboardDismiss`). Desktop toolkits have no software keyboard and ignore it.
468    pub fn keyboard_dismiss(mut self, mode: KeyboardDismiss) -> Self {
469        self.keyboard_dismiss = mode;
470        self
471    }
472
473    /// What a tap inside the scroll view does while the software keyboard is up: reach the
474    /// control under it (the default), or dismiss the keyboard and go no further
475    /// (docs/scroll.md "Keyboard"). Honored where `Cap::ScrollKeyboardDismiss` is `Native`.
476    pub fn keyboard_taps(mut self, taps: KeyboardTaps) -> Self {
477        self.keyboard_taps = taps;
478        self
479    }
480
481    /// Space around the content, inside the scrolling area: it scrolls with the content, so
482    /// the last row can clear a floating bar while the scroll view itself stays edge to edge.
483    /// Takes a number for all four sides or an `Insets`.
484    pub fn content_padding(mut self, insets: impl Into<day_spec::Insets>) -> Self {
485        self.padding = insets.into();
486        self
487    }
488
489    /// Follow the content offset (docs/scroll.md "Offset and phase"): `offset` is written as
490    /// the view scrolls, in points from the content's top-left corner, at most once per
491    /// display frame, and once more with the offset the view comes to rest at. Whatever moves
492    /// the content counts: a finger, a wheel, momentum, [`Self::scroll_target`]. Drive a
493    /// collapsing header or a parallax layer from it. Probe `Cap::ScrollOffset`; where it is
494    /// unsupported the binding keeps its value.
495    ///
496    /// ```ignore
497    /// let offset = Signal::new(Point::ZERO);
498    /// zstack((
499    ///     scroll(page).scroll_offset(offset),
500    ///     header.opacity(move || 1.0 - (offset.get().y / 120.0).clamp(0.0, 1.0)),
501    /// ))
502    /// ```
503    pub fn scroll_offset(mut self, offset: impl Binding<Point>) -> Self {
504        self.offset = Some(AnyBinding::new(offset));
505        self
506    }
507
508    /// Follow user-driven scrolling (docs/scroll.md "Offset and phase"): `phase` is
509    /// `Dragging` from the moment the user starts moving the content, `Coasting` after the
510    /// finger lifts while momentum carries it, and `Idle` once it rests. A programmatic scroll
511    /// leaves it alone. `watch` it for the begin and end moments. Where `Cap::ScrollPhases`
512    /// is not `Native`, Day derives `Dragging` and `Idle` from the offset reports (there is
513    /// no `Coasting`), which needs `Cap::ScrollOffset`.
514    pub fn scroll_phase(mut self, phase: impl Binding<ScrollPhase>) -> Self {
515        self.phase = Some(AnyBinding::new(phase));
516        self
517    }
518
519    /// Let the user zoom the content by pinch, between the scales in `range` (`1.0` is the
520    /// content's natural size): `scroll(photo).zoom(1.0..=4.0)`. Probe `Cap::ScrollZoom`;
521    /// where it is unsupported the content stays at its natural size (docs/scroll.md "Zoom").
522    pub fn zoom(mut self, range: std::ops::RangeInclusive<f64>) -> Self {
523        let (min, max) = (*range.start(), *range.end());
524        self.zoom = Some(ZoomRange {
525            min: min.min(max),
526            max: max.max(min),
527        });
528        self
529    }
530
531    /// The zoom scale, both ways (docs/scroll.md "Zoom"): `scale` follows the user's pinch,
532    /// and a value the app writes zooms there, animated, clamped to the [`Self::zoom`] range.
533    /// A "fit" button is `scale.set(1.0)`.
534    pub fn zoom_scale(mut self, scale: impl Binding<f64>) -> Self {
535        self.zoom_scale = Some(AnyBinding::new(scale));
536        self
537    }
538}
539
540impl<P: Piece> Piece for Scroll<P> {
541    fn build(self, cx: &mut BuildCx) -> RNode {
542        use day_spec::{Cap, Support};
543        let native_phases = day_core::capability(Cap::ScrollPhases) == Support::Native;
544        // Day resigns focus itself when a drag begins, where the toolkit asks it to.
545        let dismiss_on_drag = self.keyboard_dismiss != KeyboardDismiss::Never
546            && day_core::capability(Cap::ScrollKeyboardDismiss) == Support::Emulated;
547        let wants_phase = self.phase.is_some() || dismiss_on_drag;
548        let node = cx.native(
549            kinds::SCROLL,
550            &day_spec::props::ScrollProps {
551                horizontal: matches!(self.axis, Axis::Horizontal),
552                indicators: self.indicators,
553                bounce: self.bounce,
554                snap: self.snap,
555                keyboard_dismiss: self.keyboard_dismiss,
556                keyboard_taps: self.keyboard_taps,
557                zoom: self.zoom,
558                // Without native phases the offset reports are what the phase is derived from.
559                track_offset: self.offset.is_some() || (wants_phase && !native_phases),
560                track_phase: wants_phase,
561            },
562            Rc::new(ScrollLayout {
563                axis: self.axis,
564                padding: self.padding,
565            }),
566            Flex {
567                grow_w: true,
568                grow_h: true,
569                ..Default::default()
570            },
571            Boundary::Yes, // scroll viewports are layout boundaries (§7.6)
572        );
573        cx.under(node, |cx| {
574            let _ = self.child.build(cx);
575        });
576        if let Some(sig) = self.target {
577            watch(
578                move || sig.get(),
579                move |now, _| {
580                    if let Some(t) = now.clone() {
581                        // Deferred one main-loop turn: this watch runs inside the reactive
582                        // flush, before the turn-end layout that resizes the scroll content;
583                        // an edge target (Bottom/Trailing) computed now would land on the
584                        // stale content size.
585                        day_reactive::on_main(move || {
586                            day_core::with_tree(|tr| {
587                                tr.scroll_to_target(node, &t, true);
588                            });
589                        });
590                        sig.set(None); // consumed, ready for the next command
591                    }
592                },
593            );
594        }
595        if self.offset.is_some() || wants_phase {
596            let (offset, phase) = (self.offset, self.phase);
597            // The phase as last told to the app, and the pending "scrolling stopped" check,
598            // which the next movement replaces.
599            let current = Rc::new(std::cell::Cell::new(ScrollPhase::Idle));
600            let quiet: std::cell::Cell<Option<day_core::TaskHandle>> = std::cell::Cell::new(None);
601            let enter: Rc<dyn Fn(ScrollPhase)> = {
602                let current = current.clone();
603                Rc::new(move |next: ScrollPhase| {
604                    if current.replace(next) == next {
605                        return;
606                    }
607                    if next == ScrollPhase::Dragging
608                        && dismiss_on_drag
609                        && let Some(focused) = day_core::focused_node()
610                    {
611                        day_core::with_tree(|t| t.focus_node(focused, false));
612                    }
613                    if let Some(phase) = &phase {
614                        phase.set_if_changed(next);
615                    }
616                })
617            };
618            cx.on(node, move |event| match event {
619                Event::ScrollChanged(at) => {
620                    if let Some(offset) = &offset {
621                        offset.set_if_changed(*at);
622                    }
623                    if wants_phase && !native_phases {
624                        // Movement is all this toolkit reports: scrolling is under way now,
625                        // and over once the offset has held still for a moment.
626                        enter(ScrollPhase::Dragging);
627                        if let Some(pending) = quiet.take() {
628                            pending.abort();
629                        }
630                        let enter = enter.clone();
631                        quiet.set(Some(day_core::task(async move {
632                            day_core::sleep(SCROLL_IDLE_MS).await;
633                            enter(ScrollPhase::Idle);
634                        })));
635                    }
636                }
637                Event::ScrollPhase(next) if native_phases => enter(*next),
638                _ => {}
639            });
640        }
641        if let Some(scale) = self.zoom_scale {
642            // The scale the view last reported, until the binding's watcher sees the write it
643            // made (§4.4 echo guard): the view's own report is not sent back to it. Every other
644            // write is the app's and is sent, even one equal to the view's last report: the
645            // view may be on its way somewhere else (an animated zoom reports only as it moves,
646            // so a reset written straight after a zoom-in matches the scale from before it).
647            let echo: Rc<std::cell::Cell<Option<f64>>> = Rc::new(std::cell::Cell::new(None));
648            {
649                let echo = echo.clone();
650                cx.on(node, move |event| {
651                    if let Event::ScrollZoomed(z) = event {
652                        echo.set(Some(*z));
653                        scale.set_if_changed(*z);
654                    }
655                });
656            }
657            let range = self.zoom;
658            watch(
659                move || scale.get(),
660                move |want: &f64, _| {
661                    if echo.take().is_some_and(|z| (z - want).abs() <= 1e-9) {
662                        return;
663                    }
664                    let want = range.map_or(*want, |r| want.clamp(r.min, r.max));
665                    day_core::with_tree(|t| {
666                        t.patch(
667                            node,
668                            Box::new(ScrollPatch::Zoom {
669                                scale: want,
670                                animated: true,
671                            }),
672                            false,
673                        );
674                    });
675                },
676            );
677        }
678        node
679    }
680}
681
682/// Column lanes (docs/size-classes.md "Lanes"). Built by [`lanes`].
683#[must_use]
684pub struct Lanes<C: PieceSeq> {
685    children: C,
686    lane_width: f64,
687    max: usize,
688    spacing: f64,
689    run_spacing: Option<f64>,
690    balanced: bool,
691}
692
693/// Deal `children` into as many equal-width columns as the available width holds, each
694/// column stacking its own: the layout a page of cards wants (docs/size-classes.md "Lanes").
695///
696/// The lane count is decided during layout from the width the container is given, so a
697/// window dragged wider gains a lane and the same children move over: none is rebuilt, and a
698/// card keeps its scroll position, its text and every other piece of state. Children are
699/// dealt in turn (first to the first lane, second to the second, and so on), or with
700/// [`balanced`](LanesBuilder::balanced) each to the lane that is shortest so far.
701///
702/// ```ignore
703/// scroll(lanes(cards).lane_width(320.0).max_lanes(3).spacing(Space::L).padding(20.0))
704/// ```
705pub fn lanes<C: PieceSeq>(children: C) -> Lanes<C> {
706    Lanes {
707        children,
708        lane_width: 320.0,
709        max: usize::MAX,
710        spacing: 8.0,
711        run_spacing: None,
712        balanced: false,
713    }
714}
715
716#[day_macros::builder(LanesBuilder)]
717impl<C: PieceSeq> Lanes<C> {
718    /// The narrowest a lane gets, in points (default 320): the container has one lane for
719    /// every `width` plus gap that fits, and the lanes then share the whole width equally.
720    pub fn lane_width(mut self, width: f64) -> Self {
721        self.lane_width = width.max(1.0);
722        self
723    }
724    /// The most lanes, however wide the container.
725    pub fn max_lanes(mut self, max: usize) -> Self {
726        self.max = max.max(1);
727        self
728    }
729    /// The gap between lanes, and between the children of a lane unless
730    /// [`Self::run_spacing`] sets that apart.
731    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
732        self.spacing = s.into();
733        self
734    }
735    /// The gap between the children of one lane.
736    pub fn run_spacing(mut self, s: impl Into<f64>) -> Self {
737        self.run_spacing = Some(s.into());
738        self
739    }
740    /// Put each child in the lane that is shortest so far, which evens the lanes out when
741    /// the children differ in height. The default deals in turn, which keeps a child's lane
742    /// predictable from its position.
743    pub fn balanced(mut self) -> Self {
744        self.balanced = true;
745        self
746    }
747}
748
749impl<C: PieceSeq> Piece for Lanes<C> {
750    fn build(self, cx: &mut BuildCx) -> RNode {
751        let node = cx.native(
752            kinds::CONTAINER,
753            &ContainerProps::default(),
754            Rc::new(LanesLayout {
755                min_width: self.lane_width,
756                max: self.max,
757                spacing: self.spacing,
758                run_spacing: self.run_spacing.unwrap_or(self.spacing),
759                balanced: self.balanced,
760            }),
761            Flex {
762                grow_w: true,
763                ..Default::default()
764            },
765            Boundary::No,
766        );
767        cx.under(node, |cx| self.children.build_each(cx));
768        node
769    }
770}
771
772/// A z-stack: children are layered back-to-front (the first child sits at the bottom), all
773/// sharing the container bounds and positioned by the stack's [`Alignment`]. The stack sizes to
774/// the union (max width/height) of its children; contrast [`Decorate::overlay`](crate::decorators::Decorate::overlay), which sizes to
775/// its content and treats the overlaid piece as a non-sizing annotation. Pure composition: it is
776/// the same native panel as [`column()`]/[`row()`], so there is no per-backend work.
777#[must_use]
778pub struct ZStack<C: PieceSeq> {
779    children: C,
780    align: Alignment,
781}
782
783/// Build a [`ZStack`] from a tuple, `Vec` or array of children.
784pub fn zstack<C: PieceSeq>(children: C) -> ZStack<C> {
785    ZStack {
786        children,
787        align: Alignment::Center,
788    }
789}
790
791#[day_macros::builder(ZStackBuilder)]
792impl<C: PieceSeq> ZStack<C> {
793    /// Where children sit within the stack's bounds (default [`Alignment::Center`]).
794    pub fn align(mut self, a: Alignment) -> Self {
795        self.align = a;
796        self
797    }
798}
799
800impl<C: PieceSeq> Piece for ZStack<C> {
801    fn build(self, cx: &mut BuildCx) -> RNode {
802        let node = cx.native(
803            kinds::CONTAINER,
804            &ContainerProps::default(),
805            Rc::new(OverlayLayout {
806                align: self.align,
807                size_to_first: false,
808            }),
809            Flex::default(),
810            Boundary::No,
811        );
812        cx.under(node, |cx| self.children.build_each(cx));
813        node
814    }
815}
816
817// ---------------------------------------------------------------------------
818// Conformance cases (docs/testing.md)
819// ---------------------------------------------------------------------------
820
821/// The containers' `#[day::test]` cases, next to their constructors.
822#[cfg(feature = "conformance")]
823pub(crate) mod conformance {
824    use day_core::conformance::{Case, Drive, FrameExpect};
825    use day_core::{AnyPiece, ScrollTarget};
826    use day_reactive::Signal;
827    use day_spec::{Color, kinds};
828
829    use crate::*;
830
831    fn block(color: Color, id: day_core::ElementId, w: f64, h: f64) -> AnyPiece {
832        rectangle().fill(color).id(id).frame(w, h).any()
833    }
834
835    fn at(relative_to: &str, x: Option<f64>, y: Option<f64>) -> FrameExpect {
836        FrameExpect {
837            x,
838            y,
839            relative_to: Some(relative_to.into()),
840            ..Default::default()
841        }
842    }
843
844    /// A column stacks its children with the spacing it is given.
845    #[day_macros::test(day_core)]
846    fn column_spacing() -> Case {
847        Case::new()
848            .proves_duty("realize")
849            .proves_duty("insert")
850            .proves_duty("set_frame")
851            .proves_duty("measure")
852            .proves(kinds::CONTAINER)
853            .page(|| {
854                column((
855                    block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 50.0, 20.0),
856                    block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 50.0, 20.0),
857                ))
858                .spacing(10.0)
859                .align(HAlign::Leading)
860            })
861            .drive(
862                |d: Drive| async move { d.assert_frame("b", at("a", Some(0.0), Some(30.0))).await },
863            )
864    }
865
866    /// A row lays its children side by side and centers them on its cross axis.
867    #[day_macros::test(day_core)]
868    fn row_alignment() -> Case {
869        Case::new()
870            .proves(kinds::CONTAINER)
871            .page(|| {
872                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)))
873                    .spacing(8.0)
874                    .align(VAlign::Center)
875            })
876            .drive(|d: Drive| async move {
877                d.assert_frame("b", at("a", Some(58.0), Some(-10.0))).await
878            })
879    }
880
881    /// A grid aligns its rows' cells into shared columns.
882    #[day_macros::test(day_core)]
883    fn grid_columns() -> Case {
884        Case::new()
885            .proves(kinds::CONTAINER)
886            .page(|| {
887                grid((
888                    grid_row((
889                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 40.0, 20.0),
890                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 60.0, 20.0),
891                    )),
892                    grid_row((
893                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(c), 30.0, 20.0),
894                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(d), 30.0, 20.0),
895                    )),
896                ))
897                .spacing(0.0)
898                .align(day_core::Alignment::TopLeading)
899            })
900            .drive(|d: Drive| async move {
901                // The second column starts after the first column's widest cell; cells sit at
902                // their column's leading edge (they center by default).
903                d.assert_frame("d", at("a", Some(40.0), Some(20.0))).await?;
904                d.assert_frame("b", at("a", Some(40.0), Some(0.0))).await
905            })
906    }
907
908    /// An absent optional cell (`None`) keeps its column, so the cells after it stay aligned
909    /// with the rows that have every cell (docs/grid.md "Spanning and empty cells").
910    #[day_macros::test(day_core)]
911    fn grid_none_keeps_its_column() -> Case {
912        Case::new()
913            .proves(kinds::CONTAINER)
914            .page(|| {
915                let absent: Option<AnyPiece> = None;
916                grid((
917                    grid_row((
918                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 40.0, 20.0),
919                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 60.0, 20.0),
920                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(c), 30.0, 20.0),
921                    )),
922                    grid_row((
923                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(d), 30.0, 20.0),
924                        absent,
925                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(f), 30.0, 20.0),
926                    )),
927                ))
928                .spacing(0.0)
929                .align(day_core::Alignment::TopLeading)
930            })
931            .drive(|d: Drive| async move {
932                // The third column starts after the first two (40 + 60), in both rows.
933                d.assert_frame("c", at("a", Some(100.0), Some(0.0))).await?;
934                d.assert_frame("f", at("a", Some(100.0), Some(20.0))).await
935            })
936    }
937
938    /// A zstack draws its children over each other, the last on top, centered by default.
939    #[day_macros::test(day_core)]
940    fn zstack_layers() -> Case {
941        Case::new()
942            .proves(kinds::CONTAINER)
943            .proves_cap(day_spec::Cap::Snapshot)
944            .page(|| {
945                zstack((
946                    block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(under), 100.0, 60.0),
947                    block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(over), 50.0, 30.0),
948                ))
949                .id(day_core::id!(stack))
950            })
951            .shot("default")
952            .drive(|d: Drive| async move {
953                d.assert_frame("over", at("under", Some(25.0), Some(15.0)))
954                    .await?;
955                d.sample_pixel("under", 0.5, 0.5, "#0000ff").await?;
956                d.sample_pixel("under", 0.05, 0.1, "#ff0000").await
957            })
958    }
959
960    /// A scroll view scrolls natively to the target the app sets: the window shows what was
961    /// out of view.
962    #[day_macros::test(day_core)]
963    fn scroll_to_target() -> Case {
964        let jump = Signal::new(None::<ScrollTarget>);
965        Case::new()
966            .proves(kinds::SCROLL)
967            .proves_duty("scroll_to")
968            .proves_duty("set_scroll_content")
969            .page(move || {
970                let rows: Vec<AnyPiece> = (0..30)
971                    .map(|i| {
972                        let color = if i < 20 {
973                            Color::rgb(1.0, 0.0, 0.0)
974                        } else {
975                            Color::rgb(0.0, 0.0, 1.0)
976                        };
977                        rectangle().fill(color).frame(120.0, 40.0).any()
978                    })
979                    .collect();
980                column((
981                    scroll(column(rows).spacing(0.0))
982                        .scroll_target(jump)
983                        .id(day_core::id!(scroll))
984                        .frame(120.0, 120.0),
985                    button("Bottom")
986                        .action(move || jump.set(Some(ScrollTarget::Bottom)))
987                        .id(day_core::id!(bottom)),
988                ))
989                .spacing(8.0)
990            })
991            .drive(|d: Drive| async move {
992                d.sample_pixel("scroll", 0.5, 0.5, "#ff0000").await?;
993                d.tap("bottom").await?;
994                d.sample_pixel("scroll", 0.5, 0.5, "#0000ff").await
995            })
996    }
997
998    /// A scroll view reports its offset after a programmatic scroll, and the bound signal
999    /// follows it (docs/scroll.md "Offset and phase").
1000    #[day_macros::test(day_core)]
1001    fn scroll_offset_follows_a_programmatic_scroll() -> Case {
1002        Case::new()
1003            .proves(kinds::SCROLL)
1004            .proves_cap(day_spec::Cap::ScrollOffset)
1005            .requires(day_spec::Cap::ScrollOffset)
1006            .page(|| {
1007                let jump = Signal::new(None::<ScrollTarget>);
1008                let offset = Signal::new(day_spec::Point::ZERO);
1009                let lines: Vec<AnyPiece> = (0..30)
1010                    .map(|_| {
1011                        rectangle()
1012                            .fill(Color::rgb(0.5, 0.5, 0.5))
1013                            .frame(120.0, 40.0)
1014                            .any()
1015                    })
1016                    .collect();
1017                column((
1018                    scroll(column(lines).spacing(0.0))
1019                        .scroll_target(jump)
1020                        .scroll_offset(offset)
1021                        .id(day_core::id!(scroll))
1022                        .frame(120.0, 120.0),
1023                    label(move || format!("y {:.0}", offset.get().y)).id(day_core::id!(offset)),
1024                    button("Bottom")
1025                        .action(move || jump.set(Some(ScrollTarget::Bottom)))
1026                        .id(day_core::id!(bottom)),
1027                    button("Top")
1028                        .action(move || jump.set(Some(ScrollTarget::Top)))
1029                        .id(day_core::id!(top)),
1030                ))
1031                .spacing(8.0)
1032            })
1033            .drive(|d: Drive| async move {
1034                d.assert_text("offset", "y 0").await?;
1035                // 30 lines of 40 points in a 120-point viewport: the bottom is at 1080.
1036                d.tap("bottom").await?;
1037                d.assert_text("offset", "y 1080").await?;
1038                d.tap("top").await?;
1039                d.assert_text("offset", "y 0").await
1040            })
1041    }
1042
1043    /// Content padding moves the content in and scrolls with it.
1044    #[day_macros::test(day_core)]
1045    fn scroll_content_padding_offsets_the_content() -> Case {
1046        Case::new()
1047            .proves(kinds::SCROLL)
1048            .page(|| {
1049                scroll(block(
1050                    Color::rgb(0.0, 0.0, 1.0),
1051                    day_core::id!(padded_content),
1052                    60.0,
1053                    60.0,
1054                ))
1055                .content_padding(day_spec::Insets {
1056                    top: 10.0,
1057                    leading: 20.0,
1058                    bottom: 10.0,
1059                    trailing: 20.0,
1060                })
1061                .id(day_core::id!(padded_scroll))
1062                .frame(160.0, 120.0)
1063            })
1064            .drive(|d: Drive| async move {
1065                d.assert_frame(
1066                    "padded_content",
1067                    at("padded_scroll", Some(20.0), Some(10.0)),
1068                )
1069                .await
1070            })
1071    }
1072
1073    /// A zooming scroll view takes a scale the app writes, clamps it to its range, and
1074    /// reports the scale it settled on (docs/scroll.md "Zoom").
1075    #[day_macros::test(day_core)]
1076    fn scroll_zoom_scale_round_trips() -> Case {
1077        Case::new()
1078            .proves(kinds::SCROLL)
1079            .proves_cap(day_spec::Cap::ScrollZoom)
1080            .requires(day_spec::Cap::ScrollZoom)
1081            .page(|| {
1082                let scale = Signal::new(1.0_f64);
1083                column((
1084                    scroll(block(
1085                        Color::rgb(0.0, 0.5, 0.0),
1086                        day_core::id!(zoom_content),
1087                        100.0,
1088                        100.0,
1089                    ))
1090                    .zoom(1.0..=4.0)
1091                    .zoom_scale(scale)
1092                    .frame(120.0, 120.0),
1093                    label(move || format!("zoom {:.1}", scale.get())).id(day_core::id!(zoom)),
1094                    button("Double")
1095                        .action(move || scale.set(2.0))
1096                        .id(day_core::id!(zoom_double)),
1097                    button("Far")
1098                        .action(move || scale.set(9.0))
1099                        .id(day_core::id!(zoom_far)),
1100                    button("Reset")
1101                        .action(move || scale.set(1.0))
1102                        .id(day_core::id!(zoom_reset)),
1103                ))
1104                .spacing(8.0)
1105            })
1106            .drive(|d: Drive| async move {
1107                d.assert_text("zoom", "zoom 1.0").await?;
1108                d.tap("zoom_double").await?;
1109                d.assert_text("zoom", "zoom 2.0").await?;
1110                // Past the range: the view stops at its maximum and says so.
1111                d.tap("zoom_far").await?;
1112                d.assert_text("zoom", "zoom 4.0").await?;
1113                d.tap("zoom_reset").await?;
1114                d.pause(1.0).await?;
1115                d.assert_text("zoom", "zoom 1.0").await?;
1116                // A write while the view is still on its way to the one before, back to the
1117                // scale it last reported: the view goes where the last write says, and the
1118                // zoom it gave up on does not land after it.
1119                d.tap("zoom_double").await?;
1120                d.tap("zoom_reset").await?;
1121                d.pause(1.0).await?;
1122                d.assert_text("zoom", "zoom 1.0").await
1123            })
1124    }
1125
1126    /// Lanes deal their children into as many columns as the width holds, and move the same
1127    /// children when the width changes (docs/size-classes.md "Lanes").
1128    #[day_macros::test(day_core)]
1129    fn lanes_reflow_without_rebuilding() -> Case {
1130        Case::new()
1131            .page(|| {
1132                let width = Signal::new(430.0_f64);
1133                let built = Signal::new(0_u32);
1134                let card = move |id: day_core::ElementId, height: f64| {
1135                    built.update(|n| *n += 1);
1136                    rectangle()
1137                        .fill(Color::rgb(0.2, 0.4, 0.8))
1138                        .height(height)
1139                        .grow(Dimension::Width)
1140                        .wrapper_id(id)
1141                };
1142                column((
1143                    row((
1144                        button("Narrow")
1145                            .action(move || width.set(210.0))
1146                            .id(day_core::id!(lanes_narrow)),
1147                        label(move || format!("built {}", built.get()))
1148                            .id(day_core::id!(lanes_built)),
1149                    )),
1150                    lanes((
1151                        card(day_core::id!(lane_a), 80.0),
1152                        card(day_core::id!(lane_b), 40.0),
1153                        card(day_core::id!(lane_c), 30.0),
1154                    ))
1155                    .lane_width(200.0)
1156                    .max_lanes(3)
1157                    .spacing(10.0)
1158                    .id(day_core::id!(lanes))
1159                    .width(move || width.get()),
1160                ))
1161                .align(HAlign::Leading)
1162            })
1163            .drive(|d: Drive| async move {
1164                // 430 points hold two 200-point lanes of 210: a and c in the first, b in the
1165                // second.
1166                d.assert_size("lane_a", 210.0, 80.0).await?;
1167                d.assert_frame("lane_b", at("lane_a", Some(220.0), Some(0.0)))
1168                    .await?;
1169                d.assert_frame("lane_c", at("lane_a", Some(0.0), Some(90.0)))
1170                    .await?;
1171                // One lane: the same cards, stacked, none built again.
1172                d.tap("lanes_narrow").await?;
1173                d.assert_frame("lane_b", at("lane_a", Some(0.0), Some(90.0)))
1174                    .await?;
1175                d.assert_frame("lane_c", at("lane_a", Some(0.0), Some(140.0)))
1176                    .await?;
1177                d.assert_text("lanes_built", "built 3").await
1178            })
1179    }
1180
1181    /// In a wrapping row the growing children share what their line has left, by weight.
1182    #[day_macros::test(day_core)]
1183    fn wrap_row_shares_each_line_by_weight() -> Case {
1184        Case::new()
1185            .proves_modifier("grow")
1186            .page(|| {
1187                let tile = |id: day_core::ElementId, weight: f64| {
1188                    rectangle()
1189                        .fill(Color::rgb(0.8, 0.3, 0.2))
1190                        .height(20.0)
1191                        .min_width(50.0)
1192                        .grow(Dimension::Width.weight(weight))
1193                        .wrapper_id(id)
1194                };
1195                row((
1196                    tile(day_core::id!(share_a), 1.0),
1197                    tile(day_core::id!(share_b), 3.0),
1198                    tile(day_core::id!(share_c), 1.0),
1199                ))
1200                .spacing(0.0)
1201                .fit(RowFit::Wrap { run_spacing: 10.0 })
1202                .width(140.0)
1203            })
1204            .drive(|d: Drive| async move {
1205                // 140 points hold two 50-point tiles; the 40 left go one to three.
1206                d.assert_size("share_a", 60.0, 20.0).await?;
1207                d.assert_size("share_b", 80.0, 20.0).await?;
1208                // The third wraps and has its line to itself.
1209                d.assert_size("share_c", 140.0, 20.0).await?;
1210                d.assert_frame("share_c", at("share_a", Some(0.0), Some(30.0)))
1211                    .await
1212            })
1213    }
1214}