Skip to main content

day_pieces/
forms.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Grouped, label-aligned settings UI: `form` and its `section` cards, with `labeled` rows that
5//! share one aligned label column across the whole form.
6
7use std::cell::Cell;
8use std::rc::Rc;
9
10use day_core::*;
11use day_spec::props::*;
12use day_spec::{Font, Rect, Size, kinds};
13
14use crate::*;
15use day_geometry::Proposal;
16
17// ===========================================================================
18// Forms (docs/forms.md): form / section / labeled, the grouped, label-aligned settings UI.
19// ===========================================================================
20
21/// Shared label-column state for one [`form`]: every [`labeled`] row inside registers its
22/// label's width during measurement and lays its label out in a common, form-wide column,
23/// the "aligned labels" look every settings UI converges on. The width is per-layout-pass
24/// monotonic: all rows measure before any row places (the enclosing stacks measure all
25/// children first), so alignment is consistent within a pass without invalidation dances.
26#[derive(Clone)]
27struct FormLabelColumn(Rc<Cell<f64>>);
28
29const SECTION_RADIUS: f64 = 10.0;
30const LABELED_GAP: f64 = 12.0;
31/// The gap between a label and the control under it, once a row has stacked.
32const STACKED_GAP: f64 = 6.0;
33
34/// A settings-style form: a vertical run of [`section`]s whose [`labeled`] rows share one
35/// label column across the whole form.
36///
37/// ```ignore
38/// form((
39///     section((
40///         labeled(tr("volume"), slider(volume)),
41///         labeled(tr("enabled"), toggle(enabled)),
42///     ))
43///     .title(tr("sound")),
44///     section((labeled(tr("name"), text_field(name)),)),
45/// ))
46/// ```
47pub fn form<C: PieceSeq + 'static>(sections: C) -> Form<C> {
48    Form { sections }
49}
50
51/// A whole form, created by [`form`]: the shared label column wrapped around a vertical run
52/// of [`section`]s.
53pub struct Form<C: PieceSeq> {
54    sections: C,
55}
56
57impl<C: PieceSeq + 'static> Piece for Form<C> {
58    fn build(self, cx: &mut BuildCx) -> RNode {
59        // The shared column is created here, per form, so two forms on one page align
60        // independently and a form rebuilt by a `when` arm starts from a fresh column.
61        with_environment(FormLabelColumn(Rc::new(Cell::new(0.0))), move || {
62            column(self.sections).spacing(16.0).align(HAlign::Leading)
63        })
64        .build(cx)
65    }
66}
67
68/// One grouped form section (created by [`section`]): an optional header above a rounded card
69/// whose background is the platform's theme-adaptive grouped-content material
70/// (`SurfaceRole::SectionCard`: quaternary fill on AppKit, libadwaita `.card`, Qt
71/// `palette(alternate-base)`, tertiary system fill on iOS, Material surface-container, the
72/// XAML card brush), so it follows light/dark mode with no app code.
73#[must_use]
74pub struct FormSection<C: PieceSeq> {
75    title: Option<TextSource>,
76    footer: Option<TextSource>,
77    children: C,
78}
79
80/// A grouped card of form rows; `.title(…)` adds the header. Works inside a [`form`] (shared
81/// label column) or standalone.
82pub fn section<C: PieceSeq + 'static>(children: C) -> FormSection<C> {
83    FormSection {
84        title: None,
85        footer: None,
86        children,
87    }
88}
89
90#[day_macros::builder(FormSectionBuilder)]
91impl<C: PieceSeq + 'static> FormSection<C> {
92    /// The section header, shown above the card in the footnote style.
93    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
94        self.title = Some(t.into_text());
95        self
96    }
97    /// The section footer, shown under the card in the footnote style: the explanatory line
98    /// settings screens put beneath a group of rows (iOS section footers, libadwaita's group
99    /// description).
100    pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
101        self.footer = Some(t.into_text());
102        self
103    }
104}
105
106impl<C: PieceSeq + 'static> Piece for FormSection<C> {
107    fn build(self, cx: &mut BuildCx) -> RNode {
108        let children = self.children;
109        let card = piece_fn(move |cx: &mut BuildCx| {
110            let node = cx.native(
111                kinds::CONTAINER,
112                &ContainerProps {
113                    corner_radius: SECTION_RADIUS,
114                    clips: true,
115                    role: Some(day_spec::SurfaceRole::SectionCard),
116                    ..Default::default()
117                },
118                Rc::new(SectionCardLayout),
119                Flex {
120                    grow_w: true,
121                    ..Default::default()
122                },
123                Boundary::No,
124            );
125            let inner = column(children)
126                .spacing(10.0)
127                .align(HAlign::Leading)
128                .padding(14.0);
129            cx.under(node, |cx| {
130                let _ = inner.build(cx);
131            });
132            node
133        });
134        let note = |t: TextSource| Label::from_source(t).font(Font::Footnote);
135        let footer_insets = day_spec::Insets {
136            top: 0.0,
137            leading: 12.0,
138            bottom: 0.0,
139            trailing: 12.0,
140        };
141        match (self.title, self.footer) {
142            (None, None) => card.build(cx),
143            (Some(t), None) => column((note(t), card))
144                .spacing(6.0)
145                .align(HAlign::Leading)
146                .build(cx),
147            (None, Some(f)) => column((card, note(f).secondary().padding(footer_insets)))
148                .spacing(6.0)
149                .align(HAlign::Leading)
150                .build(cx),
151            (Some(t), Some(f)) => {
152                column((note(t), card, note(f).secondary().padding(footer_insets)))
153                    .spacing(6.0)
154                    .align(HAlign::Leading)
155                    .build(cx)
156            }
157        }
158    }
159}
160
161/// The card fills the width its parent proposes (uniform card widths down a form) and hugs
162/// its padded content vertically.
163struct SectionCardLayout;
164
165impl day_core::Layout for SectionCardLayout {
166    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
167        let cs = children.first().map_or(Size::ZERO, |&c| {
168            cx.measure_child(c, Proposal::new(p.width, None))
169        });
170        Size::new(p.width.unwrap_or(cs.width).max(cs.width), cs.height)
171    }
172    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
173        if let Some(&c) = children.first() {
174            let s = cx.measure_child(c, Proposal::new(Some(bounds.size.width), None));
175            cx.place_child(c, Rect::new(0.0, 0.0, bounds.size.width, s.height));
176        }
177    }
178}
179
180/// A form row: `label` sits in the form-wide aligned label column (right-aligned, vertically
181/// centered), `control` beside it. Outside a [`form`] the label column is just this row's own
182/// label width. A control with `.grow(Dimension::Both)` stretches to the row's remaining width.
183///
184/// The label also names the control for assistive technology, unless the control carries an
185/// `.a11y(|a| a.label(..))` of its own.
186pub fn labeled<M, P: Piece>(text: impl IntoText<M>, control: P) -> Labeled<P> {
187    Labeled {
188        text: text.into_text(),
189        control,
190    }
191}
192
193/// One form row, created by [`labeled`]: a label in the form-wide column beside its control.
194pub struct Labeled<P: Piece> {
195    text: TextSource,
196    control: P,
197}
198
199impl<P: Piece> Piece for Labeled<P> {
200    fn build(self, cx: &mut BuildCx) -> RNode {
201        let Labeled { text, control } = self;
202        let a11y_text = text.clone();
203        // Read the enclosing form's shared column at build time (environment is scoped).
204        let col = environment::<FormLabelColumn>();
205        let node = cx.layout_only(
206            Rc::new(LabeledLayout { col }),
207            Flex {
208                grow_w: true,
209                ..Default::default()
210            },
211            Boundary::No,
212        );
213        cx.under(node, |cx| {
214            let row_label = Label::from_source(text);
215            let _ = row_label.build(cx);
216            let ctl = control.build(cx);
217            name_control(ctl, &a11y_text);
218        });
219        node
220    }
221}
222
223/// Give a [`labeled`] row's control its label's text as its accessible name, when the control
224/// has none of its own. A live text follows its source, as an `.a11y` label does.
225fn name_control(ctl: RNode, text: &TextSource) {
226    let named = with_tree(|t| t.node_a11y(ctl)).is_some_and(|a| a.label.is_some());
227    if named {
228        return;
229    }
230    let label = |s: String| day_spec::A11yProps {
231        label: Some(s),
232        ..Default::default()
233    };
234    match text {
235        TextSource::Static(s) => with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
236        TextSource::Dyn(read) => {
237            let read = read.clone();
238            let seed = day_reactive::untrack(|| read());
239            with_tree(|t| t.set_a11y(ctl, label(seed.clone())));
240            day_reactive::bind_seeded(
241                seed,
242                move || read(),
243                move |s: &String| with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
244            );
245        }
246    }
247}
248
249struct LabeledLayout {
250    col: Option<FormLabelColumn>,
251}
252
253impl LabeledLayout {
254    /// The label column width in effect: register this row's label width, read back the max.
255    /// Only a row that sits beside its label calls this: a stacked row's label is above its
256    /// control, not in the column, and registering it would widen the column for every other
257    /// row (a long label on a phone would push their controls off the row).
258    fn column_width(&self, label_w: f64) -> f64 {
259        match &self.col {
260            Some(c) => {
261                if label_w > c.0.get() {
262                    c.0.set(label_w);
263                }
264                c.0.get()
265            }
266            None => label_w,
267        }
268    }
269}
270
271impl LabeledLayout {
272    /// How far to push each of the two children down so their text sits on one line
273    /// (docs/baseline.md), plus the height the row needs to hold them once pushed.
274    ///
275    /// `None` when either side has no baseline to offer: a toolkit that does not report them,
276    /// or a control with no text at all (a toggle, a slider, an image). The row then keeps the
277    /// centering it has always done, which is what makes this safe to have on by default.
278    fn baseline_shift(
279        cx: &mut dyn day_core::LayoutOps,
280        lbl: RNode,
281        ls: Size,
282        ctl: RNode,
283        cs: Size,
284    ) -> Option<(f64, f64, f64)> {
285        let lb = cx.baseline_of(lbl, ls)?;
286        let cb = cx.baseline_of(ctl, cs)?;
287        let deepest = lb.max(cb);
288        // Descent below the shared line decides the rest of the height.
289        let height = deepest + (ls.height - lb).max(cs.height - cb);
290        Some((deepest - lb, deepest - cb, height))
291    }
292}
293
294impl LabeledLayout {
295    /// Whether the control has to go under the label: offered the width left beside this
296    /// row's own label, it still measures wider (a two-button stepper in a 280 dp inspector;
297    /// a fixed-width field). A narrow pane then reads as the settings idiom (label above,
298    /// control full-width) instead of clipping the control at the pane's edge.
299    ///
300    /// The row's label, not the form-wide column: the column grows as the form's rows are
301    /// measured, so a decision taken against it would flip between measure and place and
302    /// the rows would overlap. A `.grow(Dimension::Both)` control measures to what it is offered, so it
303    /// stacks only when its content cannot fit that width.
304    fn stacks(cx: &mut dyn day_core::LayoutOps, ctl: RNode, label_w: f64, width: f64) -> bool {
305        let avail = (width - label_w - LABELED_GAP).max(0.0);
306        let measured = cx
307            .measure_child(ctl, Proposal::new(Some(avail), None))
308            .width;
309        measured > avail + 0.5
310    }
311}
312
313impl day_core::Layout for LabeledLayout {
314    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
315        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
316            return Size::ZERO;
317        };
318        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
319        if let Some(w) = p.width
320            && Self::stacks(cx, ctl, ls.width, w)
321        {
322            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
323            return Size::new(w, ls.height + STACKED_GAP + cs.height);
324        }
325        let colw = self.column_width(ls.width);
326        let avail = p.width.map(|w| (w - colw - LABELED_GAP).max(0.0));
327        let cs = cx.measure_child(ctl, Proposal::new(avail, None));
328        let natural = colw + LABELED_GAP + cs.width;
329        // The row spans the proposed width (labels align form-wide; controls may stretch), and
330        // hugs its content vertically: the taller child, or, once the two are sitting on one
331        // baseline, whatever the shifted pair needs.
332        let boxes = ls.height.max(cs.height);
333        let height = match Self::baseline_shift(cx, lbl, ls, ctl, cs) {
334            Some((_, _, h)) => h.max(boxes),
335            None => boxes,
336        };
337        Size::new(p.width.unwrap_or(natural).max(natural), height)
338    }
339
340    /// The row's own baseline is the line its label and control were put on, so a `labeled`
341    /// nested inside another baseline-aligned row joins that line too (docs/baseline.md).
342    fn baseline(
343        &self,
344        cx: &mut dyn day_core::LayoutOps,
345        children: &[RNode],
346        size: Size,
347    ) -> Option<f64> {
348        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
349            return None;
350        };
351        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
352        if Self::stacks(cx, ctl, ls.width, size.width) {
353            // Stacked: the label's own line is the row's.
354            return cx.baseline_of(lbl, ls);
355        }
356        let colw = self.column_width(ls.width);
357        let avail = (size.width - colw - LABELED_GAP).max(0.0);
358        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
359        let lb = cx.baseline_of(lbl, ls)?;
360        let (shift, _, _) = Self::baseline_shift(cx, lbl, ls, ctl, cs)?;
361        Some(shift + lb)
362    }
363    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
364        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
365            return;
366        };
367        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
368        if Self::stacks(cx, ctl, ls.width, bounds.size.width) {
369            // Label at the leading edge, control under it across the whole row (a hugging
370            // control keeps its own width; a `.grow(Dimension::Both)` one takes the row).
371            let w = bounds.size.width;
372            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
373            cx.place_child(lbl, Rect::new(0.0, 0.0, ls.width.min(w), ls.height));
374            let cw = if cx.flex_of(ctl).grow_w {
375                w
376            } else {
377                cs.width.min(w)
378            };
379            cx.place_child(ctl, Rect::new(0.0, ls.height + STACKED_GAP, cw, cs.height));
380            return;
381        }
382        let colw = self.column_width(ls.width);
383        let avail = (bounds.size.width - colw - LABELED_GAP).max(0.0);
384        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
385        let h = bounds.size.height;
386        // Baseline first, centering as the fallback (docs/baseline.md): a label beside a
387        // bordered field or a stepper has its text a few points off from the field's, because
388        // the two put their text at different heights inside boxes of different heights.
389        // Centering the boxes preserves that offset; this removes it.
390        let (lbl_y, ctl_y) = match Self::baseline_shift(cx, lbl, ls, ctl, cs) {
391            Some((dl, dc, used)) => {
392                // Center the aligned pair in whatever height the row was actually given, so a
393                // row stretched by a taller sibling keeps its text group centered rather than
394                // pinned to the top.
395                let slack = ((h - used) / 2.0).max(0.0);
396                (slack + dl, slack + dc)
397            }
398            None => (
399                ((h - ls.height) / 2.0).max(0.0),
400                ((h - cs.height) / 2.0).max(0.0),
401            ),
402        };
403        cx.place_child(
404            lbl,
405            Rect::new((colw - ls.width).max(0.0), lbl_y, ls.width, ls.height),
406        );
407        // `.grow(Dimension::Both)` controls fill the remaining width (text fields, sliders); others hug.
408        let cw = if cx.flex_of(ctl).grow_w {
409            avail
410        } else {
411            cs.width.min(avail)
412        };
413        cx.place_child(ctl, Rect::new(colw + LABELED_GAP, ctl_y, cw, cs.height));
414    }
415}
416
417// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
418
419// ---------------------------------------------------------------------------
420// Conformance cases (docs/testing.md)
421// ---------------------------------------------------------------------------
422
423/// The form pieces' `#[day::test]` cases, next to their constructors.
424#[cfg(feature = "conformance")]
425pub(crate) mod conformance {
426    use day_core::conformance::{Case, Drive, Fail, FrameExpect, TestResult};
427    use day_reactive::Signal;
428    use day_spec::{Insets, kinds};
429
430    use crate::*;
431
432    /// A form's rows hold their controls, and a control in a form works as anywhere else.
433    #[day_macros::test(day_core)]
434    fn form_sections() -> Case {
435        let name = Signal::new(String::new());
436        let on = Signal::new(false);
437        Case::new()
438            .proves_modifier("grow")
439            .page(move || {
440                form((
441                    section((labeled("Name", text_field(name).id(day_core::id!(name))),))
442                        .title("Profile"),
443                    section((labeled("Updates", toggle(on).id(day_core::id!(updates))),))
444                        .title("Mail"),
445                ))
446                .id(day_core::id!(form))
447            })
448            .shot("default")
449            .drive(|d: Drive| async move {
450                d.input("name", "Ada").await?;
451                d.assert_text("name", "Ada").await?;
452                d.toggle("updates", true).await?;
453                d.assert_on("updates", true).await
454            })
455    }
456
457    /// Every row's control starts at the same x: the form shares one label column.
458    #[day_macros::test(day_core)]
459    fn labeled_aligns_controls() -> Case {
460        let (a, b) = (Signal::new(String::new()), Signal::new(String::new()));
461        Case::new()
462            .page(move || {
463                form((section((
464                    labeled("Name", text_field(a).id(day_core::id!(short))),
465                    labeled("A much longer label", text_field(b).id(day_core::id!(long))),
466                )),))
467            })
468            .drive(|d: Drive| async move {
469                d.assert_frame(
470                    "short",
471                    FrameExpect {
472                        x: Some(0.0),
473                        relative_to: Some("long".into()),
474                        ..Default::default()
475                    },
476                )
477                .await
478            })
479    }
480
481    /// Compare native widgets, not just the layout's intended boxes. Native theme margins
482    /// can move a control after Day has centered it (ArkUI switches used to do this).
483    /// Both children have the same Day parent; native frames share window coordinates.
484    fn control_alignment(row_id: &str, control_id: &str) -> TestResult {
485        day_core::try_with_tree(|t| {
486            let row = t.find_by_id(row_id).ok_or_else(|| Fail(format!("no row {row_id}")))?;
487            let label = t.first_child(row).ok_or_else(|| Fail(format!("no label in {row_id}")))?;
488            let control = t.find_by_id(control_id).ok_or_else(|| Fail(format!("no control {control_id}")))?;
489            let frames = |node| -> Result<_, Fail> {
490                let day = t.node_frame(node).ok_or_else(|| Fail("no Day frame".into()))?;
491                let native = t.read_native(node).and_then(|n| n.frame)
492                    .ok_or_else(|| Fail(format!("{row_id}: native frame unavailable")))?;
493                Ok((day, native))
494            };
495            let (ld, ln) = frames(label)?;
496            let (cd, cn) = frames(control)?;
497            for (source, l, c) in [("Day", ld, cd), ("native", ln, cn)] {
498                let delta = c.origin.y + c.size.height / 2.0 - l.origin.y - l.size.height / 2.0;
499                if l.size.height <= 0.0 || c.size.height <= 0.0 || delta.abs() > 1.5 {
500                    return Err(Fail(format!("{row_id}: {source} control/label centers differ by {delta:.2}; label {l:?}, control {c:?}")));
501                }
502            }
503            // A common window offset is harmless, an extra control-only margin is not.
504            let dx = (cn.origin.x - ln.origin.x) - (cd.origin.x - ld.origin.x);
505            if dx.abs() > 1.5 {
506                return Err(Fail(format!("{row_id}: native control/label spacing shifted by {dx:.2}")));
507            }
508            Ok(())
509        }).unwrap_or_else(|| Err(Fail("the tree is busy".into())))
510    }
511
512    async fn controls_align(d: &Drive, pairs: &[(&str, &str)]) -> TestResult {
513        // Give native layout a turn after realization or a value change. Retry geometry,
514        // rather than depending on one fixed sleep on a loaded emulator.
515        for attempt in 0..100 {
516            let result = pairs
517                .iter()
518                .try_for_each(|(row, control)| control_alignment(row, control));
519            if result.is_ok() || attempt == 99 {
520                return result;
521            }
522            d.pause(0.02).await?;
523        }
524        unreachable!()
525    }
526
527    #[day_macros::test(day_core)]
528    fn labeled_nontext_controls_center() -> Case {
529        let a = Signal::new(false);
530        let b = Signal::new(true);
531        let value = Signal::new(0.5);
532        Case::new()
533            .proves(kinds::TOGGLE)
534            .proves(kinds::SLIDER)
535            .proves_duty("set_frame")
536            .page(move || {
537                column((
538                    // The Tree page's two labeled switches, outside a form.
539                    row((
540                        labeled("Multi", toggle(a).id(day_core::id!(pair_a)))
541                            .id(day_core::id!(pair_a_row)),
542                        labeled("Lock", toggle(b).id(day_core::id!(pair_b)))
543                            .id(day_core::id!(pair_b_row)),
544                    ))
545                    .spacing(16.0)
546                    .fit(RowFit::Wrap { run_spacing: 8.0 }),
547                    form((section((
548                        labeled("Updates", toggle(a).id(day_core::id!(form_toggle)))
549                            .id(day_core::id!(form_toggle_row)),
550                        labeled("Level", slider(value).id(day_core::id!(form_slider)))
551                            .id(day_core::id!(form_slider_row)),
552                    )),)),
553                ))
554                .spacing(12.0)
555                .width(300.0)
556            })
557            .drive(|d: Drive| async move {
558                let pairs = [
559                    ("pair_a_row", "pair_a"),
560                    ("pair_b_row", "pair_b"),
561                    ("form_toggle_row", "form_toggle"),
562                    ("form_slider_row", "form_slider"),
563                ];
564                controls_align(&d, &pairs).await?;
565                d.shot("centered-controls").await?;
566                d.toggle("pair_a", true).await?;
567                d.toggle("pair_b", false).await?;
568                d.wait_idle().await?;
569                controls_align(&d, &pairs).await
570            })
571    }
572
573    #[day_macros::test(day_core)]
574    fn row_nontext_controls_center() -> Case {
575        let on = Signal::new(true);
576        let value = Signal::new(0.5);
577        Case::new()
578            .proves(kinds::TOGGLE)
579            .proves(kinds::SLIDER)
580            .proves_duty("set_frame")
581            .page(move || {
582                column((
583                    row((label("Switch"), toggle(on).id(day_core::id!(row_toggle))))
584                        .spacing(12.0)
585                        .id(day_core::id!(toggle_row)),
586                    row((label("Level"), slider(value).id(day_core::id!(row_slider))))
587                        .spacing(12.0)
588                        .id(day_core::id!(slider_row)),
589                ))
590                .spacing(16.0)
591                .padding(Insets::all(18.0))
592            })
593            .drive(|d: Drive| async move {
594                let pairs = [("toggle_row", "row_toggle"), ("slider_row", "row_slider")];
595                controls_align(&d, &pairs).await?;
596                d.toggle("row_toggle", false).await?;
597                d.wait_idle().await?;
598                controls_align(&d, &pairs).await
599            })
600    }
601
602    /// Narrow inspector rows must wrap whole label/control pairs, and action bars must
603    /// keep their last button on screen rather than silently clipping it at the right edge.
604    #[day_macros::test(day_core)]
605    fn wrapped_controls_stay_inside_row() -> Case {
606        let on = Signal::new(false);
607        Case::new()
608            .proves(kinds::CONTAINER)
609            .proves(kinds::TOGGLE)
610            .proves(kinds::BUTTON)
611            .proves_duty("set_frame")
612            .page(move || {
613                column((
614                    row((
615                        labeled("Pause delivery", toggle(on).id(day_core::id!(pause)))
616                            .id(day_core::id!(pause_row)),
617                        labeled("Go offline", toggle(on).id(day_core::id!(offline)))
618                            .id(day_core::id!(offline_row)),
619                    ))
620                    .spacing(16.0)
621                    .fit(RowFit::Wrap { run_spacing: 8.0 })
622                    .id(day_core::id!(wrapped_pairs))
623                    .width(220.0),
624                    row((
625                        button("Add task").id(day_core::id!(add)),
626                        button("Delete selected").id(day_core::id!(delete)),
627                        button("Undo").id(day_core::id!(undo)),
628                        button("Redo").id(day_core::id!(redo)),
629                    ))
630                    .spacing(8.0)
631                    .fit(RowFit::Wrap { run_spacing: 8.0 })
632                    .id(day_core::id!(wrapped_actions))
633                    .width(220.0),
634                ))
635                .spacing(20.0)
636            })
637            .drive(|d: Drive| async move {
638                controls_align(&d, &[("pause_row", "pause"), ("offline_row", "offline")]).await?;
639                d.shot("wrapped-controls").await?;
640                day_core::with_tree(|t| {
641                    let frame = |id| {
642                        t.find_by_id(id)
643                            .and_then(|n| t.read_native(n))
644                            .and_then(|s| s.frame)
645                            .ok_or_else(|| Fail(format!("{id}: native frame unavailable")))
646                    };
647                    for (parent, children) in [
648                        ("wrapped_pairs", &["pause", "offline"][..]),
649                        ("wrapped_actions", &["add", "delete", "undo", "redo"][..]),
650                    ] {
651                        let bounds = frame(parent)?;
652                        for &id in children {
653                            let f = frame(id)?;
654                            d.check(
655                                f.origin.x >= bounds.origin.x - 1.5
656                                    && f.origin.y >= bounds.origin.y - 1.5
657                                    && f.origin.x + f.size.width
658                                        <= bounds.origin.x + bounds.size.width + 1.5
659                                    && f.origin.y + f.size.height
660                                        <= bounds.origin.y + bounds.size.height + 1.5,
661                                &format!("{id} {f:?} extends outside {parent} {bounds:?}"),
662                            )?;
663                        }
664                        let first = frame(children[0])?;
665                        let last = frame(children[children.len() - 1])?;
666                        d.check(
667                            last.origin.y >= first.origin.y + first.size.height,
668                            &format!("{parent}: controls did not wrap onto another line"),
669                        )?;
670                    }
671                    Ok(())
672                })
673            })
674    }
675}