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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Grouped, label-aligned settings UI: `form` and its `section` cards, with `labeled` rows that
//! share one aligned label column across the whole form.

use std::cell::Cell;
use std::rc::Rc;

use day_core::*;
use day_spec::props::*;
use day_spec::{Font, Rect, Size, kinds};

use crate::*;
use day_geometry::Proposal;

// ===========================================================================
// Forms (docs/forms.md): form / section / labeled, the grouped, label-aligned settings UI.
// ===========================================================================

/// Shared label-column state for one [`form`]: every [`labeled`] row inside registers its
/// label's width during measurement and lays its label out in a common, form-wide column,
/// the "aligned labels" look every settings UI converges on. The width is per-layout-pass
/// monotonic: all rows measure before any row places (the enclosing stacks measure all
/// children first), so alignment is consistent within a pass without invalidation dances.
#[derive(Clone)]
struct FormLabelColumn(Rc<Cell<f64>>);

const SECTION_RADIUS: f64 = 10.0;
const LABELED_GAP: f64 = 12.0;
/// The gap between a label and the control under it, once a row has stacked.
const STACKED_GAP: f64 = 6.0;

/// A settings-style form: a vertical run of [`section`]s whose [`labeled`] rows share one
/// label column across the whole form.
///
/// ```ignore
/// form((
///     section((
///         labeled(tr("volume"), slider(volume)),
///         labeled(tr("enabled"), toggle(enabled)),
///     ))
///     .title(tr("sound")),
///     section((labeled(tr("name"), text_field(name)),)),
/// ))
/// ```
pub fn form<C: PieceSeq + 'static>(sections: C) -> Form<C> {
    Form { sections }
}

/// A whole form, created by [`form`]: the shared label column wrapped around a vertical run
/// of [`section`]s.
pub struct Form<C: PieceSeq> {
    sections: C,
}

impl<C: PieceSeq + 'static> Piece for Form<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        // The shared column is created here, per form, so two forms on one page align
        // independently and a form rebuilt by a `when` arm starts from a fresh column.
        with_environment(FormLabelColumn(Rc::new(Cell::new(0.0))), move || {
            column(self.sections).spacing(16.0).align(HAlign::Leading)
        })
        .build(cx)
    }
}

/// One grouped form section (created by [`section`]): an optional header above a rounded card
/// whose background is the platform's theme-adaptive grouped-content material
/// (`SurfaceRole::SectionCard`: quaternary fill on AppKit, libadwaita `.card`, Qt
/// `palette(alternate-base)`, tertiary system fill on iOS, Material surface-container, the
/// XAML card brush), so it follows light/dark mode with no app code.
pub struct FormSection<C: PieceSeq> {
    title: Option<TextSource>,
    footer: Option<TextSource>,
    children: C,
}

/// A grouped card of form rows; `.title(…)` adds the header. Works inside a [`form`] (shared
/// label column) or standalone.
pub fn section<C: PieceSeq + 'static>(children: C) -> FormSection<C> {
    FormSection {
        title: None,
        footer: None,
        children,
    }
}

#[day_macros::builder(FormSectionBuilder)]
impl<C: PieceSeq + 'static> FormSection<C> {
    /// The section header, shown above the card in the footnote style.
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = Some(t.into_text());
        self
    }
    /// The section footer, shown under the card in the footnote style: the explanatory line
    /// settings screens put beneath a group of rows (iOS section footers, libadwaita's group
    /// description).
    pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
        self.footer = Some(t.into_text());
        self
    }
}

impl<C: PieceSeq + 'static> Piece for FormSection<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let children = self.children;
        let card = piece_fn(move |cx: &mut BuildCx| {
            let node = cx.native(
                kinds::CONTAINER,
                &ContainerProps {
                    background: None,
                    corner_radius: SECTION_RADIUS,
                    clips: true,
                    role: Some(day_spec::SurfaceRole::SectionCard),
                },
                Rc::new(SectionCardLayout),
                Flex {
                    grow_w: true,
                    ..Default::default()
                },
                Boundary::No,
            );
            let inner = column(children)
                .spacing(10.0)
                .align(HAlign::Leading)
                .padding(14.0);
            cx.under(node, |cx| {
                let _ = inner.build(cx);
            });
            node
        });
        let note = |t: TextSource| Label {
            text: t,
            font: Font::Footnote,
            font_scale: 1.0,
            weight: None,
            italic: false,
            tabular: false,
            monospace: false,
            wraps: true,
            max_lines: 0,
            runs: Vec::new(),
            markdown: false,
            align: day_spec::props::TextAlign::Leading,
            on_link: None,
            color: None,
            role: Default::default(),
        };
        let footer_insets = day_spec::Insets {
            top: 0.0,
            leading: 12.0,
            bottom: 0.0,
            trailing: 12.0,
        };
        match (self.title, self.footer) {
            (None, None) => card.build(cx),
            (Some(t), None) => column((note(t), card))
                .spacing(6.0)
                .align(HAlign::Leading)
                .build(cx),
            (None, Some(f)) => column((card, note(f).secondary().padding(footer_insets)))
                .spacing(6.0)
                .align(HAlign::Leading)
                .build(cx),
            (Some(t), Some(f)) => {
                column((note(t), card, note(f).secondary().padding(footer_insets)))
                    .spacing(6.0)
                    .align(HAlign::Leading)
                    .build(cx)
            }
        }
    }
}

/// The card fills the width its parent proposes (uniform card widths down a form) and hugs
/// its padded content vertically.
struct SectionCardLayout;

impl day_core::Layout for SectionCardLayout {
    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
        let cs = children
            .first()
            .map(|&c| cx.measure_child(c, Proposal::new(p.width, None)))
            .unwrap_or(Size::ZERO);
        Size::new(p.width.unwrap_or(cs.width).max(cs.width), cs.height)
    }
    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
        if let Some(&c) = children.first() {
            let s = cx.measure_child(c, Proposal::new(Some(bounds.size.width), None));
            cx.place_child(c, Rect::new(0.0, 0.0, bounds.size.width, s.height));
        }
    }
}

/// A form row: `label` sits in the form-wide aligned label column (right-aligned, vertically
/// centered), `control` beside it. Outside a [`form`] the label column is just this row's own
/// label width. A control with `.grow()` stretches to the row's remaining width.
///
/// The label also names the control for assistive technology, unless the control carries an
/// `.a11y(|a| a.label(..))` of its own.
pub fn labeled<M, P: Piece>(text: impl IntoText<M>, control: P) -> Labeled<P> {
    Labeled {
        text: text.into_text(),
        control,
    }
}

/// One form row, created by [`labeled`]: a label in the form-wide column beside its control.
pub struct Labeled<P: Piece> {
    text: TextSource,
    control: P,
}

impl<P: Piece> Piece for Labeled<P> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let Labeled { text, control } = self;
        let a11y_text = text.clone();
        // Read the enclosing form's shared column at build time (environment is scoped).
        let col = environment::<FormLabelColumn>();
        let node = cx.layout_only(
            Rc::new(LabeledLayout { col }),
            Flex {
                grow_w: true,
                ..Default::default()
            },
            Boundary::No,
        );
        cx.under(node, |cx| {
            let row_label = Label {
                text,
                font: Font::Body,
                font_scale: 1.0,
                weight: None,
                italic: false,
                tabular: false,
                monospace: false,
                wraps: true,
                max_lines: 0,
                runs: Vec::new(),
                markdown: false,
                align: day_spec::props::TextAlign::Leading,
                on_link: None,
                color: None,
                role: Default::default(),
            };
            let _ = row_label.build(cx);
            let ctl = control.build(cx);
            name_control(ctl, &a11y_text);
        });
        node
    }
}

/// Give a [`labeled`] row's control its label's text as its accessible name, when the control
/// has none of its own. A live text follows its source, as an `.a11y` label does.
fn name_control(ctl: RNode, text: &TextSource) {
    let named = with_tree(|t| t.node_a11y(ctl)).is_some_and(|a| a.label.is_some());
    if named {
        return;
    }
    let label = |s: String| day_spec::A11yProps {
        label: Some(s),
        ..Default::default()
    };
    match text {
        TextSource::Static(s) => with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
        TextSource::Dyn(read) => {
            let read = read.clone();
            let seed = day_reactive::untrack(|| read());
            with_tree(|t| t.set_a11y(ctl, label(seed.clone())));
            day_reactive::bind_seeded(
                seed,
                move || read(),
                move |s: &String| with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
            );
        }
    }
}

struct LabeledLayout {
    col: Option<FormLabelColumn>,
}

impl LabeledLayout {
    /// The label column width in effect: register this row's label width, read back the max.
    /// Only a row that sits beside its label calls this: a stacked row's label is above its
    /// control, not in the column, and registering it would widen the column for every other
    /// row (a long label on a phone would push their controls off the row).
    fn column_width(&self, label_w: f64) -> f64 {
        match &self.col {
            Some(c) => {
                if label_w > c.0.get() {
                    c.0.set(label_w);
                }
                c.0.get()
            }
            None => label_w,
        }
    }
}

impl LabeledLayout {
    /// How far to push each of the two children down so their text sits on one line
    /// (docs/baseline.md), plus the height the row needs to hold them once pushed.
    ///
    /// `None` when either side has no baseline to offer: a toolkit that does not report them,
    /// or a control with no text at all (a toggle, a slider, an image). The row then keeps the
    /// centering it has always done, which is what makes this safe to have on by default.
    fn baseline_shift(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        lbl: RNode,
        ls: Size,
        ctl: RNode,
        cs: Size,
    ) -> Option<(f64, f64, f64)> {
        let lb = cx.baseline_of(lbl, ls)?;
        let cb = cx.baseline_of(ctl, cs)?;
        let deepest = lb.max(cb);
        // Descent below the shared line decides the rest of the height.
        let height = deepest + (ls.height - lb).max(cs.height - cb);
        Some((deepest - lb, deepest - cb, height))
    }
}

impl LabeledLayout {
    /// Whether the control has to go under the label: offered the width left beside this
    /// row's own label, it still measures wider (a two-button stepper in a 280 dp inspector;
    /// a fixed-width field). A narrow pane then reads as the settings idiom (label above,
    /// control full-width) instead of clipping the control at the pane's edge.
    ///
    /// The row's label, not the form-wide column: the column grows as the form's rows are
    /// measured, so a decision taken against it would flip between measure and place and
    /// the rows would overlap. A `.grow()` control measures to what it is offered, so it
    /// stacks only when its content cannot fit that width.
    fn stacks(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        ctl: RNode,
        label_w: f64,
        width: f64,
    ) -> bool {
        let avail = (width - label_w - LABELED_GAP).max(0.0);
        let measured = cx
            .measure_child(ctl, Proposal::new(Some(avail), None))
            .width;
        measured > avail + 0.5
    }
}

impl day_core::Layout for LabeledLayout {
    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
            return Size::ZERO;
        };
        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
        if let Some(w) = p.width
            && self.stacks(cx, ctl, ls.width, w)
        {
            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
            return Size::new(w, ls.height + STACKED_GAP + cs.height);
        }
        let colw = self.column_width(ls.width);
        let avail = p.width.map(|w| (w - colw - LABELED_GAP).max(0.0));
        let cs = cx.measure_child(ctl, Proposal::new(avail, None));
        let natural = colw + LABELED_GAP + cs.width;
        // The row spans the proposed width (labels align form-wide; controls may stretch), and
        // hugs its content vertically: the taller child, or, once the two are sitting on one
        // baseline, whatever the shifted pair needs.
        let boxes = ls.height.max(cs.height);
        let height = match self.baseline_shift(cx, lbl, ls, ctl, cs) {
            Some((_, _, h)) => h.max(boxes),
            None => boxes,
        };
        Size::new(p.width.unwrap_or(natural).max(natural), height)
    }

    /// The row's own baseline is the line its label and control were put on, so a `labeled`
    /// nested inside another baseline-aligned row joins that line too (docs/baseline.md).
    fn baseline(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        children: &[RNode],
        size: Size,
    ) -> Option<f64> {
        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
            return None;
        };
        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
        if self.stacks(cx, ctl, ls.width, size.width) {
            // Stacked: the label's own line is the row's.
            return cx.baseline_of(lbl, ls);
        }
        let colw = self.column_width(ls.width);
        let avail = (size.width - colw - LABELED_GAP).max(0.0);
        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
        let lb = cx.baseline_of(lbl, ls)?;
        let (shift, _, _) = self.baseline_shift(cx, lbl, ls, ctl, cs)?;
        Some(shift + lb)
    }
    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
            return;
        };
        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
        if self.stacks(cx, ctl, ls.width, bounds.size.width) {
            // Label at the leading edge, control under it across the whole row (a hugging
            // control keeps its own width; a `.grow()` one takes the row).
            let w = bounds.size.width;
            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
            cx.place_child(lbl, Rect::new(0.0, 0.0, ls.width.min(w), ls.height));
            let cw = if cx.flex_of(ctl).grow_w {
                w
            } else {
                cs.width.min(w)
            };
            cx.place_child(ctl, Rect::new(0.0, ls.height + STACKED_GAP, cw, cs.height));
            return;
        }
        let colw = self.column_width(ls.width);
        let avail = (bounds.size.width - colw - LABELED_GAP).max(0.0);
        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
        let h = bounds.size.height;
        // Baseline first, centering as the fallback (docs/baseline.md): a label beside a
        // bordered field or a stepper has its text a few points off from the field's, because
        // the two put their text at different heights inside boxes of different heights.
        // Centering the boxes preserves that offset; this removes it.
        let (lbl_y, ctl_y) = match self.baseline_shift(cx, lbl, ls, ctl, cs) {
            Some((dl, dc, used)) => {
                // Center the aligned pair in whatever height the row was actually given, so a
                // row stretched by a taller sibling keeps its text group centered rather than
                // pinned to the top.
                let slack = ((h - used) / 2.0).max(0.0);
                (slack + dl, slack + dc)
            }
            None => (
                ((h - ls.height) / 2.0).max(0.0),
                ((h - cs.height) / 2.0).max(0.0),
            ),
        };
        cx.place_child(
            lbl,
            Rect::new((colw - ls.width).max(0.0), lbl_y, ls.width, ls.height),
        );
        // `.grow()` controls fill the remaining width (text fields, sliders); others hug.
        let cw = if cx.flex_of(ctl).grow_w {
            avail
        } else {
            cs.width.min(avail)
        };
        cx.place_child(ctl, Rect::new(colw + LABELED_GAP, ctl_y, cw, cs.height));
    }
}

// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---

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

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

    use crate::*;

    /// A form's rows hold their controls, and a control in a form works as anywhere else.
    #[day_macros::test(day_core)]
    fn form_sections() -> Case {
        let name = Signal::new(String::new());
        let on = Signal::new(false);
        Case::new()
            .proves_modifier("grow")
            .page(move || {
                form((
                    section((labeled("Name", text_field(name).id(day_core::id!(name))),))
                        .title("Profile"),
                    section((labeled("Updates", toggle(on).id(day_core::id!(updates))),))
                        .title("Mail"),
                ))
                .id(day_core::id!(form))
            })
            .shot("default")
            .drive(|d: Drive| async move {
                d.input("name", "Ada").await?;
                d.assert_text("name", "Ada").await?;
                d.toggle("updates", true).await?;
                d.assert_on("updates", true).await
            })
    }

    /// Every row's control starts at the same x: the form shares one label column.
    #[day_macros::test(day_core)]
    fn labeled_aligns_controls() -> Case {
        let (a, b) = (Signal::new(String::new()), Signal::new(String::new()));
        Case::new()
            .page(move || {
                form((section((
                    labeled("Name", text_field(a).id(day_core::id!(short))),
                    labeled("A much longer label", text_field(b).id(day_core::id!(long))),
                )),))
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "short",
                    FrameExpect {
                        x: Some(0.0),
                        relative_to: Some("long".into()),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// Compare native widgets, not just the layout's intended boxes. Native theme margins
    /// can move a control after Day has centered it (ArkUI switches used to do this).
    /// Both children have the same Day parent; native frames share window coordinates.
    fn control_alignment(row_id: &str, control_id: &str) -> TestResult {
        day_core::try_with_tree(|t| {
            let row = t.find_by_id(row_id).ok_or_else(|| Fail(format!("no row {row_id}")))?;
            let label = t.first_child(row).ok_or_else(|| Fail(format!("no label in {row_id}")))?;
            let control = t.find_by_id(control_id).ok_or_else(|| Fail(format!("no control {control_id}")))?;
            let frames = |node| -> Result<_, Fail> {
                let day = t.node_frame(node).ok_or_else(|| Fail("no Day frame".into()))?;
                let native = t.read_native(node).and_then(|n| n.frame)
                    .ok_or_else(|| Fail(format!("{row_id}: native frame unavailable")))?;
                Ok((day, native))
            };
            let (ld, ln) = frames(label)?;
            let (cd, cn) = frames(control)?;
            for (source, l, c) in [("Day", ld, cd), ("native", ln, cn)] {
                let delta = c.origin.y + c.size.height / 2.0 - l.origin.y - l.size.height / 2.0;
                if l.size.height <= 0.0 || c.size.height <= 0.0 || delta.abs() > 1.5 {
                    return Err(Fail(format!("{row_id}: {source} control/label centers differ by {delta:.2}; label {l:?}, control {c:?}")));
                }
            }
            // A common window offset is harmless, an extra control-only margin is not.
            let dx = (cn.origin.x - ln.origin.x) - (cd.origin.x - ld.origin.x);
            if dx.abs() > 1.5 {
                return Err(Fail(format!("{row_id}: native control/label spacing shifted by {dx:.2}")));
            }
            Ok(())
        }).unwrap_or_else(|| Err(Fail("the tree is busy".into())))
    }

    async fn controls_align(d: &Drive, pairs: &[(&str, &str)]) -> TestResult {
        // Give native layout a turn after realization or a value change. Retry geometry,
        // rather than depending on one fixed sleep on a loaded emulator.
        for attempt in 0..100 {
            let result = pairs
                .iter()
                .try_for_each(|(row, control)| control_alignment(row, control));
            if result.is_ok() || attempt == 99 {
                return result;
            }
            d.pause(0.02).await?;
        }
        unreachable!()
    }

    #[day_macros::test(day_core)]
    fn labeled_nontext_controls_center() -> Case {
        let a = Signal::new(false);
        let b = Signal::new(true);
        let value = Signal::new(0.5);
        Case::new()
            .proves(kinds::TOGGLE)
            .proves(kinds::SLIDER)
            .proves_duty("set_frame")
            .page(move || {
                column((
                    // The Tree page's two labeled switches, outside a form.
                    row((
                        labeled("Multi", toggle(a).id(day_core::id!(pair_a)))
                            .id(day_core::id!(pair_a_row)),
                        labeled("Lock", toggle(b).id(day_core::id!(pair_b)))
                            .id(day_core::id!(pair_b_row)),
                    ))
                    .spacing(16.0)
                    .fit(RowFit::Wrap { run_spacing: 8.0 }),
                    form((section((
                        labeled("Updates", toggle(a).id(day_core::id!(form_toggle)))
                            .id(day_core::id!(form_toggle_row)),
                        labeled("Level", slider(value).id(day_core::id!(form_slider)))
                            .id(day_core::id!(form_slider_row)),
                    )),)),
                ))
                .spacing(12.0)
                .width(300.0)
            })
            .drive(|d: Drive| async move {
                let pairs = [
                    ("pair_a_row", "pair_a"),
                    ("pair_b_row", "pair_b"),
                    ("form_toggle_row", "form_toggle"),
                    ("form_slider_row", "form_slider"),
                ];
                controls_align(&d, &pairs).await?;
                d.shot("centered-controls").await?;
                d.toggle("pair_a", true).await?;
                d.toggle("pair_b", false).await?;
                d.wait_idle().await?;
                controls_align(&d, &pairs).await
            })
    }

    #[day_macros::test(day_core)]
    fn row_nontext_controls_center() -> Case {
        let on = Signal::new(true);
        let value = Signal::new(0.5);
        Case::new()
            .proves(kinds::TOGGLE)
            .proves(kinds::SLIDER)
            .proves_duty("set_frame")
            .page(move || {
                column((
                    row((label("Switch"), toggle(on).id(day_core::id!(row_toggle))))
                        .spacing(12.0)
                        .id(day_core::id!(toggle_row)),
                    row((label("Level"), slider(value).id(day_core::id!(row_slider))))
                        .spacing(12.0)
                        .id(day_core::id!(slider_row)),
                ))
                .spacing(16.0)
                .padding(Insets::all(18.0))
            })
            .drive(|d: Drive| async move {
                let pairs = [("toggle_row", "row_toggle"), ("slider_row", "row_slider")];
                controls_align(&d, &pairs).await?;
                d.toggle("row_toggle", false).await?;
                d.wait_idle().await?;
                controls_align(&d, &pairs).await
            })
    }

    /// Narrow inspector rows must wrap whole label/control pairs, and action bars must
    /// keep their last button on screen rather than silently clipping it at the right edge.
    #[day_macros::test(day_core)]
    fn wrapped_controls_stay_inside_row() -> Case {
        let on = Signal::new(false);
        Case::new()
            .proves(kinds::CONTAINER)
            .proves(kinds::TOGGLE)
            .proves(kinds::BUTTON)
            .proves_duty("set_frame")
            .page(move || {
                column((
                    row((
                        labeled("Pause delivery", toggle(on).id(day_core::id!(pause)))
                            .id(day_core::id!(pause_row)),
                        labeled("Go offline", toggle(on).id(day_core::id!(offline)))
                            .id(day_core::id!(offline_row)),
                    ))
                    .spacing(16.0)
                    .fit(RowFit::Wrap { run_spacing: 8.0 })
                    .id(day_core::id!(wrapped_pairs))
                    .width(220.0),
                    row((
                        button("Add task").id(day_core::id!(add)),
                        button("Delete selected").id(day_core::id!(delete)),
                        button("Undo").id(day_core::id!(undo)),
                        button("Redo").id(day_core::id!(redo)),
                    ))
                    .spacing(8.0)
                    .fit(RowFit::Wrap { run_spacing: 8.0 })
                    .id(day_core::id!(wrapped_actions))
                    .width(220.0),
                ))
                .spacing(20.0)
            })
            .drive(|d: Drive| async move {
                controls_align(&d, &[("pause_row", "pause"), ("offline_row", "offline")]).await?;
                d.shot("wrapped-controls").await?;
                day_core::with_tree(|t| {
                    let frame = |id| {
                        t.find_by_id(id)
                            .and_then(|n| t.read_native(n))
                            .and_then(|s| s.frame)
                            .ok_or_else(|| Fail(format!("{id}: native frame unavailable")))
                    };
                    for (parent, children) in [
                        ("wrapped_pairs", &["pause", "offline"][..]),
                        ("wrapped_actions", &["add", "delete", "undo", "redo"][..]),
                    ] {
                        let bounds = frame(parent)?;
                        for &id in children {
                            let f = frame(id)?;
                            d.check(
                                f.origin.x >= bounds.origin.x - 1.5
                                    && f.origin.y >= bounds.origin.y - 1.5
                                    && f.origin.x + f.size.width
                                        <= bounds.origin.x + bounds.size.width + 1.5
                                    && f.origin.y + f.size.height
                                        <= bounds.origin.y + bounds.size.height + 1.5,
                                &format!("{id} {f:?} extends outside {parent} {bounds:?}"),
                            )?;
                        }
                        let first = frame(children[0])?;
                        let last = frame(children[children.len() - 1])?;
                        d.check(
                            last.origin.y >= first.origin.y + first.size.height,
                            &format!("{parent}: controls did not wrap onto another line"),
                        )?;
                    }
                    Ok(())
                })
            })
    }
}