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
68#[must_use]
74pub struct FormSection<C: PieceSeq> {
75 title: Option<TextSource>,
76 footer: Option<TextSource>,
77 children: C,
78}
79
80pub 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 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
94 self.title = Some(t.into_text());
95 self
96 }
97 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
177struct 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
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: 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
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 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 let height = deepest + (ls.height - lb).max(cs.height - cb);
322 Some((deepest - lb, deepest - cb, height))
323 }
324}
325
326impl LabeledLayout {
327 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 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 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 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 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 let (lbl_y, ctl_y) = match Self::baseline_shift(cx, lbl, ls, ctl, cs) {
423 Some((dl, dc, used)) => {
424 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 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#[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 #[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 #[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 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 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 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 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 #[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}