1use 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#[derive(Clone)]
27struct FormLabelColumn(Rc<Cell<f64>>);
28
29const SECTION_RADIUS: f64 = 10.0;
30const LABELED_GAP: f64 = 12.0;
31const STACKED_GAP: f64 = 6.0;
33
34pub fn form<C: PieceSeq + 'static>(sections: C) -> Form<C> {
48 Form { sections }
49}
50
51pub 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 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
68pub struct FormSection<C: PieceSeq> {
74 title: Option<TextSource>,
75 footer: Option<TextSource>,
76 children: C,
77}
78
79pub 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 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
93 self.title = Some(t.into_text());
94 self
95 }
96 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
176struct 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
196pub 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
209pub 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 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
255fn 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 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 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 let height = deepest + (ls.height - lb).max(cs.height - cb);
323 Some((deepest - lb, deepest - cb, height))
324 }
325}
326
327impl LabeledLayout {
328 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 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 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 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 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 let (lbl_y, ctl_y) = match self.baseline_shift(cx, lbl, ls, ctl, cs) {
430 Some((dl, dc, used)) => {
431 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 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#[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 #[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 #[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 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 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 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 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 #[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}