day-pieces 0.6.1

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Layout containers that arrange child pieces: `column`, `row`, `grid`/`grid_row`, `scroll`,
//! and `zstack`, together with the `HAlign`/`VAlign` alignment enums.

use std::rc::Rc;

use day_core::*;
use day_reactive::{AnyBinding, Binding, watch};
use day_spec::kinds;
use day_spec::props::*;

use crate::Decorated;

// ---------------------------------------------------------------------------
// Containers
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HAlign {
    Leading,
    #[default]
    Center,
    Trailing,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum VAlign {
    Top,
    #[default]
    Center,
    Bottom,
    /// Sit the children's text on one line rather than centering their boxes
    /// (docs/baseline.md), which is what a label beside a bordered field or a larger-type value
    /// wants, since those put their text at different heights inside their boxes. A child with no
    /// text (an image, a slider) has no baseline and stays centered. Rows only; on a `column`
    /// it reads as `Center`.
    FirstBaseline,
}

pub struct Column<C: PieceSeq> {
    children: C,
    spacing: f64,
    align: CrossAlign,
}

pub fn column<C: PieceSeq>(children: C) -> Column<C> {
    Column {
        children,
        spacing: 0.0,
        align: CrossAlign::Center,
    }
}

#[day_macros::builder(ColumnBuilder)]
impl<C: PieceSeq> Column<C> {
    /// The gap between children: a [`Space`](crate::Space) step or points.
    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
        self.spacing = s.into();
        self
    }
    pub fn align(mut self, a: HAlign) -> Self {
        self.align = match a {
            HAlign::Leading => CrossAlign::Leading,
            HAlign::Center => CrossAlign::Center,
            HAlign::Trailing => CrossAlign::Trailing,
        };
        self
    }
}

impl<C: PieceSeq> Piece for Column<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let node = cx.native(
            kinds::CONTAINER,
            &ContainerProps::default(),
            Rc::new(StackLayout {
                axis: Axis::Vertical,
                spacing: self.spacing,
                align: self.align,
            }),
            Flex::default(),
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        node
    }
}

/// How a [`row`] treats content wider than the window it is in
/// (docs/size-classes.md "Row fit policies").
///
/// A row's children negotiate one line; the fit policy is what happens when that line is
/// wider than the space the row is given. Every policy keeps the same children and the same
/// call shape, `row((…)).fit(…)`, so a page can move between them as its needs change. A row
/// that should become a column on a narrow window is [`adaptive`](crate::adaptive), a piece of
/// its own.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum RowFit {
    /// One line at natural sizes; what does not fit lands offscreen. The default, and the
    /// right contract for a label beside a value. Debug builds log the overflow once per
    /// container, naming the dayscript ids in reach.
    #[default]
    Clip,
    /// Break onto additional lines where the next child would overflow, like wrapped text:
    /// the shape a chip row or button strip wants. `run_spacing` is the vertical gap between
    /// lines. Wrapping replaces main-axis negotiation, so `.grow()` and `spacer()` are inert.
    Wrap { run_spacing: f64 },
    /// Wrap into aligned columns rather than ragged lines: every cell takes the widest
    /// child's width, and each line holds as many as the window fits. The tidier arm of
    /// [`Wrap`](RowFit::Wrap): same wrapping, but the lines stack into a grid, which is what
    /// a set of peer choices (a keypad, a palette, evenly-weighted chips) wants. The column
    /// count follows the available width. When any child grows (`.grow_w()`), the widest child
    /// becomes the narrowest a column gets and the columns stretch to share the whole width,
    /// the adaptive grid a gallery of tiles wants. No cell is wider than the line: on a window
    /// narrower than the widest child, the cells take its width and their text wraps. An
    /// authored, fixed column count with
    /// per-cell spans is [`grid`]'s job instead (docs/grid.md).
    WrapColumns { run_spacing: f64 },
    /// Keep the single line and make it a horizontal scroll strip instead of clipping. The
    /// strip stays one row tall and fills the width it is given.
    Scroll,
}

pub struct Row<C: PieceSeq> {
    children: C,
    spacing: f64,
    align: CrossAlign,
    fit: RowFit,
}

pub fn row<C: PieceSeq>(children: C) -> Row<C> {
    Row {
        children,
        spacing: 0.0,
        align: CrossAlign::Center,
        fit: RowFit::Clip,
    }
}

#[day_macros::builder(RowBuilder)]
impl<C: PieceSeq> Row<C> {
    /// The gap between children: a [`Space`](crate::Space) step or points.
    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
        self.spacing = s.into();
        self
    }
    pub fn align(mut self, a: VAlign) -> Self {
        self.align = match a {
            VAlign::Top => CrossAlign::Leading,
            VAlign::Center => CrossAlign::Center,
            VAlign::Bottom => CrossAlign::Trailing,
            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
        };
        self
    }
    /// What happens when the children outgrow the row's width (docs/size-classes.md).
    pub fn fit(mut self, fit: RowFit) -> Self {
        self.fit = fit;
        self
    }
}

impl<C: PieceSeq> Row<C> {
    /// The plain one-line container every policy bottoms out in.
    fn build_line(self, cx: &mut BuildCx, axis: Axis, align: CrossAlign) -> RNode {
        let node = cx.native(
            kinds::CONTAINER,
            &ContainerProps::default(),
            Rc::new(StackLayout {
                axis,
                spacing: self.spacing,
                align,
            }),
            Flex::default(),
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        node
    }
}

impl<C: PieceSeq> Piece for Row<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        match self.fit {
            RowFit::Clip => {
                let align = self.align;
                self.build_line(cx, Axis::Horizontal, align)
            }
            RowFit::Wrap { run_spacing } | RowFit::WrapColumns { run_spacing } => {
                let node = cx.native(
                    kinds::CONTAINER,
                    &ContainerProps::default(),
                    Rc::new(FlowLayout {
                        spacing: self.spacing,
                        run_spacing,
                        align: self.align,
                        uniform: matches!(self.fit, RowFit::WrapColumns { .. }),
                    }),
                    Flex::default(),
                    Boundary::No,
                );
                cx.under(node, |cx| self.children.build_each(cx));
                node
            }
            RowFit::Scroll => {
                // The row keeps its natural one-line measure inside a horizontal scroll
                // viewport. `grow_h` stays off: the strip is as tall as the row, not as
                // tall as whatever pane it happens to sit in.
                let strip = cx.native(
                    kinds::SCROLL,
                    &day_spec::props::ScrollProps { horizontal: true },
                    Rc::new(ScrollLayout {
                        axis: Axis::Horizontal,
                    }),
                    Flex {
                        grow_w: true,
                        ..Default::default()
                    },
                    Boundary::Yes, // scroll viewports are layout boundaries (§7.4)
                );
                cx.under(strip, |cx| {
                    let align = self.align;
                    let _ = self.build_line(cx, Axis::Horizontal, align);
                });
                strip
            }
        }
    }
}

pub struct Grid<C: PieceSeq> {
    children: C,
    row_spacing: f64,
    column_spacing: f64,
    align: Alignment,
}

/// A SwiftUI-style eager grid (docs/grid.md): columns are inferred from [`grid_row`] children.
/// A column is as wide as its widest cell, a `grow_w` cell makes its column share the leftover
/// width evenly, and a non-row child becomes a full-width cell spanning every column. `spacer()`
/// inside a row is an inert empty cell that still occupies its column (a grid has explicit
/// gutters, so stack-style push-apart spacers don't apply). Cells opt into spans and per-cell
/// alignment with [`Decorated::grid_span`](crate::decorators::Decorated::grid_span) / [`Decorate::grid_align`](crate::decorators::Decorate::grid_align).
pub fn grid<C: PieceSeq>(children: C) -> Grid<C> {
    Grid {
        children,
        row_spacing: 0.0,
        column_spacing: 0.0,
        align: Alignment::Center,
    }
}

#[day_macros::builder(GridBuilder)]
impl<C: PieceSeq> Grid<C> {
    /// Set both the row and column gutters: a [`Space`](crate::Space) step or points.
    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
        let s = s.into();
        self.row_spacing = s;
        self.column_spacing = s;
        self
    }
    pub fn row_spacing(mut self, s: impl Into<f64>) -> Self {
        self.row_spacing = s.into();
        self
    }
    pub fn column_spacing(mut self, s: impl Into<f64>) -> Self {
        self.column_spacing = s.into();
        self
    }
    /// Default alignment of every cell within its cell rect (cell/row overrides win).
    pub fn align(mut self, a: Alignment) -> Self {
        self.align = a;
        self
    }
}

impl<C: PieceSeq> Piece for Grid<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let node = cx.native(
            kinds::CONTAINER,
            &ContainerProps::default(),
            Rc::new(GridLayout {
                row_spacing: self.row_spacing,
                column_spacing: self.column_spacing,
                align: self.align,
            }),
            Flex::default(),
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        node
    }
}

pub struct GridRow<C: PieceSeq> {
    children: C,
    valign: Option<CrossAlign>,
}

/// One row of a [`grid`]: each child is a cell, assigned to columns left to right. Outside a
/// grid a row degrades gracefully to a plain [`row`]. Rows are transparent carriers (the grid
/// places their cells directly), so decorating a `grid_row` itself is unsupported (decorate the
/// cells, or the grid).
pub fn grid_row<C: PieceSeq>(children: C) -> GridRow<C> {
    GridRow {
        children,
        valign: None,
    }
}

#[day_macros::builder(GridRowBuilder)]
impl<C: PieceSeq> GridRow<C> {
    /// Vertical alignment override for this row's cells (the grid's alignment applies otherwise).
    pub fn align(mut self, a: VAlign) -> Self {
        self.valign = Some(match a {
            VAlign::Top => CrossAlign::Leading,
            VAlign::Center => CrossAlign::Center,
            VAlign::Bottom => CrossAlign::Trailing,
            VAlign::FirstBaseline => CrossAlign::FirstBaseline,
        });
        self
    }
}

impl<C: PieceSeq> Piece for GridRow<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        // A layout-only node whose StackLayout only runs when the row is not inside a grid
        // (the graceful-degrade path); a grid introspects the cells and places them itself.
        let node = cx.layout_only(
            Rc::new(StackLayout {
                axis: Axis::Horizontal,
                spacing: 0.0,
                align: self.valign.unwrap_or_default(),
            }),
            Flex {
                grid: GridFacts {
                    is_row: true,
                    row_valign: self.valign,
                    ..Default::default()
                },
                ..Default::default()
            },
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        node
    }
}

pub struct Scroll<P: Piece> {
    child: P,
    axis: Axis,
    target: Option<AnyBinding<Option<day_core::ScrollTarget>>>,
}

pub fn scroll<P: Piece>(child: P) -> Scroll<P> {
    Scroll {
        child,
        axis: Axis::Vertical,
        target: None,
    }
}

#[day_macros::builder(ScrollBuilder)]
impl<P: Piece> Scroll<P> {
    /// Scroll horizontally instead of vertically (a filmstrip of cards, a chip row). The content
    /// is measured unconstrained on the horizontal axis and the native view scrolls sideways.
    pub fn horizontal(mut self) -> Self {
        self.axis = Axis::Horizontal;
        self
    }
    /// Set the scroll axis explicitly.
    pub fn axis(mut self, axis: Axis) -> Self {
        self.axis = axis;
        self
    }

    /// Programmatic scrolling (docs/scroll.md): each `Some(target)` written to `sig` scrolls
    /// there (animated), then the signal resets to `None`. Write-and-forget, so the same
    /// target can be sent twice in a row.
    ///
    /// ```ignore
    /// let jump = Signal::new(None);
    /// scroll(rows).scroll_target(jump);
    /// button("Bottom").action(move || jump.set(Some(ScrollTarget::Bottom)));
    /// ```
    pub fn scroll_target(mut self, target: impl Binding<Option<day_core::ScrollTarget>>) -> Self {
        self.target = Some(AnyBinding::new(target));
        self
    }
}

impl<P: Piece> Piece for Scroll<P> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let node = cx.native(
            kinds::SCROLL,
            &day_spec::props::ScrollProps {
                horizontal: matches!(self.axis, Axis::Horizontal),
            },
            Rc::new(ScrollLayout { axis: self.axis }),
            Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
            Boundary::Yes, // scroll viewports are layout boundaries (§7.4)
        );
        cx.under(node, |cx| {
            let _ = self.child.build(cx);
        });
        if let Some(sig) = self.target {
            watch(
                move || sig.get(),
                move |now, _| {
                    if let Some(t) = now.clone() {
                        // Deferred one main-loop turn: this watch runs inside the reactive
                        // flush, before the turn-end layout that resizes the scroll content;
                        // an edge target (Bottom/Trailing) computed now would land on the
                        // stale content size.
                        day_reactive::on_main(move || {
                            day_core::with_tree(|tr| {
                                tr.scroll_to_target(node, &t, true);
                            });
                        });
                        sig.set(None); // consumed, ready for the next command
                    }
                },
            );
        }
        node
    }
}

/// A z-stack: children are layered back-to-front (the first child sits at the bottom), all
/// sharing the container bounds and positioned by the stack's [`Alignment`]. The stack sizes to
/// the union (max width/height) of its children; contrast [`Decorate::overlay`](crate::decorators::Decorate::overlay), which sizes to
/// its content and treats the overlaid piece as a non-sizing annotation. Pure composition: it is
/// the same native panel as [`column()`]/[`row()`], so there is no per-backend work.
pub struct ZStack<C: PieceSeq> {
    children: C,
    align: Alignment,
}

/// Build a [`ZStack`] from a tuple, `Vec` or array of children.
pub fn zstack<C: PieceSeq>(children: C) -> ZStack<C> {
    ZStack {
        children,
        align: Alignment::Center,
    }
}

#[day_macros::builder(ZStackBuilder)]
impl<C: PieceSeq> ZStack<C> {
    /// Where children sit within the stack's bounds (default [`Alignment::Center`]).
    pub fn align(mut self, a: Alignment) -> Self {
        self.align = a;
        self
    }
}

impl<C: PieceSeq> Piece for ZStack<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let node = cx.native(
            kinds::CONTAINER,
            &ContainerProps::default(),
            Rc::new(OverlayLayout {
                align: self.align,
                size_to_first: false,
            }),
            Flex::default(),
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        node
    }
}

// ---------------------------------------------------------------------------
// Conformance cases (docs/testing.md)
// ---------------------------------------------------------------------------

/// The containers' `#[day::test]` cases, next to their constructors.
#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use day_core::conformance::{Case, Drive, FrameExpect};
    use day_core::{AnyPiece, ScrollTarget};
    use day_reactive::Signal;
    use day_spec::{Color, kinds};

    use crate::*;

    fn block(color: Color, id: day_core::ElementId, w: f64, h: f64) -> AnyPiece {
        rectangle().fill(color).id(id).frame(w, h).any()
    }

    fn at(relative_to: &str, x: Option<f64>, y: Option<f64>) -> FrameExpect {
        FrameExpect {
            x,
            y,
            relative_to: Some(relative_to.into()),
            ..Default::default()
        }
    }

    /// A column stacks its children with the spacing it is given.
    #[day_macros::test(day_core)]
    fn column_spacing() -> Case {
        Case::new()
            .proves_duty("realize")
            .proves_duty("insert")
            .proves_duty("set_frame")
            .proves_duty("measure")
            .proves(kinds::CONTAINER)
            .page(|| {
                column((
                    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, 20.0),
                ))
                .spacing(10.0)
                .align(HAlign::Leading)
            })
            .drive(
                |d: Drive| async move { d.assert_frame("b", at("a", Some(0.0), Some(30.0))).await },
            )
    }

    /// A row lays its children side by side and centers them on its cross axis.
    #[day_macros::test(day_core)]
    fn row_alignment() -> Case {
        Case::new()
            .proves(kinds::CONTAINER)
            .page(|| {
                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)))
                    .spacing(8.0)
                    .align(VAlign::Center)
            })
            .drive(|d: Drive| async move {
                d.assert_frame("b", at("a", Some(58.0), Some(-10.0))).await
            })
    }

    /// A grid aligns its rows' cells into shared columns.
    #[day_macros::test(day_core)]
    fn grid_columns() -> Case {
        Case::new()
            .proves(kinds::CONTAINER)
            .page(|| {
                grid((
                    grid_row((
                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(a), 40.0, 20.0),
                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(b), 60.0, 20.0),
                    )),
                    grid_row((
                        block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(c), 30.0, 20.0),
                        block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(d), 30.0, 20.0),
                    )),
                ))
                .spacing(0.0)
                .align(day_core::Alignment::TopLeading)
            })
            .drive(|d: Drive| async move {
                // The second column starts after the first column's widest cell; cells sit at
                // their column's leading edge (they center by default).
                d.assert_frame("d", at("a", Some(40.0), Some(20.0))).await?;
                d.assert_frame("b", at("a", Some(40.0), Some(0.0))).await
            })
    }

    /// A zstack draws its children over each other, the last on top, centered by default.
    #[day_macros::test(day_core)]
    fn zstack_layers() -> Case {
        Case::new()
            .proves(kinds::CONTAINER)
            .proves_cap(day_spec::Cap::Snapshot)
            .page(|| {
                zstack((
                    block(Color::rgb(1.0, 0.0, 0.0), day_core::id!(under), 100.0, 60.0),
                    block(Color::rgb(0.0, 0.0, 1.0), day_core::id!(over), 50.0, 30.0),
                ))
                .id(day_core::id!(stack))
            })
            .shot("default")
            .drive(|d: Drive| async move {
                d.assert_frame("over", at("under", Some(25.0), Some(15.0)))
                    .await?;
                d.sample_pixel("under", 0.5, 0.5, "#0000ff").await?;
                d.sample_pixel("under", 0.05, 0.1, "#ff0000").await
            })
    }

    /// A scroll view scrolls natively to the target the app sets: the window shows what was
    /// out of view.
    #[day_macros::test(day_core)]
    fn scroll_to_target() -> Case {
        let jump = Signal::new(None::<ScrollTarget>);
        Case::new()
            .proves(kinds::SCROLL)
            .proves_duty("scroll_to")
            .proves_duty("set_scroll_content")
            .page(move || {
                let rows: Vec<AnyPiece> = (0..30)
                    .map(|i| {
                        let color = if i < 20 {
                            Color::rgb(1.0, 0.0, 0.0)
                        } else {
                            Color::rgb(0.0, 0.0, 1.0)
                        };
                        rectangle().fill(color).frame(120.0, 40.0).any()
                    })
                    .collect();
                column((
                    scroll(column(rows).spacing(0.0))
                        .scroll_target(jump)
                        .id(day_core::id!(scroll))
                        .frame(120.0, 120.0),
                    button("Bottom")
                        .action(move || jump.set(Some(ScrollTarget::Bottom)))
                        .id(day_core::id!(bottom)),
                ))
                .spacing(8.0)
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("scroll", 0.5, 0.5, "#ff0000").await?;
                d.tap("bottom").await?;
                d.sample_pixel("scroll", 0.5, 0.5, "#0000ff").await
            })
    }
}