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