1use std::cell::RefCell;
8use std::rc::Rc;
9
10use day_core::*;
11use day_reactive::{bind, bind_seeded};
12use day_spec::props::*;
13use day_spec::{Event, Font, Proposal, Rect, Role, Size, kinds};
14
15use crate::*;
16
17#[derive(Clone, Debug, Default)]
38#[must_use]
39pub struct TextBuilder {
40 text: String,
41 runs: Vec<day_spec::TextRun>,
42 base: Font,
43}
44
45impl TextBuilder {
46 pub fn new() -> Self {
47 Self::default()
48 }
49 pub fn base(mut self, font: Font) -> Self {
52 self.base = font;
53 self
54 }
55 pub fn text(mut self, s: &str) -> Self {
57 self.text.push_str(s);
58 self
59 }
60 pub fn run(
62 mut self,
63 s: &str,
64 run: impl FnOnce(std::ops::Range<usize>) -> day_spec::TextRun,
65 ) -> Self {
66 let start = self.text.len();
67 self.text.push_str(s);
68 self.runs.push(run(start..self.text.len()));
69 self
70 }
71 pub fn strong(self, s: &str) -> Self {
73 let base = self.base;
74 self.run(s, move |range| {
75 day_spec::TextRun::font(
76 range,
77 day_spec::FontSpec {
78 style: base,
79 weight: Some(day_spec::FontWeight::Bold),
80 ..Default::default()
81 },
82 )
83 })
84 }
85 pub fn emphasis(self, s: &str) -> Self {
87 let base = self.base;
88 self.run(s, move |range| {
89 day_spec::TextRun::font(
90 range,
91 day_spec::FontSpec {
92 style: base,
93 italic: true,
94 ..Default::default()
95 },
96 )
97 })
98 }
99 pub fn code(self, s: &str) -> Self {
101 let base = self.base;
102 self.run(s, move |range| {
103 day_spec::TextRun::font(
104 range,
105 day_spec::FontSpec {
106 style: base,
107 monospace: true,
108 ..Default::default()
109 },
110 )
111 })
112 }
113 pub fn colored(self, s: &str, color: day_spec::Color) -> Self {
115 let base = self.base;
116 self.run(s, move |range| day_spec::TextRun {
117 range,
118 font: day_spec::FontSpec::from(base),
119 color: Some(color),
120 ..day_spec::TextRun::default()
121 })
122 }
123 pub fn underline(self, s: &str) -> Self {
125 let base = self.base;
126 self.run(s, move |range| day_spec::TextRun {
127 range,
128 font: day_spec::FontSpec::from(base),
129 underline: day_spec::Underline::Single,
130 ..day_spec::TextRun::default()
131 })
132 }
133 pub fn highlight(self, s: &str, color: day_spec::Color) -> Self {
141 let base = self.base;
142 self.run(s, move |range| day_spec::TextRun {
143 range,
144 font: day_spec::FontSpec::from(base),
145 background: Some(color),
146 color: Some(day_spec::props::ButtonStyleSpec::on_tint(color)),
147 ..day_spec::TextRun::default()
148 })
149 }
150 pub fn sized(self, s: &str, scale: f64) -> Self {
154 let base = self.base;
155 self.run(s, move |range| day_spec::TextRun {
156 range,
157 font: day_spec::FontSpec::from(base).scaled(scale),
158 ..day_spec::TextRun::default()
159 })
160 }
161 pub fn strikethrough(self, s: &str) -> Self {
163 let base = self.base;
164 self.run(s, move |range| day_spec::TextRun {
165 range,
166 font: day_spec::FontSpec::from(base),
167 strikethrough: true,
168 ..day_spec::TextRun::default()
169 })
170 }
171 pub fn link(self, s: &str, target: &str) -> Self {
175 let base = self.base;
176 let target = target.to_string();
177 self.run(s, move |range| day_spec::TextRun {
178 range,
179 font: day_spec::FontSpec::from(base),
180 link: Some(target),
181 ..day_spec::TextRun::default()
182 })
183 }
184 #[must_use]
186 pub fn build(self) -> (String, Vec<day_spec::TextRun>) {
187 (self.text, self.runs)
188 }
189}
190
191#[must_use]
192pub struct Label {
193 pub(crate) text: TextSource,
195 pub(crate) font: Font,
196 pub(crate) font_scale: f64,
197 pub(crate) weight: Option<day_spec::FontWeight>,
198 pub(crate) italic: bool,
199 pub(crate) tabular: bool,
200 pub(crate) monospace: bool,
201 pub(crate) wraps: bool,
202 pub(crate) max_lines: u32,
203 pub(crate) color: Option<Reactive<day_spec::Color>>,
204 pub(crate) role: day_spec::props::TextRole,
206 pub(crate) runs: Vec<day_spec::TextRun>,
208 pub(crate) markdown: bool,
210 pub(crate) align: day_spec::props::TextAlign,
212 pub(crate) on_link: Option<LinkHandler>,
214}
215
216pub(crate) type LinkHandler = Rc<dyn Fn(&str)>;
218
219pub fn label<M>(text: impl IntoText<M>) -> Label {
220 Label {
221 text: text.into_text(),
222 font: Font::Body,
223 font_scale: 1.0,
224 weight: None,
225 italic: false,
226 tabular: false,
227 monospace: false,
228 wraps: true,
229 max_lines: 0,
230 color: None,
231 role: TextRole::default(),
232 runs: Vec::new(),
233 markdown: false,
234 align: day_spec::props::TextAlign::Leading,
235 on_link: None,
236 }
237}
238
239#[day_macros::builder(LabelBuilder)]
240impl Label {
241 pub fn single_line(mut self) -> Self {
243 self.wraps = false;
244 self
245 }
246 pub fn max_lines(mut self, lines: u32) -> Self {
249 self.max_lines = lines;
250 self
251 }
252 pub fn font(mut self, f: Font) -> Self {
255 self.font = f;
256 self
257 }
258 pub fn font_scale(mut self, scale: f64) -> Self {
261 self.font_scale = if scale.is_finite() && scale > 0.0 {
262 scale
263 } else {
264 1.0
265 };
266 self
267 }
268 pub fn weight(mut self, w: day_spec::FontWeight) -> Self {
270 self.weight = Some(w);
271 self
272 }
273 pub fn bold(self) -> Self {
275 self.weight(day_spec::FontWeight::Bold)
276 }
277 pub fn secondary(mut self) -> Self {
285 self.role = day_spec::props::TextRole::Secondary;
286 self
287 }
288 pub fn italic(mut self) -> Self {
290 self.italic = true;
291 self
292 }
293 pub fn tabular(mut self) -> Self {
299 self.tabular = true;
300 self
301 }
302 pub fn monospace(mut self) -> Self {
305 self.monospace = true;
306 self
307 }
308 pub fn runs(mut self, runs: Vec<day_spec::TextRun>) -> Self {
318 self.runs = runs;
319 self
320 }
321 pub fn runs_from(mut self, b: TextBuilder) -> Self {
325 let (text, runs) = b.build();
326 self.text = TextSource::Static(text);
327 self.runs = runs;
328 self
329 }
330 pub fn align(mut self, align: day_spec::props::TextAlign) -> Self {
351 self.align = align;
352 self
353 }
354 pub fn markdown(mut self) -> Self {
355 self.markdown = true;
356 self
357 }
358 pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
367 self.on_link = Some(Rc::new(f));
368 self
369 }
370 pub fn color<M>(mut self, c: impl IntoReactive<day_spec::Color, M>) -> Self {
373 self.color = Some(c.into_reactive());
374 self
375 }
376 pub fn preset(mut self, preset: &crate::TextPreset) -> Self {
379 self.font = preset.font;
380 self.font_scale = preset.font_scale;
381 if preset.weight.is_some() {
382 self.weight = preset.weight;
383 }
384 self.italic |= preset.italic;
385 self.tabular |= preset.tabular;
386 self.monospace |= preset.monospace;
387 if preset.secondary {
388 self.role = day_spec::props::TextRole::Secondary;
389 }
390 if preset.single_line {
391 self.wraps = false;
392 }
393 if let Some(c) = preset.color {
394 self.color = Some(Reactive::Const(c));
395 }
396 self
397 }
398}
399
400impl Piece for Label {
401 fn build(self, cx: &mut BuildCx) -> RNode {
402 let (initial, runs) = if self.markdown {
405 crate::markdown::parse(&self.text.initial(), self.font)
406 } else {
407 (self.text.initial(), self.runs.clone())
408 };
409 let runs = match day_spec::runs_are_valid(&initial, &runs) {
412 Ok(()) => runs,
413 Err(why) => {
414 log::warn!("label runs ignored β {why}; the text renders unstyled");
415 Vec::new()
416 }
417 };
418 let node = cx.leaf(
419 kinds::LABEL,
420 &LabelProps {
421 align: self.align,
422 text: initial,
423 font: day_spec::FontSpec {
424 style: self.font,
425 scale: self.font_scale,
426 weight: self.weight,
427 italic: self.italic,
428 tabular: self.tabular,
429 monospace: self.monospace,
430 },
431 color: self
432 .color
433 .as_ref()
434 .map(super::canvas::Reactive::get_untracked),
435 role: self.role,
436 wraps: self.wraps,
437 max_lines: self.max_lines,
438 runs,
439 },
440 Flex::default(),
441 );
442 let could_link =
446 self.markdown || self.on_link.is_some() || self.runs.iter().any(|r| r.link.is_some());
447 if could_link {
448 let handler = self.on_link.clone();
449 cx.on(node, move |ev| {
450 if let Event::LinkActivated(url) = ev {
451 match &handler {
452 Some(f) => f(url),
453 None => open_link(url),
454 }
455 }
456 });
457 }
458 let font = self.font;
461 let md = self.markdown;
462 self.text.bind_to(
463 node,
464 move |t| {
465 if md {
466 let (text, runs) = crate::markdown::parse(&t, font);
467 Box::new(LabelPatch::Runs(text, runs))
468 } else {
469 Box::new(LabelPatch::Text(t))
470 }
471 },
472 true,
473 );
474 if let Some(Reactive::Dyn(f)) = self.color {
476 bind(
477 move || f(),
478 move |c: &day_spec::Color| {
479 with_tree(|t| t.patch(node, Box::new(LabelPatch::Color(Some(*c))), false));
480 },
481 );
482 }
483 node
484 }
485}
486
487const LINK_BLUE: day_spec::Color = day_spec::Color::rgb(0.0, 0.478, 1.0);
490
491pub fn open_link(target: &str) {
502 if let Some(route) = target.strip_prefix('#') {
503 let _ = day_core::navigate(route);
504 } else {
505 day_core::open_url(target);
506 }
507}
508
509#[must_use]
523pub struct Link {
524 label: Label,
525 url: String,
526}
527
528pub fn link<M>(text: impl IntoText<M>, url: impl Into<String>) -> Link {
530 Link {
531 label: label(text),
532 url: url.into(),
533 }
534}
535
536#[day_macros::builder(LinkBuilder)]
537impl Link {
538 pub fn font(mut self, f: Font) -> Self {
540 self.label = self.label.font(f);
541 self
542 }
543 pub fn color(mut self, c: day_spec::Color) -> Self {
545 self.label = self.label.color(c);
546 self
547 }
548 pub fn bold(mut self) -> Self {
550 self.label = self.label.bold();
551 self
552 }
553}
554
555impl Piece for Link {
556 fn build(self, cx: &mut BuildCx) -> RNode {
557 let url = self.url;
558 let mut label = self.label;
559 if day_core::capability(day_spec::Cap::TextLinks) == day_spec::Support::Native {
560 let source = label.text.clone();
563 let font = day_spec::FontSpec {
564 style: label.font,
565 scale: label.font_scale,
566 weight: label.weight,
567 italic: label.italic,
568 ..Default::default()
569 };
570 let color = label
571 .color
572 .as_ref()
573 .map(super::canvas::Reactive::get_untracked);
574 let target = url.clone();
575 let runs = move |text: &str| {
576 vec![day_spec::TextRun {
577 range: 0..text.len(),
578 font,
579 color,
580 link: Some(target.clone()),
581 ..Default::default()
582 }]
583 };
584 let initial = source.initial();
585 label.runs = runs(&initial);
586 label.text = TextSource::Static(initial);
587 let node = label.build(cx);
588 source.bind_to(
589 node,
590 move |text| {
591 let spans = runs(&text);
592 Box::new(LabelPatch::Runs(text, spans))
593 },
594 true,
595 );
596 cx.on(node, move |ev| {
598 if matches!(ev, Event::Tap(_)) {
599 open_link(&url);
600 }
601 });
602 node
603 } else {
604 if label.color.is_none() {
605 label = label.color(LINK_BLUE);
606 }
607 label
608 .on_tap(move || open_link(&url))
609 .a11y(|b| b.role(Role::Button))
610 .build(cx)
611 }
612 }
613}
614
615#[must_use]
616pub struct Button {
617 title: TextSource,
618 icon: Reactive<Option<day_spec::Icon>>,
619 icon_only: bool,
620 action: Option<Rc<dyn Fn()>>,
621 native_style: day_spec::props::ButtonStyleSpec,
622 tint: Option<Reactive<day_spec::Color>>,
625 enabled: Reactive<bool>,
626 selected: Reactive<bool>,
627}
628
629pub fn button<M>(title: impl IntoText<M>) -> Button {
630 Button {
631 title: title.into_text(),
632 icon: Reactive::Const(None),
633 icon_only: false,
634 action: None,
635 native_style: day_spec::props::ButtonStyleSpec::Automatic,
636 tint: None,
637 enabled: true.into_reactive(),
638 selected: false.into_reactive(),
639 }
640}
641
642#[day_macros::builder(ButtonBuilder)]
643impl Button {
644 pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
646 let symbol = symbol.into_reactive();
647 self.icon = match symbol {
648 Reactive::Const(s) => Reactive::Const(Some(day_spec::Icon::Symbol(s))),
649 Reactive::Dyn(f) => Reactive::Dyn(Rc::new(move || Some(day_spec::Icon::Symbol(f())))),
650 };
651 self
652 }
653
654 pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
656 self.icon = Reactive::Const(Some(day_spec::Icon::Image(name.into().as_str().to_owned())));
657 self
658 }
659
660 pub fn icon_only(mut self) -> Self {
662 self.icon_only = true;
663 self
664 }
665
666 pub fn action(mut self, f: impl Fn() + 'static) -> Self {
673 self.action = Some(Rc::new(f));
674 self
675 }
676
677 pub fn bordered(mut self) -> Self {
680 self.native_style = day_spec::props::ButtonStyleSpec::Bordered;
681 self
682 }
683
684 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
691 self.enabled = v.into_reactive();
692 self
693 }
694
695 pub fn prominent(mut self) -> Self {
699 self.native_style = day_spec::props::ButtonStyleSpec::Prominent;
700 self
701 }
702
703 pub fn tint<M>(mut self, color: impl IntoReactive<day_spec::Color, M>) -> Self {
717 self.tint = Some(color.into_reactive());
718 self
719 }
720
721 pub fn compact(mut self) -> Self {
726 if self.native_style != day_spec::props::ButtonStyleSpec::Plain {
727 self.native_style = day_spec::props::ButtonStyleSpec::Compact;
728 }
729 self
730 }
731
732 pub fn plain(mut self) -> Self {
735 self.native_style = day_spec::props::ButtonStyleSpec::Plain;
736 self
737 }
738
739 pub fn selected<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
749 self.selected = v.into_reactive();
750 self
751 }
752}
753
754impl Piece for Button {
755 fn build(self, cx: &mut BuildCx) -> RNode {
756 let initial = self.title.initial();
757 let style = match &self.tint {
759 Some(c) => day_spec::props::ButtonStyleSpec::Tinted(c.get_untracked()),
760 None => self.native_style,
761 };
762 let node = cx.leaf(
763 kinds::BUTTON,
764 &ButtonProps {
765 title: initial.clone(),
766 icon: self.icon.get_untracked(),
767 icon_only: self.icon_only,
768 enabled: self.enabled.get_untracked(),
769 style,
770 selected: self.selected.get_untracked(),
771 },
772 Flex::default(),
773 );
774 if let selected @ Reactive::Dyn(_) = self.selected {
776 bind(
777 move || selected.get(),
778 move |on: &bool| {
779 with_tree(|t| t.patch(node, Box::new(ButtonPatch::Selected(*on)), false));
780 },
781 );
782 }
783 if let Some(c @ Reactive::Dyn(_)) = self.tint.clone() {
785 bind(
786 move || c.get(),
787 move |col: &day_spec::Color| {
788 with_tree(|t| {
789 t.patch(
790 node,
791 Box::new(ButtonPatch::Style(
792 day_spec::props::ButtonStyleSpec::Tinted(*col),
793 )),
794 false,
795 );
796 });
797 },
798 );
799 }
800 let enabled = self.enabled;
803 let enabled_gate = enabled.clone();
804 if let Reactive::Dyn(_) = &enabled {
805 bind(
806 move || enabled.get(),
807 move |e: &bool| {
808 with_tree(|t| t.patch(node, Box::new(ButtonPatch::Enabled(*e)), false));
809 },
810 );
811 }
812 if let Some(action) = self.action {
813 let gate = enabled_gate;
819 cx.on(node, move |ev| {
820 if matches!(ev, Event::Pressed) && gate.get() {
821 action();
822 }
823 });
824 }
825 if matches!(&self.icon, Reactive::Const(None)) {
826 self.title
828 .bind_to(node, |t| Box::new(ButtonPatch::Title(t)), true);
829 } else {
830 let icon = self.icon;
831 let icon_only = self.icon_only;
832 let seed = day_spec::props::ButtonContent {
833 title: initial,
834 icon: icon.get_untracked(),
835 icon_only,
836 };
837 let title = self.title;
838 bind_seeded(
839 seed,
840 move || day_spec::props::ButtonContent {
841 title: title.resolve(),
842 icon: icon.get(),
843 icon_only,
844 },
845 move |content: &day_spec::props::ButtonContent| {
846 with_tree(|t| {
847 t.patch(node, Box::new(ButtonPatch::Content(content.clone())), true);
848 });
849 },
850 );
851 }
852 node
853 }
854}
855
856#[must_use]
857pub struct Toggle<S: Binding<bool>> {
858 value: S,
859 enabled: Reactive<bool>,
860}
861
862pub fn toggle<S: Binding<bool>>(value: S) -> Toggle<S> {
863 Toggle {
864 value,
865 enabled: true.into_reactive(),
866 }
867}
868
869#[day_macros::builder(ToggleBuilder)]
870impl<S: Binding<bool>> Toggle<S> {
871 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
875 self.enabled = v.into_reactive();
876 self
877 }
878}
879
880impl<S: Binding<bool>> Piece for Toggle<S> {
881 fn build(self, cx: &mut BuildCx) -> RNode {
882 let initial = self.value.peek();
883 let node = cx.leaf(
884 kinds::TOGGLE,
885 &ToggleProps {
886 on: initial,
887 enabled: self.enabled.get_untracked(),
888 },
889 Flex::default(),
890 );
891 let v = self.value.clone();
892 bind_seeded(
893 initial,
894 move || v.read(),
895 move |on: &bool| {
896 with_tree(|t| t.patch(node, Box::new(TogglePatch::On(*on)), false));
897 },
898 );
899 let enabled = self.enabled;
901 if let Reactive::Dyn(_) = &enabled {
902 bind(
903 move || enabled.get(),
904 move |e: &bool| {
905 with_tree(|t| t.patch(node, Box::new(TogglePatch::Enabled(*e)), false));
906 },
907 );
908 }
909 let v = self.value;
910 cx.on(node, move |ev| {
911 if let Event::ToggleChanged(on) = ev {
912 v.write(*on);
913 }
914 });
915 node
916 }
917}
918
919#[must_use]
920pub struct Slider<S: Binding<f64>> {
921 value: S,
922 min: f64,
923 max: f64,
924 step: Option<f64>,
925 enabled: Reactive<bool>,
926}
927
928pub fn slider<S: Binding<f64>>(value: S) -> Slider<S> {
929 Slider {
930 value,
931 min: 0.0,
932 max: 1.0,
933 step: None,
934 enabled: Reactive::Const(true),
935 }
936}
937
938#[day_macros::builder(SliderBuilder)]
939impl<S: Binding<f64>> Slider<S> {
940 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
942 self.enabled = v.into_reactive();
943 self
944 }
945 pub fn range(mut self, r: std::ops::RangeInclusive<f64>) -> Self {
946 self.min = *r.start();
947 self.max = *r.end();
948 self
949 }
950 pub fn step(mut self, s: f64) -> Self {
951 self.step = Some(s);
952 self
953 }
954}
955
956impl<S: Binding<f64>> Piece for Slider<S> {
957 fn build(self, cx: &mut BuildCx) -> RNode {
958 let initial = self.value.peek();
959 let node = cx.leaf(
960 kinds::SLIDER,
961 &SliderProps {
962 value: initial,
963 min: self.min,
964 max: self.max,
965 step: self.step,
966 enabled: self.enabled.get_untracked(),
967 },
968 Flex {
969 grow_w: true,
970 ..Default::default()
971 },
972 );
973 let enabled = self.enabled;
974 if let Reactive::Dyn(_) = &enabled {
975 bind(
976 move || enabled.get(),
977 move |e: &bool| {
978 with_tree(|t| t.patch(node, Box::new(SliderPatch::Enabled(*e)), false));
979 },
980 );
981 }
982 let v = self.value.clone();
983 bind_seeded(
984 initial,
985 move || v.read(),
986 move |val: &f64| {
987 with_tree(|t| t.patch(node, Box::new(SliderPatch::Value(*val)), false));
988 },
989 );
990 let v = self.value;
991 let (step, min, max) = (self.step, self.min, self.max);
992 cx.on(node, move |ev| {
993 let snap = |val: f64| match step {
999 Some(s) if s > 0.0 => (min + ((val - min) / s).round() * s).clamp(min, max),
1000 _ => val,
1001 };
1002 match ev {
1003 Event::ValueChanged(val) => v.write_preview(snap(*val)),
1006 Event::ValueCommitted(val) => v.write_commit(snap(*val)),
1010 _ => {}
1011 }
1012 });
1013 node
1014 }
1015}
1016
1017#[must_use]
1022pub struct TextField<S: Binding<String>> {
1023 value: S,
1024 placeholder: Option<TextSource>,
1025 on_submit: Option<Rc<dyn Fn()>>,
1026 secure: Reactive<bool>,
1027 read_only: Reactive<bool>,
1028 purpose: day_spec::InputPurpose,
1029 submit_label: day_spec::SubmitLabel,
1030 max_length: Option<u32>,
1031 enabled: Reactive<bool>,
1032 select: Option<(day_reactive::Trigger, Rc<dyn Fn() -> TextSelection>)>,
1033}
1034
1035pub fn text_field<S: Binding<String>>(value: S) -> TextField<S> {
1036 TextField {
1037 value,
1038 placeholder: None,
1039 on_submit: None,
1040 secure: Reactive::Const(false),
1041 read_only: Reactive::Const(false),
1042 purpose: day_spec::InputPurpose::Text,
1043 submit_label: day_spec::SubmitLabel::Return,
1044 max_length: None,
1045 enabled: Reactive::Const(true),
1046 select: None,
1047 }
1048}
1049
1050pub fn secure_field<S: Binding<String>>(value: S) -> TextField<S> {
1057 text_field(value)
1058 .secure(true)
1059 .input_purpose(day_spec::InputPurpose::Password)
1060}
1061
1062#[day_macros::builder(TextFieldBuilder)]
1063impl<S: Binding<String>> TextField<S> {
1064 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1067 self.enabled = v.into_reactive();
1068 self
1069 }
1070 pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
1071 self.placeholder = Some(t.into_text());
1072 self
1073 }
1074 pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
1078 self.on_submit = Some(Rc::new(f));
1079 self
1080 }
1081 pub fn secure<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1086 self.secure = v.into_reactive();
1087 self
1088 }
1089 pub fn read_only<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1093 self.read_only = v.into_reactive();
1094 self
1095 }
1096 pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
1099 self.purpose = purpose;
1100 self
1101 }
1102 pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
1104 self.submit_label = label;
1105 self
1106 }
1107 pub fn max_length(mut self, characters: u32) -> Self {
1110 self.max_length = Some(characters);
1111 self
1112 }
1113 pub fn select<R: std::ops::RangeBounds<usize> + 'static>(
1132 mut self,
1133 trigger: day_reactive::Trigger,
1134 range: impl Fn() -> R + 'static,
1135 ) -> Self {
1136 self.select = Some((
1137 trigger,
1138 Rc::new(move || {
1139 use std::ops::Bound;
1140 let r = range();
1141 let start = match r.start_bound() {
1142 Bound::Included(&n) => n,
1143 Bound::Excluded(&n) => n.saturating_add(1),
1144 Bound::Unbounded => 0,
1145 };
1146 let end = match r.end_bound() {
1147 Bound::Included(&n) => n.saturating_add(1),
1148 Bound::Excluded(&n) => n,
1149 Bound::Unbounded => usize::MAX,
1150 };
1151 TextSelection::new(start, end)
1152 }),
1153 ));
1154 self
1155 }
1156}
1157
1158impl<S: Binding<String>> Piece for TextField<S> {
1159 fn build(self, cx: &mut BuildCx) -> RNode {
1160 let initial = self.value.peek();
1161 let ph = self
1162 .placeholder
1163 .as_ref()
1164 .map_or_default(super::sources::TextSource::initial);
1165 let node = cx.leaf(
1166 kinds::TEXT_FIELD,
1167 &TextFieldProps {
1168 text: initial.clone(),
1169 placeholder: ph,
1170 enabled: self.enabled.get_untracked(),
1171 },
1172 Flex {
1173 grow_w: true,
1174 ..Default::default()
1175 },
1176 );
1177 if let Reactive::Dyn(_) = &self.enabled {
1178 let enabled = self.enabled.clone();
1179 bind(
1180 move || enabled.get(),
1181 move |e: &bool| {
1182 with_tree(|t| t.patch(node, Box::new(TextFieldPatch::Enabled(*e)), false));
1183 },
1184 );
1185 }
1186 let (secure, read_only) = (self.secure, self.read_only);
1191 let (purpose, submit_label, max_length) =
1192 (self.purpose, self.submit_label, self.max_length);
1193 let traits = move |secure: bool, read_only: bool| day_spec::InputTraits {
1194 secure,
1195 read_only,
1196 purpose,
1197 submit_label,
1198 max_length,
1199 };
1200 let initial_traits = traits(secure.get_untracked(), read_only.get_untracked());
1201 let reactive_traits =
1202 matches!(secure, Reactive::Dyn(_)) || matches!(read_only, Reactive::Dyn(_));
1203 if initial_traits != day_spec::InputTraits::default() {
1204 with_tree(|t| t.set_node_input_traits(node, &initial_traits));
1205 }
1206 if reactive_traits {
1207 bind_seeded(
1208 initial_traits,
1209 move || traits(secure.get(), read_only.get()),
1210 move |tr: &day_spec::InputTraits| {
1211 with_tree(|t| t.set_node_input_traits(node, tr));
1212 },
1213 );
1214 }
1215 let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1218 let last: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1220 let v = self.value.clone();
1221 let session = self.value.clone();
1222 let (g, typed) = (guard.clone(), last.clone());
1223 bind_seeded(
1224 initial,
1225 move || v.read(),
1226 move |t: &String| {
1227 let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
1228 if !from_native && typed.borrow_mut().take().is_some() {
1229 session.end_preview();
1235 }
1236 with_tree(|tr| {
1237 tr.patch(
1238 node,
1239 Box::new(TextFieldPatch::Text {
1240 text: t.clone(),
1241 from_native,
1242 }),
1243 false,
1244 );
1245 });
1246 },
1247 );
1248 let value = self.value.clone();
1249 let v = self.value;
1250 let submit = self.on_submit;
1251 {
1257 let (v, last) = (v.clone(), last.clone());
1258 day_reactive::Scope::current().on_cleanup(move || {
1259 if let Some(t) = last.borrow_mut().take() {
1260 v.write_teardown(t);
1261 }
1262 });
1263 }
1264 cx.on(node, move |ev| match ev {
1265 Event::TextChanged(t) => {
1266 let cut = max_length
1271 .and_then(|max| t.char_indices().nth(max as usize))
1272 .map(|(at, _)| t[..at].to_string());
1273 let t = match cut {
1274 Some(cut) => {
1275 with_tree(|tr| {
1276 tr.patch(
1277 node,
1278 Box::new(TextFieldPatch::Text {
1279 text: cut.clone(),
1280 from_native: false,
1281 }),
1282 false,
1283 );
1284 });
1285 cut
1286 }
1287 None => t.clone(),
1288 };
1289 *guard.borrow_mut() = Some(t.clone());
1290 *last.borrow_mut() = Some(t.clone());
1291 v.write_preview(t);
1292 }
1293 Event::Submitted => {
1294 if let Some(t) = last.borrow_mut().take() {
1295 v.write_commit(t);
1296 }
1297 if let Some(f) = &submit {
1298 f();
1299 }
1300 }
1301 Event::FocusChanged(false) => {
1302 if let Some(t) = last.borrow_mut().take() {
1303 v.write_commit(t);
1304 }
1305 }
1306 _ => {}
1307 });
1308 if let Some(p) = self.placeholder {
1309 p.bind_to(node, |t| Box::new(TextFieldPatch::Placeholder(t)), false);
1310 }
1311 if let Some((trigger, range)) = self.select {
1318 let scope = day_reactive::Scope::current();
1319 day_reactive::watch(
1320 move || trigger.track(),
1321 move |(), _| {
1322 let (range, value) = (range.clone(), value.clone());
1323 day_reactive::at_turn_end(move || {
1324 if !scope.is_alive() {
1325 return;
1326 }
1327 let sel = range().clamped(&value.peek());
1328 day_reactive::on_main(move || {
1329 with_tree(|t| {
1330 t.patch(node, Box::new(TextFieldPatch::Select(sel)), false);
1331 });
1332 });
1333 });
1334 },
1335 );
1336 }
1337 node
1338 }
1339}
1340
1341#[must_use]
1344pub struct Progress {
1345 value: Option<FractionSource>,
1347 animating: crate::Reactive<bool>,
1348 large: bool,
1349}
1350
1351pub fn spinner() -> Progress {
1354 Progress {
1355 value: None,
1356 animating: crate::Reactive::Const(true),
1357 large: false,
1358 }
1359}
1360
1361pub fn progress<M>(fraction: impl IntoFraction<M>) -> Progress {
1365 Progress {
1366 value: Some(fraction.into_fraction()),
1367 animating: crate::Reactive::Const(true),
1368 large: false,
1369 }
1370}
1371
1372#[day_macros::builder(ProgressBuilder)]
1373impl Progress {
1374 pub fn animating<M>(mut self, source: impl crate::IntoReactive<bool, M>) -> Self {
1376 self.animating = source.into_reactive();
1377 self
1378 }
1379 pub fn large(mut self) -> Self {
1381 self.large = true;
1382 self
1383 }
1384}
1385
1386impl Piece for Progress {
1387 fn build(self, cx: &mut BuildCx) -> RNode {
1388 let determinate = self.value.is_some();
1389 let initial = self
1390 .value
1391 .as_ref()
1392 .map(super::sources::FractionSource::initial);
1393 let node = cx.leaf(
1394 kinds::PROGRESS,
1395 &ProgressProps {
1396 value: initial,
1397 animating: self.animating.get_untracked(),
1398 large: self.large,
1399 },
1400 Flex {
1403 grow_w: determinate,
1404 ..Default::default()
1405 },
1406 );
1407 if !determinate && let crate::Reactive::Dyn(f) = self.animating {
1408 day_reactive::bind_seeded(
1409 f(),
1410 move || f(),
1411 move |on| {
1412 day_core::with_tree(|t| {
1413 t.patch(node, Box::new(ProgressPatch::Animating(*on)), false);
1414 });
1415 },
1416 );
1417 }
1418 if let Some(src) = self.value {
1419 src.bind_to(node);
1420 }
1421 node
1422 }
1423}
1424
1425#[must_use]
1428pub struct Divider {
1429 vertical: bool,
1430}
1431
1432pub fn divider() -> Divider {
1433 Divider { vertical: false }
1434}
1435
1436#[day_macros::builder(DividerBuilder)]
1437impl Divider {
1438 pub fn vertical(mut self) -> Self {
1442 self.vertical = true;
1443 self
1444 }
1445}
1446
1447impl Piece for Divider {
1448 fn build(self, cx: &mut BuildCx) -> RNode {
1449 let props = DividerProps {
1450 vertical: self.vertical,
1451 };
1452 if self.vertical {
1453 cx.native(
1454 kinds::DIVIDER,
1455 &props,
1456 Rc::new(VerticalLeaf),
1457 Flex {
1458 grow_h: true,
1459 ..Default::default()
1460 },
1461 Boundary::No,
1462 )
1463 } else {
1464 cx.leaf(
1465 kinds::DIVIDER,
1466 &props,
1467 Flex {
1468 grow_w: true,
1469 ..Default::default()
1470 },
1471 )
1472 }
1473 }
1474}
1475
1476struct VerticalLeaf;
1480
1481impl Layout for VerticalLeaf {
1482 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1483 let s = cx.measure_leaf(Proposal::new(p.height, p.width));
1484 Size::new(s.height, s.width)
1485 }
1486 fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
1487}
1488
1489pub struct Spacer;
1490
1491#[must_use]
1492pub fn spacer() -> Spacer {
1493 Spacer
1494}
1495
1496impl Piece for Spacer {
1497 fn build(self, cx: &mut BuildCx) -> RNode {
1498 cx.layout_only(
1499 Rc::new(PassThrough),
1500 Flex {
1501 is_spacer: true,
1502 ..Default::default()
1503 },
1504 Boundary::No,
1505 )
1506 }
1507}
1508
1509#[cfg(feature = "conformance")]
1518pub(crate) mod conformance {
1519 use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
1520 use day_reactive::Signal;
1521 use day_spec::{Cap, Font, Role, kinds};
1522
1523 use crate::*;
1524
1525 #[day_macros::test(day_core)]
1527 fn button_press() -> Case {
1528 let presses = Signal::new(0i64);
1529 Case::new()
1530 .proves(kinds::BUTTON)
1531 .page(move || {
1532 column((
1533 button("Press")
1534 .action(move || presses.update(|n| *n += 1))
1535 .id(day_core::id!(press)),
1536 label(move || presses.get().to_string()).id(day_core::id!(count)),
1537 ))
1538 .spacing(8.0)
1539 })
1540 .shot("default")
1541 .drive(|d: Drive| async move {
1542 d.assert_text("press", "Press").await?;
1543 d.tap("press").await?;
1544 d.assert_text("count", "1").await?;
1545 d.tap("press").await?;
1546 d.assert_text("count", "2").await
1547 })
1548 }
1549
1550 #[day_macros::test(day_core)]
1554 fn button_disabled() -> Case {
1555 let presses = Signal::new(0i64);
1556 let enabled = Signal::new(false);
1557 Case::new()
1558 .proves(kinds::BUTTON)
1559 .proves_duty("set_enabled")
1560 .page(move || {
1561 column((
1562 button("Off")
1563 .enabled(move || enabled.get())
1564 .action(move || presses.update(|n| *n += 1))
1565 .id(day_core::id!(off)),
1566 label(move || presses.get().to_string()).id(day_core::id!(count)),
1567 button("Enable")
1568 .action(move || enabled.set(true))
1569 .id(day_core::id!(enable)),
1570 ))
1571 .spacing(8.0)
1572 })
1573 .drive(|d: Drive| async move {
1574 d.assert_enabled("off", false).await?;
1575 d.assert_text("count", "0").await?;
1576 d.tap("enable").await?;
1577 d.assert_enabled("off", true).await?;
1578 d.tap("off").await?;
1579 d.assert_text("count", "1").await
1580 })
1581 }
1582
1583 #[day_macros::test(day_core)]
1585 fn toggle_binding() -> Case {
1586 let on = Signal::new(false);
1587 Case::new()
1588 .proves(kinds::TOGGLE)
1589 .page(move || {
1590 column((
1591 toggle(on).id(day_core::id!(tgl_switch)),
1592 label(move || if on.get() { "on" } else { "off" }.to_owned())
1593 .id(day_core::id!(tgl_state)),
1594 button("Set on")
1595 .action(move || on.set(true))
1596 .id(day_core::id!(tgl_set)),
1597 ))
1598 .spacing(8.0)
1599 })
1600 .drive(|d: Drive| async move {
1601 d.toggle("tgl_switch", true).await?;
1602 d.assert_text("tgl_state", "on").await?;
1603 d.toggle("tgl_switch", false).await?;
1604 d.assert_text("tgl_state", "off").await?;
1605 d.tap("tgl_set").await?;
1606 d.assert_on("tgl_switch", true).await
1607 })
1608 }
1609
1610 #[day_macros::test(day_core)]
1612 fn text_field_binding() -> Case {
1613 let name = Signal::new(String::new());
1614 Case::new()
1615 .proves(kinds::TEXT_FIELD)
1616 .page(move || {
1617 column((
1618 text_field(name)
1619 .placeholder("Name")
1620 .id(day_core::id!(tf_field)),
1621 label(move || name.get()).id(day_core::id!(tf_echo)),
1622 button("Set")
1623 .action(move || name.set("Ada".into()))
1624 .id(day_core::id!(tf_set)),
1625 ))
1626 .spacing(8.0)
1627 })
1628 .drive(|d: Drive| async move {
1629 d.input("tf_field", "Grace").await?;
1630 d.assert_text("tf_echo", "Grace").await?;
1631 d.tap("tf_set").await?;
1632 d.assert_text("tf_field", "Ada").await
1633 })
1634 }
1635
1636 #[day_macros::test(day_core)]
1639 fn text_field_secure() -> Case {
1640 let password = Signal::new(String::new());
1641 let shown = Signal::new(false);
1642 Case::new()
1643 .proves(kinds::TEXT_FIELD)
1644 .proves_duty("set_input_traits")
1645 .page(move || {
1646 column((
1647 secure_field(password)
1648 .secure(move || !shown.get())
1649 .placeholder("Password")
1650 .id(day_core::id!(tfs_pass)),
1651 toggle(shown).id(day_core::id!(tfs_show)),
1652 label(move || password.get().chars().count().to_string())
1653 .id(day_core::id!(tfs_len)),
1654 ))
1655 .spacing(8.0)
1656 })
1657 .shot("masked")
1658 .drive(|d: Drive| async move {
1659 d.input("tfs_pass", "correct horse").await?;
1660 d.assert_text("tfs_len", "13").await?;
1661 d.focus("tfs_pass").await?;
1662 d.toggle("tfs_show", true).await?;
1663 d.wait_idle().await?;
1664 d.shot("shown").await?;
1665 d.assert_focused("tfs_pass", true).await?;
1666 d.input("tfs_pass", "battery").await?;
1667 d.assert_text("tfs_len", "7").await?;
1668 d.toggle("tfs_show", false).await?;
1669 d.wait_idle().await?;
1670 d.assert_text("tfs_pass", "battery").await
1671 })
1672 }
1673
1674 #[day_macros::test(day_core)]
1676 fn text_field_max_length() -> Case {
1677 let pin = Signal::new(String::new());
1678 Case::new()
1679 .proves(kinds::TEXT_FIELD)
1680 .page(move || {
1681 column((
1682 text_field(pin).max_length(4).id(day_core::id!(tfm_pin)),
1683 label(move || pin.get()).id(day_core::id!(tfm_echo)),
1684 ))
1685 .spacing(8.0)
1686 })
1687 .drive(|d: Drive| async move {
1688 d.input("tfm_pin", "123456").await?;
1689 d.assert_text("tfm_echo", "1234").await?;
1690 d.assert_text("tfm_pin", "1234").await
1691 })
1692 }
1693
1694 #[day_macros::test(day_core)]
1697 fn slider_range() -> Case {
1698 let value = Signal::new(40.0f64);
1699 Case::new()
1700 .proves(kinds::SLIDER)
1701 .page(move || {
1702 column((
1703 slider(value)
1704 .range(0.0..=100.0)
1705 .step(10.0)
1706 .id(day_core::id!(sl_slider)),
1707 label(move || format!("{:.0}", value.get())).id(day_core::id!(sl_value)),
1708 ))
1709 .spacing(8.0)
1710 })
1711 .drive(|d: Drive| async move {
1712 d.set_value("sl_slider", 72.0).await?;
1713 d.assert_text("sl_value", "70").await?;
1714 d.assert_value("sl_slider", 70.0).await
1715 })
1716 }
1717
1718 #[day_macros::test(day_core)]
1721 fn label_heading() -> Case {
1722 let text = Signal::new("Hello".to_owned());
1723 Case::new()
1724 .proves(kinds::LABEL)
1725 .proves_duty("set_a11y")
1726 .page(move || {
1727 column((
1728 label(move || text.get())
1729 .font(Font::Headline)
1730 .a11y(|a| a.role(Role::Heading(2)))
1731 .id(day_core::id!(lbl_heading)),
1732 button("Rename")
1733 .action(move || text.set("Renamed".into()))
1734 .id(day_core::id!(lbl_rename)),
1735 ))
1736 .spacing(8.0)
1737 })
1738 .drive(|d: Drive| async move {
1739 d.assert_text("lbl_heading", "Hello").await?;
1740 d.tap("lbl_rename").await?;
1741 d.assert_text("lbl_heading", "Renamed").await?;
1742 d.a11y_audit(Some("lbl_heading")).await
1743 })
1744 }
1745
1746 #[day_macros::test(day_core)]
1748 fn label_text() -> Case {
1749 Case::new()
1750 .proves(kinds::LABEL)
1751 .page(|| label("Plain text").id(day_core::id!(text)))
1752 .drive(|d: Drive| async move { d.assert_text("text", "Plain text").await })
1753 }
1754
1755 #[day_macros::test(day_core)]
1757 fn label_reactive() -> Case {
1758 let count = Signal::new(0i64);
1759 Case::new()
1760 .proves(kinds::LABEL)
1761 .proves_duty("update")
1762 .proves_duty("read_native")
1763 .page(move || {
1764 column((
1765 label(move || format!("Count {}", count.get())).id(day_core::id!(text)),
1766 button("Add")
1767 .action(move || count.update(|n| *n += 1))
1768 .id(day_core::id!(add)),
1769 ))
1770 .spacing(8.0)
1771 })
1772 .drive(|d: Drive| async move {
1773 d.assert_text("text", "Count 0").await?;
1774 d.tap("add").await?;
1775 d.tap("add").await?;
1776 d.assert_text("text", "Count 2").await
1777 })
1778 }
1779
1780 #[day_macros::test(day_core)]
1782 fn label_runs() -> Case {
1783 Case::new()
1784 .proves(kinds::LABEL)
1785 .proves_cap(Cap::TextRuns)
1786 .requires(Cap::TextRuns)
1787 .page(|| {
1788 label("")
1789 .runs_from(
1790 TextBuilder::new()
1791 .text("Plain, ")
1792 .strong("strong")
1793 .text(" and ")
1794 .emphasis("emphasized"),
1795 )
1796 .id(day_core::id!(runs))
1797 })
1798 .shot("default")
1799 .drive(|d: Drive| async move {
1800 d.assert_text("runs", "Plain, strong and emphasized").await
1801 })
1802 }
1803
1804 #[day_macros::test(day_core)]
1807 fn label_link_runs_reactive() -> Case {
1808 let text = Signal::new("π [Alpha](#alpha) / [Beta](#beta)".to_string());
1809 Case::new()
1810 .proves(kinds::LABEL)
1811 .requires(Cap::TextRuns)
1812 .page(move || {
1813 column((
1814 label(text).markdown().id(day_core::id!(links)),
1815 button("Replace")
1816 .id(day_core::id!(replace))
1817 .action(move || {
1818 text.set("[ζ±δΊ¬](#tokyo) then [again](#again)".into());
1819 }),
1820 button("Plain")
1821 .id(day_core::id!(plain))
1822 .action(move || text.set("Plain π".into())),
1823 button("Restore")
1824 .id(day_core::id!(restore))
1825 .action(move || text.set("[Restored](#restored)".into())),
1826 ))
1827 })
1828 .drive(|d: Drive| async move {
1829 d.assert_text("links", "π Alpha / Beta").await?;
1830 d.tap("replace").await?;
1831 d.assert_text("links", "ζ±δΊ¬ then again").await?;
1832 d.tap("plain").await?;
1833 d.assert_text("links", "Plain π").await?;
1834 d.tap("restore").await?;
1835 d.assert_text("links", "Restored").await
1836 })
1837 }
1838
1839 #[day_macros::test(day_core)]
1842 fn label_selectable() -> Case {
1843 Case::new()
1844 .proves(kinds::LABEL)
1845 .proves_modifier("selectable")
1846 .proves_duty("set_selectable")
1847 .page(|| label("Copy me").selectable().id(day_core::id!(text)))
1848 .drive(|d: Drive| async move { d.assert_text("text", "Copy me").await })
1849 }
1850
1851 #[day_macros::test(day_core)]
1853 fn button_title() -> Case {
1854 let saved = Signal::new(false);
1855 Case::new()
1856 .proves(kinds::BUTTON)
1857 .page(move || {
1858 button(move || if saved.get() { "Saved" } else { "Save" }.to_owned())
1859 .action(move || saved.set(true))
1860 .id(day_core::id!(save))
1861 })
1862 .drive(|d: Drive| async move {
1863 d.assert_text("save", "Save").await?;
1864 d.tap("save").await?;
1865 d.assert_text("save", "Saved").await
1866 })
1867 }
1868
1869 #[day_macros::test(day_core)]
1871 fn button_a11y() -> Case {
1872 Case::new()
1873 .proves(kinds::BUTTON)
1874 .proves_modifier("a11y")
1875 .page(|| {
1876 button("Send")
1877 .a11y(|a| a.label("Send the message"))
1878 .id(day_core::id!(send))
1879 })
1880 .drive(|d: Drive| async move { d.a11y_audit(Some("send")).await })
1881 }
1882
1883 #[day_macros::test(day_core)]
1886 fn button_a11y_survives_title_change() -> Case {
1887 let playing = Signal::new(false);
1888 Case::new()
1889 .proves(kinds::BUTTON)
1890 .proves_modifier("a11y")
1891 .page(move || {
1892 button(move || if playing.get() { "Pause" } else { "Play" }.to_owned())
1893 .icon(day_spec::Symbol::Play)
1894 .action(move || playing.set(true))
1895 .a11y(|a| a.label("Playback"))
1896 .id(day_core::id!(play))
1897 })
1898 .drive(|d: Drive| async move {
1899 d.a11y_audit(Some("play")).await?;
1900 d.tap("play").await?;
1901 d.assert_text("play", "Pause").await?;
1902 d.a11y_audit(Some("play")).await
1903 })
1904 }
1905
1906 #[day_macros::test(day_core)]
1908 fn toggle_disabled() -> Case {
1909 let on = Signal::new(false);
1910 let enabled = Signal::new(false);
1911 Case::new()
1912 .proves(kinds::TOGGLE)
1913 .page(move || {
1914 column((
1915 toggle(on)
1916 .enabled(move || enabled.get())
1917 .id(day_core::id!(switch)),
1918 button("Enable")
1919 .action(move || enabled.set(true))
1920 .id(day_core::id!(enable)),
1921 ))
1922 .spacing(8.0)
1923 })
1924 .drive(|d: Drive| async move {
1925 d.assert_enabled("switch", false).await?;
1926 d.tap("enable").await?;
1927 d.assert_enabled("switch", true).await?;
1928 d.toggle("switch", true).await?;
1929 d.assert_on("switch", true).await
1930 })
1931 }
1932
1933 #[day_macros::test(day_core)]
1935 fn toggle_disabled_constant() -> Case {
1936 let on = Signal::new(true);
1937 Case::new()
1938 .proves(kinds::TOGGLE)
1939 .page(move || toggle(on).enabled(false).id(day_core::id!(switch)))
1940 .drive(|d: Drive| async move {
1941 d.assert_enabled("switch", false).await?;
1942 d.assert_on("switch", true).await
1943 })
1944 }
1945
1946 #[day_macros::test(day_core)]
1948 fn toggle_a11y() -> Case {
1949 let on = Signal::new(false);
1950 Case::new()
1951 .proves(kinds::TOGGLE)
1952 .page(move || {
1953 toggle(on)
1954 .a11y(|a| a.label("Notifications"))
1955 .id(day_core::id!(switch))
1956 })
1957 .drive(|d: Drive| async move { d.a11y_audit(Some("switch")).await })
1958 }
1959
1960 #[day_macros::test(day_core)]
1962 fn slider_disabled() -> Case {
1963 let value = Signal::new(0.5f64);
1964 let enabled = Signal::new(false);
1965 Case::new()
1966 .proves(kinds::SLIDER)
1967 .page(move || {
1968 column((
1969 slider(value)
1970 .enabled(move || enabled.get())
1971 .id(day_core::id!(slider)),
1972 button("Enable")
1973 .action(move || enabled.set(true))
1974 .id(day_core::id!(enable)),
1975 ))
1976 .spacing(8.0)
1977 })
1978 .drive(|d: Drive| async move {
1979 d.assert_enabled("slider", false).await?;
1980 d.tap("enable").await?;
1981 d.assert_enabled("slider", true).await?;
1982 d.set_value("slider", 0.25).await?;
1983 d.assert_value("slider", 0.25).await
1984 })
1985 }
1986
1987 #[day_macros::test(day_core)]
1989 fn slider_follows_signal() -> Case {
1990 let value = Signal::new(10.0f64);
1991 Case::new()
1992 .proves(kinds::SLIDER)
1993 .page(move || {
1994 column((
1995 slider(value).range(0.0..=50.0).id(day_core::id!(slider)),
1996 button("Set 40")
1997 .action(move || value.set(40.0))
1998 .id(day_core::id!(set)),
1999 ))
2000 .spacing(8.0)
2001 })
2002 .drive(|d: Drive| async move {
2003 d.assert_value("slider", 10.0).await?;
2004 d.tap("set").await?;
2005 d.assert_value("slider", 40.0).await
2006 })
2007 }
2008
2009 #[day_macros::test(day_core)]
2011 fn slider_a11y() -> Case {
2012 let value = Signal::new(0.5f64);
2013 Case::new()
2014 .proves(kinds::SLIDER)
2015 .page(move || {
2016 slider(value)
2017 .a11y(|a| a.label("Volume"))
2018 .id(day_core::id!(slider))
2019 })
2020 .drive(|d: Drive| async move { d.a11y_audit(Some("slider")).await })
2021 }
2022
2023 #[day_macros::test(day_core)]
2025 fn text_field_disabled() -> Case {
2026 let text = Signal::new("Fixed".to_owned());
2027 let enabled = Signal::new(false);
2028 Case::new()
2029 .proves(kinds::TEXT_FIELD)
2030 .page(move || {
2031 column((
2032 text_field(text)
2033 .enabled(move || enabled.get())
2034 .id(day_core::id!(field)),
2035 button("Enable")
2036 .action(move || enabled.set(true))
2037 .id(day_core::id!(enable)),
2038 ))
2039 .spacing(8.0)
2040 })
2041 .drive(|d: Drive| async move {
2042 d.assert_enabled("field", false).await?;
2043 d.assert_text("field", "Fixed").await?;
2044 d.tap("enable").await?;
2045 d.assert_enabled("field", true).await?;
2046 d.input("field", "Changed").await?;
2047 d.assert_text("field", "Changed").await
2048 })
2049 }
2050
2051 #[day_macros::test(day_core)]
2053 fn text_field_read_only() -> Case {
2054 let text = Signal::new("Shown".to_owned());
2055 Case::new()
2056 .proves(kinds::TEXT_FIELD)
2057 .proves_duty("set_input_traits")
2058 .page(move || {
2059 column((
2060 text_field(text).read_only(true).id(day_core::id!(field)),
2061 button("Replace")
2062 .action(move || text.set("Replaced".into()))
2063 .id(day_core::id!(replace)),
2064 ))
2065 .spacing(8.0)
2066 })
2067 .drive(|d: Drive| async move {
2068 d.assert_text("field", "Shown").await?;
2069 d.assert_enabled("field", true).await?;
2070 d.tap("replace").await?;
2071 d.assert_text("field", "Replaced").await
2072 })
2073 }
2074
2075 #[day_macros::test(day_core)]
2077 fn text_field_submit() -> Case {
2078 let text = Signal::new(String::new());
2079 let sent = Signal::new(String::new());
2080 Case::new()
2081 .proves(kinds::TEXT_FIELD)
2082 .page(move || {
2083 column((
2084 text_field(text)
2085 .submit_label(day_spec::SubmitLabel::Send)
2086 .on_submit(move || sent.set(text.get_untracked()))
2087 .id(day_core::id!(field)),
2088 label(move || sent.get()).id(day_core::id!(sent)),
2089 ))
2090 .spacing(8.0)
2091 })
2092 .drive(|d: Drive| async move {
2093 d.input("field", "hello").await?;
2094 d.submit("field").await?;
2095 d.assert_text("sent", "hello").await
2096 })
2097 }
2098
2099 #[day_macros::test(day_core)]
2101 fn progress_value() -> Case {
2102 let done = Signal::new(0.25f64);
2103 Case::new()
2104 .proves(kinds::PROGRESS)
2105 .page(move || {
2106 column((
2107 progress(done).id(day_core::id!(bar)),
2108 button("Advance")
2109 .action(move || done.set(0.75))
2110 .id(day_core::id!(advance)),
2111 ))
2112 .spacing(8.0)
2113 })
2114 .drive(|d: Drive| async move {
2115 d.assert_value("bar", 0.25).await?;
2116 d.tap("advance").await?;
2117 d.assert_value("bar", 0.75).await
2118 })
2119 }
2120
2121 #[day_macros::test(day_core)]
2123 fn spinner_renders() -> Case {
2124 Case::new()
2125 .proves(kinds::PROGRESS)
2126 .page(|| spinner().id(day_core::id!(spin)))
2127 .drive(|d: Drive| async move {
2128 d.assert_visible("spin").await?;
2129 d.assert_native(
2130 "spin",
2131 NativeExpect {
2132 visible: Some(true),
2133 ..Default::default()
2134 },
2135 )
2136 .await
2137 })
2138 }
2139
2140 #[day_macros::test(day_core)]
2142 fn spinner_size_and_animation() -> Case {
2143 Case::new()
2144 .proves(kinds::PROGRESS)
2145 .page(|| {
2146 let running = Signal::new(true);
2147 column((
2148 spinner()
2149 .animating(running)
2150 .id(day_core::id!(spinner_fixture::small)),
2151 spinner()
2152 .animating(running)
2153 .large()
2154 .id(day_core::id!(spinner_fixture::large)),
2155 button("Stop fixture")
2156 .action(move || running.set(false))
2157 .id(day_core::id!(spinner_fixture::stop)),
2158 ))
2159 })
2160 .drive(|d: Drive| async move {
2161 let sizes = match day_core::toolkit_key() {
2162 Some("appkit") => Some((20.0, 32.0)),
2163 Some("uikit") => Some((20.0, 37.0)),
2164 Some("gtk") => Some((24.0, 48.0)),
2165 Some("arkui") => Some((32.0, 64.0)),
2166 Some("xaml" | "winui") => Some((32.0, 48.0)),
2167 Some("dom") => Some((22.0, 48.0)),
2168 _ => None, };
2170 for stopped in [false, true] {
2171 if stopped {
2172 d.tap("spinner_fixture::stop").await?;
2173 }
2174 d.assert_visible("spinner_fixture::small").await?;
2175 d.assert_visible("spinner_fixture::large").await?;
2176 if let Some((small, large)) = sizes {
2177 d.assert_size("spinner_fixture::small", small, small)
2178 .await?;
2179 d.assert_size("spinner_fixture::large", large, large)
2180 .await?;
2181 }
2182 }
2183 Ok(())
2184 })
2185 }
2186
2187 #[day_macros::test(day_core)]
2189 fn divider_renders() -> Case {
2190 Case::new()
2191 .proves(kinds::DIVIDER)
2192 .page(|| {
2193 column((
2194 label("Above"),
2195 divider().id(day_core::id!(rule)),
2196 label("Below"),
2197 ))
2198 .spacing(8.0)
2199 .width(200.0)
2200 })
2201 .drive(|d: Drive| async move {
2202 d.assert_visible("rule").await?;
2203 d.assert_frame(
2204 "rule",
2205 FrameExpect {
2206 width: Some(200.0),
2207 ..Default::default()
2208 },
2209 )
2210 .await
2211 })
2212 }
2213
2214 #[day_macros::test(day_core)]
2217 fn vertical_divider_fills_height() -> Case {
2218 Case::new()
2219 .proves(kinds::DIVIDER)
2220 .page(|| {
2221 row((
2222 label("Left"),
2223 divider().vertical().id(day_core::id!(rule)),
2224 label("Right"),
2225 ))
2226 .spacing(8.0)
2227 .height(120.0)
2228 .id(day_core::id!(row))
2229 })
2230 .drive(|d: Drive| async move {
2231 d.assert_visible("rule").await?;
2232 d.assert_frame(
2234 "rule",
2235 FrameExpect {
2236 height: Some(120.0),
2237 ..Default::default()
2238 },
2239 )
2240 .await
2241 })
2242 }
2243
2244 #[day_macros::test(day_core)]
2246 fn spacer_fills() -> Case {
2247 Case::new()
2248 .proves_modifier("width")
2249 .page(|| {
2250 row((
2251 label("A").width(50.0).wrapper_id(day_core::id!(first)),
2253 spacer(),
2254 label("B").width(50.0).wrapper_id(day_core::id!(last)),
2255 ))
2256 .width(300.0)
2257 .wrapper_id(day_core::id!(row))
2258 })
2259 .drive(|d: Drive| async move {
2260 d.assert_frame(
2261 "last",
2262 FrameExpect {
2263 width: Some(50.0),
2264 x: Some(250.0),
2265 relative_to: Some("row".into()),
2266 ..Default::default()
2267 },
2268 )
2269 .await
2270 })
2271 }
2272
2273 #[day_macros::test(day_core)]
2275 fn link_opens_url() -> Case {
2276 Case::new()
2277 .proves_duty("open_url")
2278 .page(|| link("daybrite.dev", "https://daybrite.dev/").id(day_core::id!(link)))
2279 .drive(|d: Drive| async move {
2280 d.assert_text("link", "daybrite.dev").await?;
2281 d.tap("link").await?;
2282 d.assert_opened_url("https://daybrite.dev/").await
2283 })
2284 }
2285}
2286
2287#[cfg(test)]
2288mod button_style_tests {
2289 use super::*;
2290 use day_spec::props::ButtonStyleSpec;
2291
2292 #[test]
2293 fn compact_keeps_a_plain_button_plain() {
2294 assert_eq!(
2295 button("Γ").plain().compact().native_style,
2296 ButtonStyleSpec::Plain
2297 );
2298 assert_eq!(button("β").compact().native_style, ButtonStyleSpec::Compact);
2299 assert_eq!(
2301 button("+").compact().plain().native_style,
2302 ButtonStyleSpec::Plain
2303 );
2304 }
2305}