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.
73pub struct FormSection<C: PieceSeq> {
74    title: Option<TextSource>,
75    footer: Option<TextSource>,
76    children: C,
77}
78
79/// A grouped card of form rows; `.title(…)` adds the header. Works inside a [`form`] (shared
80/// label column) or standalone.
81pub fn section<C: PieceSeq + 'static>(children: C) -> FormSection<C> {
82    FormSection {
83        title: None,
84        footer: None,
85        children,
86    }
87}
88
89#[day_macros::builder(FormSectionBuilder)]
90impl<C: PieceSeq + 'static> FormSection<C> {
91    /// The section header, shown above the card in the footnote style.
92    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
93        self.title = Some(t.into_text());
94        self
95    }
96    /// The section footer, shown under the card in the footnote style: the explanatory line
97    /// settings screens put beneath a group of rows (iOS section footers, libadwaita's group
98    /// description).
99    pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
100        self.footer = Some(t.into_text());
101        self
102    }
103}
104
105impl<C: PieceSeq + 'static> Piece for FormSection<C> {
106    fn build(self, cx: &mut BuildCx) -> RNode {
107        let children = self.children;
108        let card = piece_fn(move |cx: &mut BuildCx| {
109            let node = cx.native(
110                kinds::CONTAINER,
111                &ContainerProps {
112                    background: None,
113                    corner_radius: SECTION_RADIUS,
114                    clips: true,
115                    role: Some(day_spec::SurfaceRole::SectionCard),
116                },
117                Rc::new(SectionCardLayout),
118                Flex {
119                    grow_w: true,
120                    ..Default::default()
121                },
122                Boundary::No,
123            );
124            let inner = column(children)
125                .spacing(10.0)
126                .align(HAlign::Leading)
127                .padding(14.0);
128            cx.under(node, |cx| {
129                let _ = inner.build(cx);
130            });
131            node
132        });
133        let note = |t: TextSource| Label {
134            text: t,
135            font: Font::Footnote,
136            font_scale: 1.0,
137            weight: None,
138            italic: false,
139            tabular: false,
140            monospace: false,
141            wraps: true,
142            max_lines: 0,
143            runs: Vec::new(),
144            markdown: false,
145            align: day_spec::props::TextAlign::Leading,
146            on_link: None,
147            color: None,
148            role: Default::default(),
149        };
150        let footer_insets = day_spec::Insets {
151            top: 0.0,
152            leading: 12.0,
153            bottom: 0.0,
154            trailing: 12.0,
155        };
156        match (self.title, self.footer) {
157            (None, None) => card.build(cx),
158            (Some(t), None) => column((note(t), card))
159                .spacing(6.0)
160                .align(HAlign::Leading)
161                .build(cx),
162            (None, Some(f)) => column((card, note(f).secondary().padding(footer_insets)))
163                .spacing(6.0)
164                .align(HAlign::Leading)
165                .build(cx),
166            (Some(t), Some(f)) => {
167                column((note(t), card, note(f).secondary().padding(footer_insets)))
168                    .spacing(6.0)
169                    .align(HAlign::Leading)
170                    .build(cx)
171            }
172        }
173    }
174}
175
176/// The card fills the width its parent proposes (uniform card widths down a form) and hugs
177/// its padded content vertically.
178struct SectionCardLayout;
179
180impl day_core::Layout for SectionCardLayout {
181    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
182        let cs = children
183            .first()
184            .map(|&c| cx.measure_child(c, Proposal::new(p.width, None)))
185            .unwrap_or(Size::ZERO);
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: Default::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        &self,
312        cx: &mut dyn day_core::LayoutOps,
313        lbl: RNode,
314        ls: Size,
315        ctl: RNode,
316        cs: Size,
317    ) -> Option<(f64, f64, f64)> {
318        let lb = cx.baseline_of(lbl, ls)?;
319        let cb = cx.baseline_of(ctl, cs)?;
320        let deepest = lb.max(cb);
321        // Descent below the shared line decides the rest of the height.
322        let height = deepest + (ls.height - lb).max(cs.height - cb);
323        Some((deepest - lb, deepest - cb, height))
324    }
325}
326
327impl LabeledLayout {
328    /// Whether the control has to go under the label: offered the width left beside this
329    /// row's own label, it still measures wider (a two-button stepper in a 280 dp inspector;
330    /// a fixed-width field). A narrow pane then reads as the settings idiom (label above,
331    /// control full-width) instead of clipping the control at the pane's edge.
332    ///
333    /// The row's label, not the form-wide column: the column grows as the form's rows are
334    /// measured, so a decision taken against it would flip between measure and place and
335    /// the rows would overlap. A `.grow(Dimension::Both)` control measures to what it is offered, so it
336    /// stacks only when its content cannot fit that width.
337    fn stacks(
338        &self,
339        cx: &mut dyn day_core::LayoutOps,
340        ctl: RNode,
341        label_w: f64,
342        width: f64,
343    ) -> bool {
344        let avail = (width - label_w - LABELED_GAP).max(0.0);
345        let measured = cx
346            .measure_child(ctl, Proposal::new(Some(avail), None))
347            .width;
348        measured > avail + 0.5
349    }
350}
351
352impl day_core::Layout for LabeledLayout {
353    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
354        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
355            return Size::ZERO;
356        };
357        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
358        if let Some(w) = p.width
359            && self.stacks(cx, ctl, ls.width, w)
360        {
361            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
362            return Size::new(w, ls.height + STACKED_GAP + cs.height);
363        }
364        let colw = self.column_width(ls.width);
365        let avail = p.width.map(|w| (w - colw - LABELED_GAP).max(0.0));
366        let cs = cx.measure_child(ctl, Proposal::new(avail, None));
367        let natural = colw + LABELED_GAP + cs.width;
368        // The row spans the proposed width (labels align form-wide; controls may stretch), and
369        // hugs its content vertically: the taller child, or, once the two are sitting on one
370        // baseline, whatever the shifted pair needs.
371        let boxes = ls.height.max(cs.height);
372        let height = match self.baseline_shift(cx, lbl, ls, ctl, cs) {
373            Some((_, _, h)) => h.max(boxes),
374            None => boxes,
375        };
376        Size::new(p.width.unwrap_or(natural).max(natural), height)
377    }
378
379    /// The row's own baseline is the line its label and control were put on, so a `labeled`
380    /// nested inside another baseline-aligned row joins that line too (docs/baseline.md).
381    fn baseline(
382        &self,
383        cx: &mut dyn day_core::LayoutOps,
384        children: &[RNode],
385        size: Size,
386    ) -> Option<f64> {
387        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
388            return None;
389        };
390        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
391        if self.stacks(cx, ctl, ls.width, size.width) {
392            // Stacked: the label's own line is the row's.
393            return cx.baseline_of(lbl, ls);
394        }
395        let colw = self.column_width(ls.width);
396        let avail = (size.width - colw - LABELED_GAP).max(0.0);
397        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
398        let lb = cx.baseline_of(lbl, ls)?;
399        let (shift, _, _) = self.baseline_shift(cx, lbl, ls, ctl, cs)?;
400        Some(shift + lb)
401    }
402    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
403        let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
404            return;
405        };
406        let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
407        if self.stacks(cx, ctl, ls.width, bounds.size.width) {
408            // Label at the leading edge, control under it across the whole row (a hugging
409            // control keeps its own width; a `.grow(Dimension::Both)` one takes the row).
410            let w = bounds.size.width;
411            let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
412            cx.place_child(lbl, Rect::new(0.0, 0.0, ls.width.min(w), ls.height));
413            let cw = if cx.flex_of(ctl).grow_w {
414                w
415            } else {
416                cs.width.min(w)
417            };
418            cx.place_child(ctl, Rect::new(0.0, ls.height + STACKED_GAP, cw, cs.height));
419            return;
420        }
421        let colw = self.column_width(ls.width);
422        let avail = (bounds.size.width - colw - LABELED_GAP).max(0.0);
423        let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
424        let h = bounds.size.height;
425        // Baseline first, centering as the fallback (docs/baseline.md): a label beside a
426        // bordered field or a stepper has its text a few points off from the field's, because
427        // the two put their text at different heights inside boxes of different heights.
428        // Centering the boxes preserves that offset; this removes it.
429        let (lbl_y, ctl_y) = match self.baseline_shift(cx, lbl, ls, ctl, cs) {
430            Some((dl, dc, used)) => {
431                // Center the aligned pair in whatever height the row was actually given, so a
432                // row stretched by a taller sibling keeps its text group centered rather than
433                // pinned to the top.
434                let slack = ((h - used) / 2.0).max(0.0);
435                (slack + dl, slack + dc)
436            }
437            None => (
438                ((h - ls.height) / 2.0).max(0.0),
439                ((h - cs.height) / 2.0).max(0.0),
440            ),
441        };
442        cx.place_child(
443            lbl,
444            Rect::new((colw - ls.width).max(0.0), lbl_y, ls.width, ls.height),
445        );
446        // `.grow(Dimension::Both)` controls fill the remaining width (text fields, sliders); others hug.
447        let cw = if cx.flex_of(ctl).grow_w {
448            avail
449        } else {
450            cs.width.min(avail)
451        };
452        cx.place_child(ctl, Rect::new(colw + LABELED_GAP, ctl_y, cw, cs.height));
453    }
454}
455
456// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
457
458// ---------------------------------------------------------------------------
459// Conformance cases (docs/testing.md)
460// ---------------------------------------------------------------------------
461
462/// The form pieces' `#[day::test]` cases, next to their constructors.
463#[cfg(feature = "conformance")]
464pub(crate) mod conformance {
465    use day_core::conformance::{Case, Drive, Fail, FrameExpect, TestResult};
466    use day_reactive::Signal;
467    use day_spec::{Insets, kinds};
468
469    use crate::*;
470
471    /// A form's rows hold their controls, and a control in a form works as anywhere else.
472    #[day_macros::test(day_core)]
473    fn form_sections() -> Case {
474        let name = Signal::new(String::new());
475        let on = Signal::new(false);
476        Case::new()
477            .proves_modifier("grow")
478            .page(move || {
479                form((
480                    section((labeled("Name", text_field(name).id(day_core::id!(name))),))
481                        .title("Profile"),
482                    section((labeled("Updates", toggle(on).id(day_core::id!(updates))),))
483                        .title("Mail"),
484                ))
485                .id(day_core::id!(form))
486            })
487            .shot("default")
488            .drive(|d: Drive| async move {
489                d.input("name", "Ada").await?;
490                d.assert_text("name", "Ada").await?;
491                d.toggle("updates", true).await?;
492                d.assert_on("updates", true).await
493            })
494    }
495
496    /// Every row's control starts at the same x: the form shares one label column.
497    #[day_macros::test(day_core)]
498    fn labeled_aligns_controls() -> Case {
499        let (a, b) = (Signal::new(String::new()), Signal::new(String::new()));
500        Case::new()
501            .page(move || {
502                form((section((
503                    labeled("Name", text_field(a).id(day_core::id!(short))),
504                    labeled("A much longer label", text_field(b).id(day_core::id!(long))),
505                )),))
506            })
507            .drive(|d: Drive| async move {
508                d.assert_frame(
509                    "short",
510                    FrameExpect {
511                        x: Some(0.0),
512                        relative_to: Some("long".into()),
513                        ..Default::default()
514                    },
515                )
516                .await
517            })
518    }
519
520    /// Compare native widgets, not just the layout's intended boxes. Native theme margins
521    /// can move a control after Day has centered it (ArkUI switches used to do this).
522    /// Both children have the same Day parent; native frames share window coordinates.
523    fn control_alignment(row_id: &str, control_id: &str) -> TestResult {
524        day_core::try_with_tree(|t| {
525            let row = t.find_by_id(row_id).ok_or_else(|| Fail(format!("no row {row_id}")))?;
526            let label = t.first_child(row).ok_or_else(|| Fail(format!("no label in {row_id}")))?;
527            let control = t.find_by_id(control_id).ok_or_else(|| Fail(format!("no control {control_id}")))?;
528            let frames = |node| -> Result<_, Fail> {
529                let day = t.node_frame(node).ok_or_else(|| Fail("no Day frame".into()))?;
530                let native = t.read_native(node).and_then(|n| n.frame)
531                    .ok_or_else(|| Fail(format!("{row_id}: native frame unavailable")))?;
532                Ok((day, native))
533            };
534            let (ld, ln) = frames(label)?;
535            let (cd, cn) = frames(control)?;
536            for (source, l, c) in [("Day", ld, cd), ("native", ln, cn)] {
537                let delta = c.origin.y + c.size.height / 2.0 - l.origin.y - l.size.height / 2.0;
538                if l.size.height <= 0.0 || c.size.height <= 0.0 || delta.abs() > 1.5 {
539                    return Err(Fail(format!("{row_id}: {source} control/label centers differ by {delta:.2}; label {l:?}, control {c:?}")));
540                }
541            }
542            // A common window offset is harmless, an extra control-only margin is not.
543            let dx = (cn.origin.x - ln.origin.x) - (cd.origin.x - ld.origin.x);
544            if dx.abs() > 1.5 {
545                return Err(Fail(format!("{row_id}: native control/label spacing shifted by {dx:.2}")));
546            }
547            Ok(())
548        }).unwrap_or_else(|| Err(Fail("the tree is busy".into())))
549    }
550
551    async fn controls_align(d: &Drive, pairs: &[(&str, &str)]) -> TestResult {
552        // Give native layout a turn after realization or a value change. Retry geometry,
553        // rather than depending on one fixed sleep on a loaded emulator.
554        for attempt in 0..100 {
555            let result = pairs
556                .iter()
557                .try_for_each(|(row, control)| control_alignment(row, control));
558            if result.is_ok() || attempt == 99 {
559                return result;
560            }
561            d.pause(0.02).await?;
562        }
563        unreachable!()
564    }
565
566    #[day_macros::test(day_core)]
567    fn labeled_nontext_controls_center() -> Case {
568        let a = Signal::new(false);
569        let b = Signal::new(true);
570        let value = Signal::new(0.5);
571        Case::new()
572            .proves(kinds::TOGGLE)
573            .proves(kinds::SLIDER)
574            .proves_duty("set_frame")
575            .page(move || {
576                column((
577                    // The Tree page's two labeled switches, outside a form.
578                    row((
579                        labeled("Multi", toggle(a).id(day_core::id!(pair_a)))
580                            .id(day_core::id!(pair_a_row)),
581                        labeled("Lock", toggle(b).id(day_core::id!(pair_b)))
582                            .id(day_core::id!(pair_b_row)),
583                    ))
584                    .spacing(16.0)
585                    .fit(RowFit::Wrap { run_spacing: 8.0 }),
586                    form((section((
587                        labeled("Updates", toggle(a).id(day_core::id!(form_toggle)))
588                            .id(day_core::id!(form_toggle_row)),
589                        labeled("Level", slider(value).id(day_core::id!(form_slider)))
590                            .id(day_core::id!(form_slider_row)),
591                    )),)),
592                ))
593                .spacing(12.0)
594                .width(300.0)
595            })
596            .drive(|d: Drive| async move {
597                let pairs = [
598                    ("pair_a_row", "pair_a"),
599                    ("pair_b_row", "pair_b"),
600                    ("form_toggle_row", "form_toggle"),
601                    ("form_slider_row", "form_slider"),
602                ];
603                controls_align(&d, &pairs).await?;
604                d.shot("centered-controls").await?;
605                d.toggle("pair_a", true).await?;
606                d.toggle("pair_b", false).await?;
607                d.wait_idle().await?;
608                controls_align(&d, &pairs).await
609            })
610    }
611
612    #[day_macros::test(day_core)]
613    fn row_nontext_controls_center() -> Case {
614        let on = Signal::new(true);
615        let value = Signal::new(0.5);
616        Case::new()
617            .proves(kinds::TOGGLE)
618            .proves(kinds::SLIDER)
619            .proves_duty("set_frame")
620            .page(move || {
621                column((
622                    row((label("Switch"), toggle(on).id(day_core::id!(row_toggle))))
623                        .spacing(12.0)
624                        .id(day_core::id!(toggle_row)),
625                    row((label("Level"), slider(value).id(day_core::id!(row_slider))))
626                        .spacing(12.0)
627                        .id(day_core::id!(slider_row)),
628                ))
629                .spacing(16.0)
630                .padding(Insets::all(18.0))
631            })
632            .drive(|d: Drive| async move {
633                let pairs = [("toggle_row", "row_toggle"), ("slider_row", "row_slider")];
634                controls_align(&d, &pairs).await?;
635                d.toggle("row_toggle", false).await?;
636                d.wait_idle().await?;
637                controls_align(&d, &pairs).await
638            })
639    }
640
641    /// Narrow inspector rows must wrap whole label/control pairs, and action bars must
642    /// keep their last button on screen rather than silently clipping it at the right edge.
643    #[day_macros::test(day_core)]
644    fn wrapped_controls_stay_inside_row() -> Case {
645        let on = Signal::new(false);
646        Case::new()
647            .proves(kinds::CONTAINER)
648            .proves(kinds::TOGGLE)
649            .proves(kinds::BUTTON)
650            .proves_duty("set_frame")
651            .page(move || {
652                column((
653                    row((
654                        labeled("Pause delivery", toggle(on).id(day_core::id!(pause)))
655                            .id(day_core::id!(pause_row)),
656                        labeled("Go offline", toggle(on).id(day_core::id!(offline)))
657                            .id(day_core::id!(offline_row)),
658                    ))
659                    .spacing(16.0)
660                    .fit(RowFit::Wrap { run_spacing: 8.0 })
661                    .id(day_core::id!(wrapped_pairs))
662                    .width(220.0),
663                    row((
664                        button("Add task").id(day_core::id!(add)),
665                        button("Delete selected").id(day_core::id!(delete)),
666                        button("Undo").id(day_core::id!(undo)),
667                        button("Redo").id(day_core::id!(redo)),
668                    ))
669                    .spacing(8.0)
670                    .fit(RowFit::Wrap { run_spacing: 8.0 })
671                    .id(day_core::id!(wrapped_actions))
672                    .width(220.0),
673                ))
674                .spacing(20.0)
675            })
676            .drive(|d: Drive| async move {
677                controls_align(&d, &[("pause_row", "pause"), ("offline_row", "offline")]).await?;
678                d.shot("wrapped-controls").await?;
679                day_core::with_tree(|t| {
680                    let frame = |id| {
681                        t.find_by_id(id)
682                            .and_then(|n| t.read_native(n))
683                            .and_then(|s| s.frame)
684                            .ok_or_else(|| Fail(format!("{id}: native frame unavailable")))
685                    };
686                    for (parent, children) in [
687                        ("wrapped_pairs", &["pause", "offline"][..]),
688                        ("wrapped_actions", &["add", "delete", "undo", "redo"][..]),
689                    ] {
690                        let bounds = frame(parent)?;
691                        for &id in children {
692                            let f = frame(id)?;
693                            d.check(
694                                f.origin.x >= bounds.origin.x - 1.5
695                                    && f.origin.y >= bounds.origin.y - 1.5
696                                    && f.origin.x + f.size.width
697                                        <= bounds.origin.x + bounds.size.width + 1.5
698                                    && f.origin.y + f.size.height
699                                        <= bounds.origin.y + bounds.size.height + 1.5,
700                                &format!("{id} {f:?} extends outside {parent} {bounds:?}"),
701                            )?;
702                        }
703                        let first = frame(children[0])?;
704                        let last = frame(children[children.len() - 1])?;
705                        d.check(
706                            last.origin.y >= first.origin.y + first.size.height,
707                            &format!("{parent}: controls did not wrap onto another line"),
708                        )?;
709                    }
710                    Ok(())
711                })
712            })
713    }
714}