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 corner_radius: SECTION_RADIUS,
114 clips: true,
115 role: Some(day_spec::SurfaceRole::SectionCard),
116 ..Default::default()
117 },
118 Rc::new(SectionCardLayout),
119 Flex {
120 grow_w: true,
121 ..Default::default()
122 },
123 Boundary::No,
124 );
125 let inner = column(children)
126 .spacing(10.0)
127 .align(HAlign::Leading)
128 .padding(14.0);
129 cx.under(node, |cx| {
130 let _ = inner.build(cx);
131 });
132 node
133 });
134 let note = |t: TextSource| Label::from_source(t).font(Font::Footnote);
135 let footer_insets = day_spec::Insets {
136 top: 0.0,
137 leading: 12.0,
138 bottom: 0.0,
139 trailing: 12.0,
140 };
141 match (self.title, self.footer) {
142 (None, None) => card.build(cx),
143 (Some(t), None) => column((note(t), card))
144 .spacing(6.0)
145 .align(HAlign::Leading)
146 .build(cx),
147 (None, Some(f)) => column((card, note(f).secondary().padding(footer_insets)))
148 .spacing(6.0)
149 .align(HAlign::Leading)
150 .build(cx),
151 (Some(t), Some(f)) => {
152 column((note(t), card, note(f).secondary().padding(footer_insets)))
153 .spacing(6.0)
154 .align(HAlign::Leading)
155 .build(cx)
156 }
157 }
158 }
159}
160
161struct SectionCardLayout;
164
165impl day_core::Layout for SectionCardLayout {
166 fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
167 let cs = children.first().map_or(Size::ZERO, |&c| {
168 cx.measure_child(c, Proposal::new(p.width, None))
169 });
170 Size::new(p.width.unwrap_or(cs.width).max(cs.width), cs.height)
171 }
172 fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
173 if let Some(&c) = children.first() {
174 let s = cx.measure_child(c, Proposal::new(Some(bounds.size.width), None));
175 cx.place_child(c, Rect::new(0.0, 0.0, bounds.size.width, s.height));
176 }
177 }
178}
179
180pub fn labeled<M, P: Piece>(text: impl IntoText<M>, control: P) -> Labeled<P> {
187 Labeled {
188 text: text.into_text(),
189 control,
190 }
191}
192
193pub struct Labeled<P: Piece> {
195 text: TextSource,
196 control: P,
197}
198
199impl<P: Piece> Piece for Labeled<P> {
200 fn build(self, cx: &mut BuildCx) -> RNode {
201 let Labeled { text, control } = self;
202 let a11y_text = text.clone();
203 let col = environment::<FormLabelColumn>();
205 let node = cx.layout_only(
206 Rc::new(LabeledLayout { col }),
207 Flex {
208 grow_w: true,
209 ..Default::default()
210 },
211 Boundary::No,
212 );
213 cx.under(node, |cx| {
214 let row_label = Label::from_source(text);
215 let _ = row_label.build(cx);
216 let ctl = control.build(cx);
217 name_control(ctl, &a11y_text);
218 });
219 node
220 }
221}
222
223fn name_control(ctl: RNode, text: &TextSource) {
226 let named = with_tree(|t| t.node_a11y(ctl)).is_some_and(|a| a.label.is_some());
227 if named {
228 return;
229 }
230 let label = |s: String| day_spec::A11yProps {
231 label: Some(s),
232 ..Default::default()
233 };
234 match text {
235 TextSource::Static(s) => with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
236 TextSource::Dyn(read) => {
237 let read = read.clone();
238 let seed = day_reactive::untrack(|| read());
239 with_tree(|t| t.set_a11y(ctl, label(seed.clone())));
240 day_reactive::bind_seeded(
241 seed,
242 move || read(),
243 move |s: &String| with_tree(|t| t.set_a11y(ctl, label(s.clone()))),
244 );
245 }
246 }
247}
248
249struct LabeledLayout {
250 col: Option<FormLabelColumn>,
251}
252
253impl LabeledLayout {
254 fn column_width(&self, label_w: f64) -> f64 {
259 match &self.col {
260 Some(c) => {
261 if label_w > c.0.get() {
262 c.0.set(label_w);
263 }
264 c.0.get()
265 }
266 None => label_w,
267 }
268 }
269}
270
271impl LabeledLayout {
272 fn baseline_shift(
279 cx: &mut dyn day_core::LayoutOps,
280 lbl: RNode,
281 ls: Size,
282 ctl: RNode,
283 cs: Size,
284 ) -> Option<(f64, f64, f64)> {
285 let lb = cx.baseline_of(lbl, ls)?;
286 let cb = cx.baseline_of(ctl, cs)?;
287 let deepest = lb.max(cb);
288 let height = deepest + (ls.height - lb).max(cs.height - cb);
290 Some((deepest - lb, deepest - cb, height))
291 }
292}
293
294impl LabeledLayout {
295 fn stacks(cx: &mut dyn day_core::LayoutOps, ctl: RNode, label_w: f64, width: f64) -> bool {
305 let avail = (width - label_w - LABELED_GAP).max(0.0);
306 let measured = cx
307 .measure_child(ctl, Proposal::new(Some(avail), None))
308 .width;
309 measured > avail + 0.5
310 }
311}
312
313impl day_core::Layout for LabeledLayout {
314 fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
315 let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
316 return Size::ZERO;
317 };
318 let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
319 if let Some(w) = p.width
320 && Self::stacks(cx, ctl, ls.width, w)
321 {
322 let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
323 return Size::new(w, ls.height + STACKED_GAP + cs.height);
324 }
325 let colw = self.column_width(ls.width);
326 let avail = p.width.map(|w| (w - colw - LABELED_GAP).max(0.0));
327 let cs = cx.measure_child(ctl, Proposal::new(avail, None));
328 let natural = colw + LABELED_GAP + cs.width;
329 let boxes = ls.height.max(cs.height);
333 let height = match Self::baseline_shift(cx, lbl, ls, ctl, cs) {
334 Some((_, _, h)) => h.max(boxes),
335 None => boxes,
336 };
337 Size::new(p.width.unwrap_or(natural).max(natural), height)
338 }
339
340 fn baseline(
343 &self,
344 cx: &mut dyn day_core::LayoutOps,
345 children: &[RNode],
346 size: Size,
347 ) -> Option<f64> {
348 let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
349 return None;
350 };
351 let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
352 if Self::stacks(cx, ctl, ls.width, size.width) {
353 return cx.baseline_of(lbl, ls);
355 }
356 let colw = self.column_width(ls.width);
357 let avail = (size.width - colw - LABELED_GAP).max(0.0);
358 let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
359 let lb = cx.baseline_of(lbl, ls)?;
360 let (shift, _, _) = Self::baseline_shift(cx, lbl, ls, ctl, cs)?;
361 Some(shift + lb)
362 }
363 fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
364 let (Some(&lbl), Some(&ctl)) = (children.first(), children.get(1)) else {
365 return;
366 };
367 let ls = cx.measure_child(lbl, Proposal::UNCONSTRAINED);
368 if Self::stacks(cx, ctl, ls.width, bounds.size.width) {
369 let w = bounds.size.width;
372 let cs = cx.measure_child(ctl, Proposal::new(Some(w), None));
373 cx.place_child(lbl, Rect::new(0.0, 0.0, ls.width.min(w), ls.height));
374 let cw = if cx.flex_of(ctl).grow_w {
375 w
376 } else {
377 cs.width.min(w)
378 };
379 cx.place_child(ctl, Rect::new(0.0, ls.height + STACKED_GAP, cw, cs.height));
380 return;
381 }
382 let colw = self.column_width(ls.width);
383 let avail = (bounds.size.width - colw - LABELED_GAP).max(0.0);
384 let cs = cx.measure_child(ctl, Proposal::new(Some(avail), None));
385 let h = bounds.size.height;
386 let (lbl_y, ctl_y) = match Self::baseline_shift(cx, lbl, ls, ctl, cs) {
391 Some((dl, dc, used)) => {
392 let slack = ((h - used) / 2.0).max(0.0);
396 (slack + dl, slack + dc)
397 }
398 None => (
399 ((h - ls.height) / 2.0).max(0.0),
400 ((h - cs.height) / 2.0).max(0.0),
401 ),
402 };
403 cx.place_child(
404 lbl,
405 Rect::new((colw - ls.width).max(0.0), lbl_y, ls.width, ls.height),
406 );
407 let cw = if cx.flex_of(ctl).grow_w {
409 avail
410 } else {
411 cs.width.min(avail)
412 };
413 cx.place_child(ctl, Rect::new(colw + LABELED_GAP, ctl_y, cw, cs.height));
414 }
415}
416
417#[cfg(feature = "conformance")]
425pub(crate) mod conformance {
426 use day_core::conformance::{Case, Drive, Fail, FrameExpect, TestResult};
427 use day_reactive::Signal;
428 use day_spec::{Insets, kinds};
429
430 use crate::*;
431
432 #[day_macros::test(day_core)]
434 fn form_sections() -> Case {
435 let name = Signal::new(String::new());
436 let on = Signal::new(false);
437 Case::new()
438 .proves_modifier("grow")
439 .page(move || {
440 form((
441 section((labeled("Name", text_field(name).id(day_core::id!(name))),))
442 .title("Profile"),
443 section((labeled("Updates", toggle(on).id(day_core::id!(updates))),))
444 .title("Mail"),
445 ))
446 .id(day_core::id!(form))
447 })
448 .shot("default")
449 .drive(|d: Drive| async move {
450 d.input("name", "Ada").await?;
451 d.assert_text("name", "Ada").await?;
452 d.toggle("updates", true).await?;
453 d.assert_on("updates", true).await
454 })
455 }
456
457 #[day_macros::test(day_core)]
459 fn labeled_aligns_controls() -> Case {
460 let (a, b) = (Signal::new(String::new()), Signal::new(String::new()));
461 Case::new()
462 .page(move || {
463 form((section((
464 labeled("Name", text_field(a).id(day_core::id!(short))),
465 labeled("A much longer label", text_field(b).id(day_core::id!(long))),
466 )),))
467 })
468 .drive(|d: Drive| async move {
469 d.assert_frame(
470 "short",
471 FrameExpect {
472 x: Some(0.0),
473 relative_to: Some("long".into()),
474 ..Default::default()
475 },
476 )
477 .await
478 })
479 }
480
481 fn control_alignment(row_id: &str, control_id: &str) -> TestResult {
485 day_core::try_with_tree(|t| {
486 let row = t.find_by_id(row_id).ok_or_else(|| Fail(format!("no row {row_id}")))?;
487 let label = t.first_child(row).ok_or_else(|| Fail(format!("no label in {row_id}")))?;
488 let control = t.find_by_id(control_id).ok_or_else(|| Fail(format!("no control {control_id}")))?;
489 let frames = |node| -> Result<_, Fail> {
490 let day = t.node_frame(node).ok_or_else(|| Fail("no Day frame".into()))?;
491 let native = t.read_native(node).and_then(|n| n.frame)
492 .ok_or_else(|| Fail(format!("{row_id}: native frame unavailable")))?;
493 Ok((day, native))
494 };
495 let (ld, ln) = frames(label)?;
496 let (cd, cn) = frames(control)?;
497 for (source, l, c) in [("Day", ld, cd), ("native", ln, cn)] {
498 let delta = c.origin.y + c.size.height / 2.0 - l.origin.y - l.size.height / 2.0;
499 if l.size.height <= 0.0 || c.size.height <= 0.0 || delta.abs() > 1.5 {
500 return Err(Fail(format!("{row_id}: {source} control/label centers differ by {delta:.2}; label {l:?}, control {c:?}")));
501 }
502 }
503 let dx = (cn.origin.x - ln.origin.x) - (cd.origin.x - ld.origin.x);
505 if dx.abs() > 1.5 {
506 return Err(Fail(format!("{row_id}: native control/label spacing shifted by {dx:.2}")));
507 }
508 Ok(())
509 }).unwrap_or_else(|| Err(Fail("the tree is busy".into())))
510 }
511
512 async fn controls_align(d: &Drive, pairs: &[(&str, &str)]) -> TestResult {
513 for attempt in 0..100 {
516 let result = pairs
517 .iter()
518 .try_for_each(|(row, control)| control_alignment(row, control));
519 if result.is_ok() || attempt == 99 {
520 return result;
521 }
522 d.pause(0.02).await?;
523 }
524 unreachable!()
525 }
526
527 #[day_macros::test(day_core)]
528 fn labeled_nontext_controls_center() -> Case {
529 let a = Signal::new(false);
530 let b = Signal::new(true);
531 let value = Signal::new(0.5);
532 Case::new()
533 .proves(kinds::TOGGLE)
534 .proves(kinds::SLIDER)
535 .proves_duty("set_frame")
536 .page(move || {
537 column((
538 row((
540 labeled("Multi", toggle(a).id(day_core::id!(pair_a)))
541 .id(day_core::id!(pair_a_row)),
542 labeled("Lock", toggle(b).id(day_core::id!(pair_b)))
543 .id(day_core::id!(pair_b_row)),
544 ))
545 .spacing(16.0)
546 .fit(RowFit::Wrap { run_spacing: 8.0 }),
547 form((section((
548 labeled("Updates", toggle(a).id(day_core::id!(form_toggle)))
549 .id(day_core::id!(form_toggle_row)),
550 labeled("Level", slider(value).id(day_core::id!(form_slider)))
551 .id(day_core::id!(form_slider_row)),
552 )),)),
553 ))
554 .spacing(12.0)
555 .width(300.0)
556 })
557 .drive(|d: Drive| async move {
558 let pairs = [
559 ("pair_a_row", "pair_a"),
560 ("pair_b_row", "pair_b"),
561 ("form_toggle_row", "form_toggle"),
562 ("form_slider_row", "form_slider"),
563 ];
564 controls_align(&d, &pairs).await?;
565 d.shot("centered-controls").await?;
566 d.toggle("pair_a", true).await?;
567 d.toggle("pair_b", false).await?;
568 d.wait_idle().await?;
569 controls_align(&d, &pairs).await
570 })
571 }
572
573 #[day_macros::test(day_core)]
574 fn row_nontext_controls_center() -> Case {
575 let on = Signal::new(true);
576 let value = Signal::new(0.5);
577 Case::new()
578 .proves(kinds::TOGGLE)
579 .proves(kinds::SLIDER)
580 .proves_duty("set_frame")
581 .page(move || {
582 column((
583 row((label("Switch"), toggle(on).id(day_core::id!(row_toggle))))
584 .spacing(12.0)
585 .id(day_core::id!(toggle_row)),
586 row((label("Level"), slider(value).id(day_core::id!(row_slider))))
587 .spacing(12.0)
588 .id(day_core::id!(slider_row)),
589 ))
590 .spacing(16.0)
591 .padding(Insets::all(18.0))
592 })
593 .drive(|d: Drive| async move {
594 let pairs = [("toggle_row", "row_toggle"), ("slider_row", "row_slider")];
595 controls_align(&d, &pairs).await?;
596 d.toggle("row_toggle", false).await?;
597 d.wait_idle().await?;
598 controls_align(&d, &pairs).await
599 })
600 }
601
602 #[day_macros::test(day_core)]
605 fn wrapped_controls_stay_inside_row() -> Case {
606 let on = Signal::new(false);
607 Case::new()
608 .proves(kinds::CONTAINER)
609 .proves(kinds::TOGGLE)
610 .proves(kinds::BUTTON)
611 .proves_duty("set_frame")
612 .page(move || {
613 column((
614 row((
615 labeled("Pause delivery", toggle(on).id(day_core::id!(pause)))
616 .id(day_core::id!(pause_row)),
617 labeled("Go offline", toggle(on).id(day_core::id!(offline)))
618 .id(day_core::id!(offline_row)),
619 ))
620 .spacing(16.0)
621 .fit(RowFit::Wrap { run_spacing: 8.0 })
622 .id(day_core::id!(wrapped_pairs))
623 .width(220.0),
624 row((
625 button("Add task").id(day_core::id!(add)),
626 button("Delete selected").id(day_core::id!(delete)),
627 button("Undo").id(day_core::id!(undo)),
628 button("Redo").id(day_core::id!(redo)),
629 ))
630 .spacing(8.0)
631 .fit(RowFit::Wrap { run_spacing: 8.0 })
632 .id(day_core::id!(wrapped_actions))
633 .width(220.0),
634 ))
635 .spacing(20.0)
636 })
637 .drive(|d: Drive| async move {
638 controls_align(&d, &[("pause_row", "pause"), ("offline_row", "offline")]).await?;
639 d.shot("wrapped-controls").await?;
640 day_core::with_tree(|t| {
641 let frame = |id| {
642 t.find_by_id(id)
643 .and_then(|n| t.read_native(n))
644 .and_then(|s| s.frame)
645 .ok_or_else(|| Fail(format!("{id}: native frame unavailable")))
646 };
647 for (parent, children) in [
648 ("wrapped_pairs", &["pause", "offline"][..]),
649 ("wrapped_actions", &["add", "delete", "undo", "redo"][..]),
650 ] {
651 let bounds = frame(parent)?;
652 for &id in children {
653 let f = frame(id)?;
654 d.check(
655 f.origin.x >= bounds.origin.x - 1.5
656 && f.origin.y >= bounds.origin.y - 1.5
657 && f.origin.x + f.size.width
658 <= bounds.origin.x + bounds.size.width + 1.5
659 && f.origin.y + f.size.height
660 <= bounds.origin.y + bounds.size.height + 1.5,
661 &format!("{id} {f:?} extends outside {parent} {bounds:?}"),
662 )?;
663 }
664 let first = frame(children[0])?;
665 let last = frame(children[children.len() - 1])?;
666 d.check(
667 last.origin.y >= first.origin.y + first.size.height,
668 &format!("{parent}: controls did not wrap onto another line"),
669 )?;
670 }
671 Ok(())
672 })
673 })
674 }
675}