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: impl Into<day_spec::Ink>) -> Self {
116 let base = self.base;
117 let color = color.into();
118 self.run(s, move |range| day_spec::TextRun {
119 range,
120 font: day_spec::FontSpec::from(base),
121 color: Some(color),
122 ..day_spec::TextRun::default()
123 })
124 }
125 pub fn underline(self, s: &str) -> Self {
127 self.underline_styled(s, day_spec::Decoration::SINGLE)
128 }
129 pub fn underline_styled(self, s: &str, decoration: impl Into<day_spec::Decoration>) -> Self {
133 let base = self.base;
134 let decoration = decoration.into();
135 self.run(s, move |range| day_spec::TextRun {
136 range,
137 font: day_spec::FontSpec::from(base),
138 underline: Some(decoration),
139 ..day_spec::TextRun::default()
140 })
141 }
142 pub fn small_caps(self, s: &str) -> Self {
145 let base = self.base;
146 self.run(s, move |range| {
147 day_spec::TextRun::font(
148 range,
149 day_spec::FontSpec {
150 style: base,
151 small_caps: true,
152 ..Default::default()
153 },
154 )
155 })
156 }
157 pub fn highlight(self, s: &str, color: impl Into<day_spec::Ink>) -> Self {
165 let base = self.base;
166 let color = color.into();
167 let on = color.map(day_spec::props::ButtonStyleSpec::on_tint);
168 self.run(s, move |range| day_spec::TextRun {
169 range,
170 font: day_spec::FontSpec::from(base),
171 background: Some(color),
172 color: Some(on),
173 ..day_spec::TextRun::default()
174 })
175 }
176 pub fn sized(self, s: &str, scale: f64) -> Self {
180 let base = self.base;
181 self.run(s, move |range| day_spec::TextRun {
182 range,
183 font: day_spec::FontSpec::from(base).scaled(scale),
184 ..day_spec::TextRun::default()
185 })
186 }
187 pub fn strikethrough(self, s: &str) -> Self {
189 self.strikethrough_styled(s, day_spec::Decoration::SINGLE)
190 }
191 pub fn strikethrough_styled(
193 self,
194 s: &str,
195 decoration: impl Into<day_spec::Decoration>,
196 ) -> Self {
197 let base = self.base;
198 let decoration = decoration.into();
199 self.run(s, move |range| day_spec::TextRun {
200 range,
201 font: day_spec::FontSpec::from(base),
202 strikethrough: Some(decoration),
203 ..day_spec::TextRun::default()
204 })
205 }
206 pub fn link(self, s: &str, target: &str) -> Self {
210 let base = self.base;
211 let target = target.to_string();
212 self.run(s, move |range| day_spec::TextRun {
213 range,
214 font: day_spec::FontSpec::from(base),
215 link: Some(target),
216 ..day_spec::TextRun::default()
217 })
218 }
219 #[must_use]
221 pub fn build(self) -> (String, Vec<day_spec::TextRun>) {
222 (self.text, self.runs)
223 }
224}
225
226#[must_use]
227pub struct Label {
228 pub(crate) text: TextSource,
229 pub(crate) font: Font,
230 pub(crate) font_scale: Reactive<f64>,
231 pub(crate) max_text_scale: Option<f64>,
232 pub(crate) weight: Option<day_spec::FontWeight>,
233 pub(crate) italic: bool,
234 pub(crate) tabular: bool,
235 pub(crate) monospace: bool,
236 pub(crate) small_caps: bool,
237 pub(crate) oldstyle_figures: bool,
238 pub(crate) wraps: bool,
239 pub(crate) max_lines: Reactive<u32>,
240 pub(crate) truncation: Reactive<Truncation>,
241 pub(crate) letter_spacing: Reactive<f64>,
242 pub(crate) line_height: Reactive<f64>,
243 pub(crate) color: Option<Reactive<day_spec::Ink>>,
244 pub(crate) role: day_spec::props::TextRole,
246 pub(crate) runs: Vec<day_spec::TextRun>,
248 pub(crate) markdown: bool,
250 pub(crate) align: day_spec::props::TextAlign,
252 pub(crate) underline: Option<day_spec::Decoration>,
254 pub(crate) strikethrough: Option<day_spec::Decoration>,
256 pub(crate) link: Option<String>,
258 pub(crate) on_link: Option<LinkHandler>,
260 pub(crate) on_selection: Option<SelectionHandler>,
262}
263
264pub(crate) type LinkHandler = Rc<dyn Fn(&str)>;
266
267pub(crate) type SelectionHandler = Rc<dyn Fn(&SelectedText)>;
269
270#[derive(Clone, Debug, Default, PartialEq, Eq)]
272pub struct SelectedText {
273 pub text: String,
276 pub range: std::ops::Range<usize>,
278}
279
280impl SelectedText {
281 #[must_use]
283 pub fn is_empty(&self) -> bool {
284 self.range.is_empty()
285 }
286}
287
288pub fn label<M>(text: impl IntoText<M>) -> Label {
289 Label::from_source(text.into_text())
290}
291
292impl Label {
293 pub(crate) fn from_source(text: TextSource) -> Label {
295 Label {
296 text,
297 font: Font::Body,
298 font_scale: Reactive::Const(1.0),
299 max_text_scale: None,
300 weight: None,
301 italic: false,
302 tabular: false,
303 monospace: false,
304 small_caps: false,
305 oldstyle_figures: false,
306 wraps: true,
307 max_lines: Reactive::Const(0),
308 truncation: Reactive::Const(Truncation::Tail),
309 letter_spacing: Reactive::Const(0.0),
310 line_height: Reactive::Const(0.0),
311 color: None,
312 role: TextRole::default(),
313 runs: Vec::new(),
314 markdown: false,
315 align: day_spec::props::TextAlign::Leading,
316 underline: None,
317 strikethrough: None,
318 link: None,
319 on_link: None,
320 on_selection: None,
321 }
322 }
323}
324
325#[day_macros::builder(LabelBuilder)]
326impl Label {
327 pub fn single_line(mut self) -> Self {
330 self.wraps = false;
331 self
332 }
333 pub fn max_lines<M>(mut self, lines: impl IntoReactive<u32, M>) -> Self {
338 self.max_lines = lines.into_reactive();
339 self
340 }
341 pub fn truncation<M>(mut self, mode: impl IntoReactive<Truncation, M>) -> Self {
346 self.truncation = mode.into_reactive();
347 self
348 }
349 pub fn letter_spacing<M>(mut self, ems: impl IntoReactive<f64, M>) -> Self {
352 self.letter_spacing = ems.into_reactive();
353 self
354 }
355 pub fn line_height<M>(mut self, multiple: impl IntoReactive<f64, M>) -> Self {
359 self.line_height = multiple.into_reactive();
360 self
361 }
362 pub fn font(mut self, f: Font) -> Self {
365 self.font = f;
366 self
367 }
368 pub fn font_scale<M>(mut self, scale: impl IntoReactive<f64, M>) -> Self {
372 self.font_scale = scale.into_reactive();
373 self
374 }
375 pub fn max_text_scale(mut self, cap: f64) -> Self {
381 self.max_text_scale = (cap.is_finite() && cap > 0.0).then_some(cap);
382 self
383 }
384 pub fn weight(mut self, w: day_spec::FontWeight) -> Self {
386 self.weight = Some(w);
387 self
388 }
389 pub fn bold(self) -> Self {
391 self.weight(day_spec::FontWeight::Bold)
392 }
393 pub fn secondary(mut self) -> Self {
401 self.role = day_spec::props::TextRole::Secondary;
402 self
403 }
404 pub fn italic(mut self) -> Self {
406 self.italic = true;
407 self
408 }
409 pub fn tabular(mut self) -> Self {
415 self.tabular = true;
416 self
417 }
418 pub fn monospace(mut self) -> Self {
421 self.monospace = true;
422 self
423 }
424 pub fn small_caps(mut self) -> Self {
428 self.small_caps = true;
429 self
430 }
431 pub fn oldstyle_figures(mut self) -> Self {
434 self.oldstyle_figures = true;
435 self
436 }
437 pub fn underline(mut self, decoration: impl Into<day_spec::Decoration>) -> Self {
443 self.underline = Some(decoration.into());
444 self
445 }
446 pub fn strikethrough(mut self, decoration: impl Into<day_spec::Decoration>) -> Self {
448 self.strikethrough = Some(decoration.into());
449 self
450 }
451 pub fn runs(mut self, runs: Vec<day_spec::TextRun>) -> Self {
461 self.runs = runs;
462 self
463 }
464 pub fn runs_from(mut self, b: TextBuilder) -> Self {
468 let (text, runs) = b.build();
469 self.text = TextSource::Static(text);
470 self.runs = runs;
471 self
472 }
473 pub fn align(mut self, align: day_spec::props::TextAlign) -> Self {
477 self.align = align;
478 self
479 }
480 pub fn markdown(mut self) -> Self {
499 self.markdown = true;
500 self
501 }
502 pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
511 self.on_link = Some(Rc::new(f));
512 self
513 }
514 pub fn on_selection(mut self, f: impl Fn(&SelectedText) + 'static) -> Self {
521 self.on_selection = Some(Rc::new(f));
522 self
523 }
524 pub fn color<M>(mut self, c: impl IntoReactive<day_spec::Ink, M>) -> Self {
529 self.color = Some(c.into_reactive());
530 self
531 }
532 pub fn preset(mut self, preset: &crate::TextPreset) -> Self {
535 self.font = preset.font;
536 self.font_scale = Reactive::Const(preset.font_scale);
537 if preset.weight.is_some() {
538 self.weight = preset.weight;
539 }
540 self.italic |= preset.italic;
541 self.tabular |= preset.tabular;
542 self.monospace |= preset.monospace;
543 self.small_caps |= preset.small_caps;
544 if preset.secondary {
545 self.role = day_spec::props::TextRole::Secondary;
546 }
547 if preset.single_line {
548 self.wraps = false;
549 }
550 if let Some(c) = preset.color {
551 self.color = Some(Reactive::Const(c));
552 }
553 if let Some(ems) = preset.letter_spacing {
554 self.letter_spacing = Reactive::Const(ems);
555 }
556 if let Some(multiple) = preset.line_height {
557 self.line_height = Reactive::Const(multiple);
558 }
559 if preset.max_text_scale.is_some() {
560 self.max_text_scale = preset.max_text_scale;
561 }
562 self
563 }
564}
565
566struct LabelState {
569 markdown: bool,
570 font: Font,
571 spec: std::cell::Cell<day_spec::FontSpec>,
573 color: Option<day_spec::Ink>,
574 underline: Option<day_spec::Decoration>,
575 strikethrough: Option<day_spec::Decoration>,
576 link: Option<String>,
577 source: RefCell<String>,
579 displayed: RefCell<String>,
581}
582
583impl LabelState {
584 fn covers(&self) -> bool {
586 self.link.is_some() || self.underline.is_some() || self.strikethrough.is_some()
587 }
588
589 fn shape(&self, source: &str, fixed: &[day_spec::TextRun]) -> (String, Vec<day_spec::TextRun>) {
592 let (text, runs) = if self.markdown {
593 day_spec::markdown::parse(source, self.font)
594 } else {
595 (source.to_owned(), fixed.to_vec())
596 };
597 let runs = match day_spec::runs_are_valid(&text, &runs) {
600 Ok(()) => runs,
601 Err(why) => {
602 log::warn!("label runs ignored: {why}; the text renders unstyled");
603 Vec::new()
604 }
605 };
606 let runs = if self.covers() {
607 self.cover(&text, runs)
608 } else {
609 runs
610 };
611 source.clone_into(&mut self.source.borrow_mut());
612 text.clone_into(&mut self.displayed.borrow_mut());
613 (text, runs)
614 }
615
616 fn cover(&self, text: &str, runs: Vec<day_spec::TextRun>) -> Vec<day_spec::TextRun> {
619 let fill = |range: std::ops::Range<usize>| day_spec::TextRun {
620 range,
621 font: self.spec.get(),
622 color: self.color,
623 underline: self.underline,
624 strikethrough: self.strikethrough,
625 link: self.link.clone(),
626 ..day_spec::TextRun::default()
627 };
628 let mut out = Vec::with_capacity(runs.len() * 2 + 1);
629 let mut at = 0usize;
630 for mut run in runs {
631 if run.range.start > at {
632 out.push(fill(at..run.range.start));
633 }
634 at = run.range.end;
635 run.underline = run.underline.or(self.underline);
636 run.strikethrough = run.strikethrough.or(self.strikethrough);
637 if run.link.is_none() {
638 run.link.clone_from(&self.link);
639 }
640 out.push(run);
641 }
642 if at < text.len() {
643 out.push(fill(at..text.len()));
644 }
645 out
646 }
647}
648
649fn label_font_scale(scale: &Reactive<f64>, font: Font, cap: Option<f64>) -> f64 {
652 let own = scale.get();
653 let own = if own.is_finite() && own > 0.0 {
654 own
655 } else {
656 1.0
657 };
658 match cap {
659 Some(cap) => {
660 let system = day_core::text_scale_of(font);
661 if system > cap {
662 own * cap / system
663 } else {
664 own
665 }
666 }
667 None => own,
668 }
669}
670
671impl Piece for Label {
672 fn build(mut self, cx: &mut BuildCx) -> RNode {
673 if self.link.is_some()
676 && day_core::capability(day_spec::Cap::TextLinks) != day_spec::Support::Native
677 && let Some(url) = self.link.take()
678 {
679 if self.color.is_none() {
680 self.color = Some(Reactive::Const(LINK_INK));
681 }
682 let handler = self.on_link.clone();
683 return self
684 .on_tap(move || match &handler {
685 Some(f) => f(&url),
686 None => open_link(&url),
687 })
688 .a11y(|b| b.role(Role::Button))
689 .build(cx);
690 }
691 let scale = label_font_scale_untracked(&self.font_scale, self.font, self.max_text_scale);
692 let spec = |scale: f64| day_spec::FontSpec {
693 style: self.font,
694 scale,
695 weight: self.weight,
696 italic: self.italic,
697 tabular: self.tabular,
698 monospace: self.monospace,
699 small_caps: self.small_caps,
700 oldstyle_figures: self.oldstyle_figures,
701 };
702 let color = self
703 .color
704 .as_ref()
705 .map(super::canvas::Reactive::get_untracked);
706 let state = Rc::new(LabelState {
707 markdown: self.markdown,
708 font: self.font,
709 spec: std::cell::Cell::new(spec(scale)),
710 color,
711 underline: self.underline,
712 strikethrough: self.strikethrough,
713 link: self.link.clone(),
714 source: RefCell::new(String::new()),
715 displayed: RefCell::new(String::new()),
716 });
717 let (initial, runs) = state.shape(&self.text.initial(), &self.runs);
718 let paragraph = {
719 let (max_lines, truncation) = (self.max_lines.clone(), self.truncation.clone());
720 let (letter_spacing, line_height) =
721 (self.letter_spacing.clone(), self.line_height.clone());
722 move || LabelParagraph {
723 max_lines: max_lines.get(),
724 truncation: truncation.get(),
725 letter_spacing: letter_spacing.get(),
726 line_height: line_height.get(),
727 }
728 };
729 let seed = day_reactive::untrack(¶graph);
730 let node = cx.leaf(
731 kinds::LABEL,
732 &LabelProps {
733 align: self.align,
734 text: initial,
735 font: state.spec.get(),
736 color,
737 role: self.role,
738 wraps: self.wraps,
739 max_lines: seed.max_lines,
740 truncation: seed.truncation,
741 letter_spacing: seed.letter_spacing,
742 line_height: seed.line_height,
743 reports_selection: self.on_selection.is_some(),
744 runs,
745 },
746 Flex::default(),
747 );
748 let could_link = self.markdown
752 || self.link.is_some()
753 || self.on_link.is_some()
754 || self.runs.iter().any(|r| r.link.is_some());
755 if could_link {
756 let handler = self.on_link.clone();
757 let whole = self.link.clone();
758 cx.on(node, move |ev| match ev {
759 Event::LinkActivated(url) => match &handler {
760 Some(f) => f(url),
761 None => open_link(url),
762 },
763 Event::Tap(_) => {
766 if let Some(url) = &whole {
767 match &handler {
768 Some(f) => f(url),
769 None => open_link(url),
770 }
771 }
772 }
773 _ => {}
774 });
775 }
776 if let Some(handler) = self.on_selection.clone() {
779 with_tree(|t| t.set_node_selectable(node, true));
780 let state = state.clone();
781 cx.on(node, move |ev| {
782 if let Event::TextSelected { start, end } = ev {
783 let shown = state.displayed.borrow();
784 let range = (*start).min(shown.len())..(*end).min(shown.len());
785 let text = shown.get(range.clone()).unwrap_or_default().to_owned();
786 drop(shown);
787 let range = if text.is_empty() { 0..0 } else { range };
788 handler(&SelectedText { text, range });
789 }
790 });
791 }
792 let styled = self.markdown || state.covers();
795 {
796 let state = state.clone();
797 self.text.bind_to(
798 node,
799 move |t| {
800 let (text, runs) = state.shape(&t, &[]);
801 if styled {
802 Box::new(LabelPatch::Runs(text, runs))
803 } else {
804 Box::new(LabelPatch::Text(text))
805 }
806 },
807 true,
808 );
809 }
810 if matches!(self.font_scale, Reactive::Dyn(_)) || self.max_text_scale.is_some() {
812 let (font_scale, font, cap) = (self.font_scale.clone(), self.font, self.max_text_scale);
813 let state = state.clone();
814 bind_seeded(
816 scale,
817 move || label_font_scale(&font_scale, font, cap),
818 move |scale: &f64| {
819 let mut next = state.spec.get();
820 next.scale = *scale;
821 state.spec.set(next);
822 with_tree(|t| t.patch(node, Box::new(LabelPatch::Font(next)), true));
823 if state.covers() {
825 let source = state.source.borrow().clone();
826 let (text, runs) = state.shape(&source, &[]);
827 with_tree(|t| t.patch(node, Box::new(LabelPatch::Runs(text, runs)), true));
828 }
829 },
830 );
831 }
832 let reactive_paragraph = matches!(self.max_lines, Reactive::Dyn(_))
834 || matches!(self.truncation, Reactive::Dyn(_))
835 || matches!(self.letter_spacing, Reactive::Dyn(_))
836 || matches!(self.line_height, Reactive::Dyn(_));
837 if reactive_paragraph {
838 bind_seeded(seed, paragraph, move |p: &LabelParagraph| {
839 with_tree(|t| t.patch(node, Box::new(LabelPatch::Paragraph(*p)), true));
840 });
841 }
842 if let Some(Reactive::Dyn(f)) = self.color {
844 bind(
845 move || f(),
846 move |c: &day_spec::Ink| {
847 with_tree(|t| t.patch(node, Box::new(LabelPatch::Color(Some(*c))), false));
848 },
849 );
850 }
851 node
852 }
853}
854
855fn label_font_scale_untracked(scale: &Reactive<f64>, font: Font, cap: Option<f64>) -> f64 {
857 day_reactive::untrack(|| label_font_scale(scale, font, cap))
858}
859
860const LINK_INK: day_spec::Ink = day_spec::Ink::system(day_spec::SystemColor::Link);
863
864pub fn open_link(target: &str) {
875 if let Some(route) = target.strip_prefix('#') {
876 let _ = day_core::navigate(route);
877 } else {
878 day_core::open_url(target);
879 }
880}
881
882pub fn link<M>(text: impl IntoText<M>, url: impl Into<String>) -> Label {
899 let mut label = label(text);
900 label.link = Some(url.into());
901 label
902}
903
904#[must_use]
905pub struct Button {
906 title: TextSource,
907 icon: Reactive<Option<day_spec::Icon>>,
908 icon_only: bool,
909 action: Option<Rc<dyn Fn()>>,
910 native_style: day_spec::props::ButtonStyleSpec,
911 tint: Option<Reactive<day_spec::Ink>>,
914 enabled: Reactive<bool>,
915 selected: Reactive<bool>,
916}
917
918pub fn button<M>(title: impl IntoText<M>) -> Button {
919 Button {
920 title: title.into_text(),
921 icon: Reactive::Const(None),
922 icon_only: false,
923 action: None,
924 native_style: day_spec::props::ButtonStyleSpec::Automatic,
925 tint: None,
926 enabled: true.into_reactive(),
927 selected: false.into_reactive(),
928 }
929}
930
931#[day_macros::builder(ButtonBuilder)]
932impl Button {
933 pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
935 let symbol = symbol.into_reactive();
936 self.icon = match symbol {
937 Reactive::Const(s) => Reactive::Const(Some(day_spec::Icon::Symbol(s))),
938 Reactive::Dyn(f) => Reactive::Dyn(Rc::new(move || Some(day_spec::Icon::Symbol(f())))),
939 };
940 self
941 }
942
943 pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
945 self.icon = Reactive::Const(Some(day_spec::Icon::Image(name.into().as_str().to_owned())));
946 self
947 }
948
949 pub fn icon_only(mut self) -> Self {
951 self.icon_only = true;
952 self
953 }
954
955 pub fn action(mut self, f: impl Fn() + 'static) -> Self {
962 self.action = Some(Rc::new(f));
963 self
964 }
965
966 pub fn bordered(mut self) -> Self {
969 self.native_style = day_spec::props::ButtonStyleSpec::Bordered;
970 self
971 }
972
973 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
980 self.enabled = v.into_reactive();
981 self
982 }
983
984 pub fn prominent(mut self) -> Self {
988 self.native_style = day_spec::props::ButtonStyleSpec::Prominent;
989 self
990 }
991
992 pub fn tint<M>(mut self, color: impl IntoReactive<day_spec::Ink, M>) -> Self {
1006 self.tint = Some(color.into_reactive());
1007 self
1008 }
1009
1010 pub fn compact(mut self) -> Self {
1015 if self.native_style != day_spec::props::ButtonStyleSpec::Plain {
1016 self.native_style = day_spec::props::ButtonStyleSpec::Compact;
1017 }
1018 self
1019 }
1020
1021 pub fn plain(mut self) -> Self {
1024 self.native_style = day_spec::props::ButtonStyleSpec::Plain;
1025 self
1026 }
1027
1028 pub fn selected<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1038 self.selected = v.into_reactive();
1039 self
1040 }
1041}
1042
1043impl Piece for Button {
1044 fn build(self, cx: &mut BuildCx) -> RNode {
1045 let initial = self.title.initial();
1046 let style = match &self.tint {
1048 Some(c) => day_spec::props::ButtonStyleSpec::Tinted(c.get_untracked()),
1049 None => self.native_style,
1050 };
1051 let node = cx.leaf(
1052 kinds::BUTTON,
1053 &ButtonProps {
1054 title: initial.clone(),
1055 icon: self.icon.get_untracked(),
1056 icon_only: self.icon_only,
1057 enabled: self.enabled.get_untracked(),
1058 style,
1059 selected: self.selected.get_untracked(),
1060 },
1061 Flex::default(),
1062 );
1063 if let selected @ Reactive::Dyn(_) = self.selected {
1065 bind(
1066 move || selected.get(),
1067 move |on: &bool| {
1068 with_tree(|t| t.patch(node, Box::new(ButtonPatch::Selected(*on)), false));
1069 },
1070 );
1071 }
1072 if let Some(c @ Reactive::Dyn(_)) = self.tint.clone() {
1074 bind(
1075 move || c.get(),
1076 move |col: &day_spec::Ink| {
1077 with_tree(|t| {
1078 t.patch(
1079 node,
1080 Box::new(ButtonPatch::Style(
1081 day_spec::props::ButtonStyleSpec::Tinted(*col),
1082 )),
1083 false,
1084 );
1085 });
1086 },
1087 );
1088 }
1089 let enabled = self.enabled;
1092 let enabled_gate = enabled.clone();
1093 if let Reactive::Dyn(_) = &enabled {
1094 bind(
1095 move || enabled.get(),
1096 move |e: &bool| {
1097 with_tree(|t| t.patch(node, Box::new(ButtonPatch::Enabled(*e)), false));
1098 },
1099 );
1100 }
1101 if let Some(action) = self.action {
1102 let gate = enabled_gate;
1108 cx.on(node, move |ev| {
1109 if matches!(ev, Event::Pressed) && gate.get() {
1110 action();
1111 }
1112 });
1113 }
1114 if matches!(&self.icon, Reactive::Const(None)) {
1115 self.title
1117 .bind_to(node, |t| Box::new(ButtonPatch::Title(t)), true);
1118 } else {
1119 let icon = self.icon;
1120 let icon_only = self.icon_only;
1121 let seed = day_spec::props::ButtonContent {
1122 title: initial,
1123 icon: icon.get_untracked(),
1124 icon_only,
1125 };
1126 let title = self.title;
1127 bind_seeded(
1128 seed,
1129 move || day_spec::props::ButtonContent {
1130 title: title.resolve(),
1131 icon: icon.get(),
1132 icon_only,
1133 },
1134 move |content: &day_spec::props::ButtonContent| {
1135 with_tree(|t| {
1136 t.patch(node, Box::new(ButtonPatch::Content(content.clone())), true);
1137 });
1138 },
1139 );
1140 }
1141 node
1142 }
1143}
1144
1145#[must_use]
1146pub struct Toggle<S: Binding<bool>> {
1147 value: S,
1148 enabled: Reactive<bool>,
1149}
1150
1151pub fn toggle<S: Binding<bool>>(value: S) -> Toggle<S> {
1152 Toggle {
1153 value,
1154 enabled: true.into_reactive(),
1155 }
1156}
1157
1158#[day_macros::builder(ToggleBuilder)]
1159impl<S: Binding<bool>> Toggle<S> {
1160 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1164 self.enabled = v.into_reactive();
1165 self
1166 }
1167}
1168
1169impl<S: Binding<bool>> Piece for Toggle<S> {
1170 fn build(self, cx: &mut BuildCx) -> RNode {
1171 let initial = self.value.peek();
1172 let node = cx.leaf(
1173 kinds::TOGGLE,
1174 &ToggleProps {
1175 on: initial,
1176 enabled: self.enabled.get_untracked(),
1177 },
1178 Flex::default(),
1179 );
1180 let v = self.value.clone();
1181 bind_seeded(
1182 initial,
1183 move || v.read(),
1184 move |on: &bool| {
1185 with_tree(|t| t.patch(node, Box::new(TogglePatch::On(*on)), false));
1186 },
1187 );
1188 let enabled = self.enabled;
1190 if let Reactive::Dyn(_) = &enabled {
1191 bind(
1192 move || enabled.get(),
1193 move |e: &bool| {
1194 with_tree(|t| t.patch(node, Box::new(TogglePatch::Enabled(*e)), false));
1195 },
1196 );
1197 }
1198 let v = self.value;
1199 cx.on(node, move |ev| {
1200 if let Event::ToggleChanged(on) = ev
1206 && v.peek() != *on
1207 {
1208 v.write(*on);
1209 }
1210 });
1211 node
1212 }
1213}
1214
1215#[must_use]
1216pub struct Slider<S: Binding<f64>> {
1217 value: S,
1218 min: f64,
1219 max: f64,
1220 step: Option<f64>,
1221 enabled: Reactive<bool>,
1222}
1223
1224pub fn slider<S: Binding<f64>>(value: S) -> Slider<S> {
1225 Slider {
1226 value,
1227 min: 0.0,
1228 max: 1.0,
1229 step: None,
1230 enabled: Reactive::Const(true),
1231 }
1232}
1233
1234#[day_macros::builder(SliderBuilder)]
1235impl<S: Binding<f64>> Slider<S> {
1236 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1238 self.enabled = v.into_reactive();
1239 self
1240 }
1241 pub fn range(mut self, r: std::ops::RangeInclusive<f64>) -> Self {
1242 self.min = *r.start();
1243 self.max = *r.end();
1244 self
1245 }
1246 pub fn step(mut self, s: f64) -> Self {
1247 self.step = Some(s);
1248 self
1249 }
1250}
1251
1252impl<S: Binding<f64>> Piece for Slider<S> {
1253 fn build(self, cx: &mut BuildCx) -> RNode {
1254 let initial = self.value.peek();
1255 let node = cx.leaf(
1256 kinds::SLIDER,
1257 &SliderProps {
1258 value: initial,
1259 min: self.min,
1260 max: self.max,
1261 step: self.step,
1262 enabled: self.enabled.get_untracked(),
1263 },
1264 Flex {
1265 grow_w: true,
1266 ..Default::default()
1267 },
1268 );
1269 let enabled = self.enabled;
1270 if let Reactive::Dyn(_) = &enabled {
1271 bind(
1272 move || enabled.get(),
1273 move |e: &bool| {
1274 with_tree(|t| t.patch(node, Box::new(SliderPatch::Enabled(*e)), false));
1275 },
1276 );
1277 }
1278 let v = self.value.clone();
1279 bind_seeded(
1280 initial,
1281 move || v.read(),
1282 move |val: &f64| {
1283 with_tree(|t| t.patch(node, Box::new(SliderPatch::Value(*val)), false));
1284 },
1285 );
1286 let v = self.value;
1287 let (step, min, max) = (self.step, self.min, self.max);
1288 cx.on(node, move |ev| {
1289 let snap = |val: f64| match step {
1295 Some(s) if s > 0.0 => (min + ((val - min) / s).round() * s).clamp(min, max),
1296 _ => val,
1297 };
1298 match ev {
1299 Event::ValueChanged(val) => v.write_preview(snap(*val)),
1302 Event::ValueCommitted(val) => v.write_commit(snap(*val)),
1306 _ => {}
1307 }
1308 });
1309 node
1310 }
1311}
1312
1313#[must_use]
1318pub struct TextField<S: Binding<String>> {
1319 value: S,
1320 placeholder: Option<TextSource>,
1321 on_submit: Option<Rc<dyn Fn()>>,
1322 secure: Reactive<bool>,
1323 read_only: Reactive<bool>,
1324 purpose: day_spec::InputPurpose,
1325 submit_label: day_spec::SubmitLabel,
1326 max_length: Option<u32>,
1327 enabled: Reactive<bool>,
1328 select: Option<(day_reactive::Trigger, Rc<dyn Fn() -> TextSelection>)>,
1329}
1330
1331pub fn text_field<S: Binding<String>>(value: S) -> TextField<S> {
1332 TextField {
1333 value,
1334 placeholder: None,
1335 on_submit: None,
1336 secure: Reactive::Const(false),
1337 read_only: Reactive::Const(false),
1338 purpose: day_spec::InputPurpose::Text,
1339 submit_label: day_spec::SubmitLabel::Return,
1340 max_length: None,
1341 enabled: Reactive::Const(true),
1342 select: None,
1343 }
1344}
1345
1346pub fn secure_field<S: Binding<String>>(value: S) -> TextField<S> {
1353 text_field(value)
1354 .secure(true)
1355 .input_purpose(day_spec::InputPurpose::Password)
1356}
1357
1358#[day_macros::builder(TextFieldBuilder)]
1359impl<S: Binding<String>> TextField<S> {
1360 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1363 self.enabled = v.into_reactive();
1364 self
1365 }
1366 pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
1367 self.placeholder = Some(t.into_text());
1368 self
1369 }
1370 pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
1374 self.on_submit = Some(Rc::new(f));
1375 self
1376 }
1377 pub fn secure<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1382 self.secure = v.into_reactive();
1383 self
1384 }
1385 pub fn read_only<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1389 self.read_only = v.into_reactive();
1390 self
1391 }
1392 pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
1395 self.purpose = purpose;
1396 self
1397 }
1398 pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
1400 self.submit_label = label;
1401 self
1402 }
1403 pub fn max_length(mut self, characters: u32) -> Self {
1406 self.max_length = Some(characters);
1407 self
1408 }
1409 pub fn select<R: std::ops::RangeBounds<usize> + 'static>(
1428 mut self,
1429 trigger: day_reactive::Trigger,
1430 range: impl Fn() -> R + 'static,
1431 ) -> Self {
1432 self.select = Some((
1433 trigger,
1434 Rc::new(move || {
1435 use std::ops::Bound;
1436 let r = range();
1437 let start = match r.start_bound() {
1438 Bound::Included(&n) => n,
1439 Bound::Excluded(&n) => n.saturating_add(1),
1440 Bound::Unbounded => 0,
1441 };
1442 let end = match r.end_bound() {
1443 Bound::Included(&n) => n.saturating_add(1),
1444 Bound::Excluded(&n) => n,
1445 Bound::Unbounded => usize::MAX,
1446 };
1447 TextSelection::new(start, end)
1448 }),
1449 ));
1450 self
1451 }
1452}
1453
1454impl<S: Binding<String>> Piece for TextField<S> {
1455 fn build(self, cx: &mut BuildCx) -> RNode {
1456 let initial = self.value.peek();
1457 let ph = self
1458 .placeholder
1459 .as_ref()
1460 .map_or_default(super::sources::TextSource::initial);
1461 let node = cx.leaf(
1462 kinds::TEXT_FIELD,
1463 &TextFieldProps {
1464 text: initial.clone(),
1465 placeholder: ph,
1466 enabled: self.enabled.get_untracked(),
1467 },
1468 Flex {
1469 grow_w: true,
1470 ..Default::default()
1471 },
1472 );
1473 if let Reactive::Dyn(_) = &self.enabled {
1474 let enabled = self.enabled.clone();
1475 bind(
1476 move || enabled.get(),
1477 move |e: &bool| {
1478 with_tree(|t| t.patch(node, Box::new(TextFieldPatch::Enabled(*e)), false));
1479 },
1480 );
1481 }
1482 let (secure, read_only) = (self.secure, self.read_only);
1487 let (purpose, submit_label, max_length) =
1488 (self.purpose, self.submit_label, self.max_length);
1489 let traits = move |secure: bool, read_only: bool| day_spec::InputTraits {
1490 secure,
1491 read_only,
1492 purpose,
1493 submit_label,
1494 max_length,
1495 };
1496 let initial_traits = traits(secure.get_untracked(), read_only.get_untracked());
1497 let reactive_traits =
1498 matches!(secure, Reactive::Dyn(_)) || matches!(read_only, Reactive::Dyn(_));
1499 if initial_traits != day_spec::InputTraits::default() {
1500 with_tree(|t| t.set_node_input_traits(node, &initial_traits));
1501 }
1502 if reactive_traits {
1503 bind_seeded(
1504 initial_traits,
1505 move || traits(secure.get(), read_only.get()),
1506 move |tr: &day_spec::InputTraits| {
1507 with_tree(|t| t.set_node_input_traits(node, tr));
1508 },
1509 );
1510 }
1511 let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1514 let last: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1516 let v = self.value.clone();
1517 let session = self.value.clone();
1518 let (g, typed) = (guard.clone(), last.clone());
1519 bind_seeded(
1520 initial,
1521 move || v.read(),
1522 move |t: &String| {
1523 let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
1524 if !from_native && typed.borrow_mut().take().is_some() {
1525 session.end_preview();
1531 }
1532 with_tree(|tr| {
1533 tr.patch(
1534 node,
1535 Box::new(TextFieldPatch::Text {
1536 text: t.clone(),
1537 from_native,
1538 }),
1539 false,
1540 );
1541 });
1542 },
1543 );
1544 let value = self.value.clone();
1545 let v = self.value;
1546 let submit = self.on_submit;
1547 {
1553 let (v, last) = (v.clone(), last.clone());
1554 day_reactive::Scope::current().on_cleanup(move || {
1555 if let Some(t) = last.borrow_mut().take() {
1556 v.write_teardown(t);
1557 }
1558 });
1559 }
1560 cx.on(node, move |ev| match ev {
1561 Event::TextChanged(t) => {
1562 let cut = max_length
1567 .and_then(|max| t.char_indices().nth(max as usize))
1568 .map(|(at, _)| t[..at].to_string());
1569 let t = match cut {
1570 Some(cut) => {
1571 with_tree(|tr| {
1572 tr.patch(
1573 node,
1574 Box::new(TextFieldPatch::Text {
1575 text: cut.clone(),
1576 from_native: false,
1577 }),
1578 false,
1579 );
1580 });
1581 cut
1582 }
1583 None => t.clone(),
1584 };
1585 *guard.borrow_mut() = Some(t.clone());
1586 *last.borrow_mut() = Some(t.clone());
1587 v.write_preview(t);
1588 }
1589 Event::Submitted => {
1590 if let Some(t) = last.borrow_mut().take() {
1591 v.write_commit(t);
1592 }
1593 if let Some(f) = &submit {
1594 f();
1595 }
1596 }
1597 Event::FocusChanged(false) => {
1598 if let Some(t) = last.borrow_mut().take() {
1599 v.write_commit(t);
1600 }
1601 }
1602 _ => {}
1603 });
1604 if let Some(p) = self.placeholder {
1605 p.bind_to(node, |t| Box::new(TextFieldPatch::Placeholder(t)), false);
1606 }
1607 if let Some((trigger, range)) = self.select {
1614 let scope = day_reactive::Scope::current();
1615 day_reactive::watch(
1616 move || trigger.track(),
1617 move |(), _| {
1618 let (range, value) = (range.clone(), value.clone());
1619 day_reactive::at_turn_end(move || {
1620 if !scope.is_alive() {
1621 return;
1622 }
1623 let sel = range().clamped(&value.peek());
1624 day_reactive::on_main(move || {
1625 with_tree(|t| {
1626 t.patch(node, Box::new(TextFieldPatch::Select(sel)), false);
1627 });
1628 });
1629 });
1630 },
1631 );
1632 }
1633 node
1634 }
1635}
1636
1637#[must_use]
1640pub struct Progress {
1641 value: Option<FractionSource>,
1643 animating: crate::Reactive<bool>,
1644 large: bool,
1645}
1646
1647pub fn spinner() -> Progress {
1650 Progress {
1651 value: None,
1652 animating: crate::Reactive::Const(true),
1653 large: false,
1654 }
1655}
1656
1657pub fn progress<M>(fraction: impl IntoFraction<M>) -> Progress {
1661 Progress {
1662 value: Some(fraction.into_fraction()),
1663 animating: crate::Reactive::Const(true),
1664 large: false,
1665 }
1666}
1667
1668#[day_macros::builder(ProgressBuilder)]
1669impl Progress {
1670 pub fn animating<M>(mut self, source: impl crate::IntoReactive<bool, M>) -> Self {
1672 self.animating = source.into_reactive();
1673 self
1674 }
1675 pub fn large(mut self) -> Self {
1677 self.large = true;
1678 self
1679 }
1680}
1681
1682impl Piece for Progress {
1683 fn build(self, cx: &mut BuildCx) -> RNode {
1684 let determinate = self.value.is_some();
1685 let initial = self
1686 .value
1687 .as_ref()
1688 .map(super::sources::FractionSource::initial);
1689 let node = cx.leaf(
1690 kinds::PROGRESS,
1691 &ProgressProps {
1692 value: initial,
1693 animating: self.animating.get_untracked(),
1694 large: self.large,
1695 },
1696 Flex {
1699 grow_w: determinate,
1700 ..Default::default()
1701 },
1702 );
1703 if !determinate && let crate::Reactive::Dyn(f) = self.animating {
1704 day_reactive::bind_seeded(
1705 f(),
1706 move || f(),
1707 move |on| {
1708 day_core::with_tree(|t| {
1709 t.patch(node, Box::new(ProgressPatch::Animating(*on)), false);
1710 });
1711 },
1712 );
1713 }
1714 if let Some(src) = self.value {
1715 src.bind_to(node);
1716 }
1717 node
1718 }
1719}
1720
1721#[must_use]
1724pub struct Divider {
1725 vertical: bool,
1726}
1727
1728pub fn divider() -> Divider {
1729 Divider { vertical: false }
1730}
1731
1732#[day_macros::builder(DividerBuilder)]
1733impl Divider {
1734 pub fn vertical(mut self) -> Self {
1738 self.vertical = true;
1739 self
1740 }
1741}
1742
1743impl Piece for Divider {
1744 fn build(self, cx: &mut BuildCx) -> RNode {
1745 let props = DividerProps {
1746 vertical: self.vertical,
1747 };
1748 if self.vertical {
1749 cx.native(
1750 kinds::DIVIDER,
1751 &props,
1752 Rc::new(VerticalLeaf),
1753 Flex {
1754 grow_h: true,
1755 ..Default::default()
1756 },
1757 Boundary::No,
1758 )
1759 } else {
1760 cx.leaf(
1761 kinds::DIVIDER,
1762 &props,
1763 Flex {
1764 grow_w: true,
1765 ..Default::default()
1766 },
1767 )
1768 }
1769 }
1770}
1771
1772struct VerticalLeaf;
1776
1777impl Layout for VerticalLeaf {
1778 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1779 let s = cx.measure_leaf(Proposal::new(p.height, p.width));
1780 Size::new(s.height, s.width)
1781 }
1782 fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
1783}
1784
1785pub struct Spacer;
1786
1787#[must_use]
1788pub fn spacer() -> Spacer {
1789 Spacer
1790}
1791
1792impl Piece for Spacer {
1793 fn build(self, cx: &mut BuildCx) -> RNode {
1794 cx.layout_only(
1795 Rc::new(PassThrough),
1796 Flex {
1797 is_spacer: true,
1798 ..Default::default()
1799 },
1800 Boundary::No,
1801 )
1802 }
1803}
1804
1805#[cfg(feature = "conformance")]
1814pub(crate) mod conformance {
1815 use day_core::Piece;
1816 use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
1817 use day_reactive::Signal;
1818 use day_spec::props::Truncation;
1819 use day_spec::{Cap, Font, Role, kinds};
1820
1821 use crate::*;
1822
1823 #[day_macros::test(day_core)]
1825 fn button_press() -> Case {
1826 let presses = Signal::new(0i64);
1827 Case::new()
1828 .proves(kinds::BUTTON)
1829 .page(move || {
1830 column((
1831 button("Press")
1832 .action(move || presses.update(|n| *n += 1))
1833 .id(day_core::id!(press)),
1834 label(move || presses.get().to_string()).id(day_core::id!(count)),
1835 ))
1836 .spacing(8.0)
1837 })
1838 .shot("default")
1839 .drive(|d: Drive| async move {
1840 d.assert_text("press", "Press").await?;
1841 d.tap("press").await?;
1842 d.assert_text("count", "1").await?;
1843 d.tap("press").await?;
1844 d.assert_text("count", "2").await
1845 })
1846 }
1847
1848 #[day_macros::test(day_core)]
1852 fn button_disabled() -> Case {
1853 let presses = Signal::new(0i64);
1854 let enabled = Signal::new(false);
1855 Case::new()
1856 .proves(kinds::BUTTON)
1857 .proves_duty("set_enabled")
1858 .page(move || {
1859 column((
1860 button("Off")
1861 .enabled(move || enabled.get())
1862 .action(move || presses.update(|n| *n += 1))
1863 .id(day_core::id!(off)),
1864 label(move || presses.get().to_string()).id(day_core::id!(count)),
1865 button("Enable")
1866 .action(move || enabled.set(true))
1867 .id(day_core::id!(enable)),
1868 ))
1869 .spacing(8.0)
1870 })
1871 .drive(|d: Drive| async move {
1872 d.assert_enabled("off", false).await?;
1873 d.assert_text("count", "0").await?;
1874 d.tap("enable").await?;
1875 d.assert_enabled("off", true).await?;
1876 d.tap("off").await?;
1877 d.assert_text("count", "1").await
1878 })
1879 }
1880
1881 #[day_macros::test(day_core)]
1883 fn toggle_binding() -> Case {
1884 let on = Signal::new(false);
1885 Case::new()
1886 .proves(kinds::TOGGLE)
1887 .page(move || {
1888 column((
1889 toggle(on).id(day_core::id!(tgl_switch)),
1890 label(move || if on.get() { "on" } else { "off" }.to_owned())
1891 .id(day_core::id!(tgl_state)),
1892 button("Set on")
1893 .action(move || on.set(true))
1894 .id(day_core::id!(tgl_set)),
1895 ))
1896 .spacing(8.0)
1897 })
1898 .drive(|d: Drive| async move {
1899 d.toggle("tgl_switch", true).await?;
1900 d.assert_text("tgl_state", "on").await?;
1901 d.toggle("tgl_switch", false).await?;
1902 d.assert_text("tgl_state", "off").await?;
1903 d.tap("tgl_set").await?;
1904 d.assert_on("tgl_switch", true).await
1905 })
1906 }
1907
1908 #[day_macros::test(day_core)]
1912 fn toggle_flip_is_one_change() -> Case {
1913 let on = Signal::new(false);
1914 let changes = Signal::new(0u32);
1915 Case::new()
1916 .proves(kinds::TOGGLE)
1917 .page(move || {
1918 day_reactive::watch(move || on.get(), move |_, _| changes.update(|n| *n += 1));
1919 column((
1920 toggle(on).id(day_core::id!(tgl_once)),
1921 button("Set on")
1922 .action(move || on.set(true))
1923 .id(day_core::id!(tgl_once_set)),
1924 label(move || format!("changes {}", changes.get()))
1925 .id(day_core::id!(tgl_once_changes)),
1926 ))
1927 .spacing(8.0)
1928 })
1929 .drive(|d: Drive| async move {
1930 d.toggle("tgl_once", true).await?;
1931 d.wait_idle().await?;
1932 d.pause(0.3).await?;
1933 d.assert_text("tgl_once_changes", "changes 1").await?;
1934 d.toggle("tgl_once", false).await?;
1935 d.wait_idle().await?;
1936 d.pause(0.3).await?;
1937 d.assert_text("tgl_once_changes", "changes 2").await?;
1938 d.tap("tgl_once_set").await?;
1939 d.wait_idle().await?;
1940 d.pause(0.3).await?;
1941 d.assert_on("tgl_once", true).await?;
1942 d.assert_text("tgl_once_changes", "changes 3").await
1943 })
1944 }
1945
1946 #[day_macros::test(day_core)]
1948 fn text_field_binding() -> Case {
1949 let name = Signal::new(String::new());
1950 Case::new()
1951 .proves(kinds::TEXT_FIELD)
1952 .page(move || {
1953 column((
1954 text_field(name)
1955 .placeholder("Name")
1956 .id(day_core::id!(tf_field)),
1957 label(move || name.get()).id(day_core::id!(tf_echo)),
1958 button("Set")
1959 .action(move || name.set("Ada".into()))
1960 .id(day_core::id!(tf_set)),
1961 ))
1962 .spacing(8.0)
1963 })
1964 .drive(|d: Drive| async move {
1965 d.input("tf_field", "Grace").await?;
1966 d.assert_text("tf_echo", "Grace").await?;
1967 d.tap("tf_set").await?;
1968 d.assert_text("tf_field", "Ada").await
1969 })
1970 }
1971
1972 #[day_macros::test(day_core)]
1975 fn text_field_secure() -> Case {
1976 let password = Signal::new(String::new());
1977 let shown = Signal::new(false);
1978 Case::new()
1979 .proves(kinds::TEXT_FIELD)
1980 .proves_duty("set_input_traits")
1981 .page(move || {
1982 column((
1983 secure_field(password)
1984 .secure(move || !shown.get())
1985 .placeholder("Password")
1986 .id(day_core::id!(tfs_pass)),
1987 toggle(shown).id(day_core::id!(tfs_show)),
1988 label(move || password.get().chars().count().to_string())
1989 .id(day_core::id!(tfs_len)),
1990 ))
1991 .spacing(8.0)
1992 })
1993 .shot("masked")
1994 .drive(|d: Drive| async move {
1995 d.input("tfs_pass", "correct horse").await?;
1996 d.assert_text("tfs_len", "13").await?;
1997 d.focus("tfs_pass").await?;
1998 d.toggle("tfs_show", true).await?;
1999 d.wait_idle().await?;
2000 d.shot("shown").await?;
2001 d.assert_focused("tfs_pass", true).await?;
2002 d.input("tfs_pass", "battery").await?;
2003 d.assert_text("tfs_len", "7").await?;
2004 d.toggle("tfs_show", false).await?;
2005 d.wait_idle().await?;
2006 d.assert_text("tfs_pass", "battery").await
2007 })
2008 }
2009
2010 #[day_macros::test(day_core)]
2012 fn text_field_max_length() -> Case {
2013 let pin = Signal::new(String::new());
2014 Case::new()
2015 .proves(kinds::TEXT_FIELD)
2016 .page(move || {
2017 column((
2018 text_field(pin).max_length(4).id(day_core::id!(tfm_pin)),
2019 label(move || pin.get()).id(day_core::id!(tfm_echo)),
2020 ))
2021 .spacing(8.0)
2022 })
2023 .drive(|d: Drive| async move {
2024 d.input("tfm_pin", "123456").await?;
2025 d.assert_text("tfm_echo", "1234").await?;
2026 d.assert_text("tfm_pin", "1234").await
2027 })
2028 }
2029
2030 #[day_macros::test(day_core)]
2033 fn slider_range() -> Case {
2034 let value = Signal::new(40.0f64);
2035 Case::new()
2036 .proves(kinds::SLIDER)
2037 .page(move || {
2038 column((
2039 slider(value)
2040 .range(0.0..=100.0)
2041 .step(10.0)
2042 .id(day_core::id!(sl_slider)),
2043 label(move || format!("{:.0}", value.get())).id(day_core::id!(sl_value)),
2044 ))
2045 .spacing(8.0)
2046 })
2047 .drive(|d: Drive| async move {
2048 d.set_value("sl_slider", 72.0).await?;
2049 d.assert_text("sl_value", "70").await?;
2050 d.assert_value("sl_slider", 70.0).await
2051 })
2052 }
2053
2054 #[day_macros::test(day_core)]
2057 fn label_heading() -> Case {
2058 let text = Signal::new("Hello".to_owned());
2059 Case::new()
2060 .proves(kinds::LABEL)
2061 .proves_duty("set_a11y")
2062 .page(move || {
2063 column((
2064 label(move || text.get())
2065 .font(Font::Headline)
2066 .a11y(|a| a.role(Role::Heading(2)))
2067 .id(day_core::id!(lbl_heading)),
2068 button("Rename")
2069 .action(move || text.set("Renamed".into()))
2070 .id(day_core::id!(lbl_rename)),
2071 ))
2072 .spacing(8.0)
2073 })
2074 .drive(|d: Drive| async move {
2075 d.assert_text("lbl_heading", "Hello").await?;
2076 d.tap("lbl_rename").await?;
2077 d.assert_text("lbl_heading", "Renamed").await?;
2078 d.a11y_audit(Some("lbl_heading")).await
2079 })
2080 }
2081
2082 #[day_macros::test(day_core)]
2084 fn label_text() -> Case {
2085 Case::new()
2086 .proves(kinds::LABEL)
2087 .page(|| label("Plain text").id(day_core::id!(text)))
2088 .drive(|d: Drive| async move { d.assert_text("text", "Plain text").await })
2089 }
2090
2091 #[day_macros::test(day_core)]
2093 fn label_reactive() -> Case {
2094 let count = Signal::new(0i64);
2095 Case::new()
2096 .proves(kinds::LABEL)
2097 .proves_duty("update")
2098 .proves_duty("read_native")
2099 .page(move || {
2100 column((
2101 label(move || format!("Count {}", count.get())).id(day_core::id!(text)),
2102 button("Add")
2103 .action(move || count.update(|n| *n += 1))
2104 .id(day_core::id!(add)),
2105 ))
2106 .spacing(8.0)
2107 })
2108 .drive(|d: Drive| async move {
2109 d.assert_text("text", "Count 0").await?;
2110 d.tap("add").await?;
2111 d.tap("add").await?;
2112 d.assert_text("text", "Count 2").await
2113 })
2114 }
2115
2116 #[day_macros::test(day_core)]
2118 fn label_runs() -> Case {
2119 Case::new()
2120 .proves(kinds::LABEL)
2121 .proves_cap(Cap::TextRuns)
2122 .requires(Cap::TextRuns)
2123 .page(|| {
2124 label("")
2125 .runs_from(
2126 TextBuilder::new()
2127 .text("Plain, ")
2128 .strong("strong")
2129 .text(" and ")
2130 .emphasis("emphasized"),
2131 )
2132 .id(day_core::id!(runs))
2133 })
2134 .shot("default")
2135 .drive(|d: Drive| async move {
2136 d.assert_text("runs", "Plain, strong and emphasized").await
2137 })
2138 }
2139
2140 #[day_macros::test(day_core)]
2142 fn label_runs_keep_the_label_color() -> Case {
2143 let text = Signal::new(
2144 "\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588} **\u{2588}**".to_string(),
2145 );
2146 Case::new()
2147 .proves(kinds::LABEL)
2148 .requires(Cap::TextRuns)
2149 .requires(Cap::Snapshot)
2150 .page(move || {
2151 column((
2152 label(text)
2153 .markdown()
2154 .color(day_spec::Color::rgb(1.0, 0.0, 0.0))
2155 .id(day_core::id!(colored)),
2156 button("Restyle")
2157 .id(day_core::id!(restyle))
2158 .action(move || {
2159 text.set(
2160 "\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588} *\u{2588}*"
2161 .into(),
2162 );
2163 }),
2164 ))
2165 })
2166 .drive(|d: Drive| async move {
2167 d.sample_pixel("colored", 0.1, 0.5, "#ff0000").await?;
2168 d.tap("restyle").await?;
2169 d.sample_pixel("colored", 0.1, 0.5, "#ff0000").await
2170 })
2171 }
2172
2173 #[day_macros::test(day_core)]
2176 fn label_link_runs_reactive() -> Case {
2177 let text = Signal::new("😀 [Alpha](#alpha) / [Beta](#beta)".to_string());
2178 Case::new()
2179 .proves(kinds::LABEL)
2180 .requires(Cap::TextRuns)
2181 .page(move || {
2182 column((
2183 label(text).markdown().id(day_core::id!(links)),
2184 button("Replace")
2185 .id(day_core::id!(replace))
2186 .action(move || {
2187 text.set("[東京](#tokyo) then [again](#again)".into());
2188 }),
2189 button("Plain")
2190 .id(day_core::id!(plain))
2191 .action(move || text.set("Plain 😀".into())),
2192 button("Restore")
2193 .id(day_core::id!(restore))
2194 .action(move || text.set("[Restored](#restored)".into())),
2195 ))
2196 })
2197 .drive(|d: Drive| async move {
2198 d.assert_text("links", "😀 Alpha / Beta").await?;
2199 d.tap("replace").await?;
2200 d.assert_text("links", "東京 then again").await?;
2201 d.tap("plain").await?;
2202 d.assert_text("links", "Plain 😀").await?;
2203 d.tap("restore").await?;
2204 d.assert_text("links", "Restored").await
2205 })
2206 }
2207
2208 fn foot(id: day_core::ElementId) -> impl Piece {
2211 rectangle()
2212 .fill(day_spec::Color::hex(0x0033_6699))
2213 .frame(10.0, 4.0)
2214 .id(id)
2215 }
2216
2217 const LONG: &str = "Day lays this sentence out over many lines when its label is narrow, \
2218 so a line limit has plenty of text to cut and the ellipsis has something to stand for.";
2219
2220 #[day_macros::test(day_core)]
2224 fn label_max_lines() -> Case {
2225 let limit = Signal::new(0u32);
2226 Case::new()
2227 .proves(kinds::LABEL)
2228 .page(move || {
2229 column((
2230 row((
2231 column((
2232 label(LONG)
2233 .max_lines(limit)
2234 .width(100.0)
2235 .id(day_core::id!(ml_text)),
2236 foot(day_core::id!(ml_foot)),
2237 ))
2238 .align(HAlign::Leading),
2239 column((label("Ag\nAg").width(100.0), foot(day_core::id!(ml_two))))
2240 .align(HAlign::Leading),
2241 column((label("Ag").width(100.0), foot(day_core::id!(ml_one))))
2242 .align(HAlign::Leading),
2243 ))
2244 .align(VAlign::Top),
2245 button("Two lines")
2246 .action(move || limit.set(2))
2247 .id(day_core::id!(ml_set_two)),
2248 button("One line")
2249 .action(move || limit.set(1))
2250 .id(day_core::id!(ml_set_one)),
2251 ))
2252 .align(HAlign::Leading)
2253 .spacing(8.0)
2254 })
2255 .shot("unlimited")
2256 .drive(|d: Drive| async move {
2257 let level_with = |other: &str| FrameExpect {
2258 y: Some(0.0),
2259 relative_to: Some(other.into()),
2260 ..Default::default()
2261 };
2262 d.tap("ml_set_two").await?;
2263 d.wait_idle().await?;
2264 d.assert_frame("ml_foot", level_with("ml_two")).await?;
2265 d.shot("two").await?;
2266 d.tap("ml_set_one").await?;
2267 d.wait_idle().await?;
2268 d.assert_frame("ml_foot", level_with("ml_one")).await?;
2269 d.assert_text("ml_text", LONG).await
2270 })
2271 }
2272
2273 #[day_macros::test(day_core)]
2276 fn label_truncation_modes() -> Case {
2277 let mode = Signal::new(Truncation::Middle);
2278 Case::new()
2279 .proves(kinds::LABEL)
2280 .page(move || {
2281 column((
2282 row((
2283 column((
2284 label("/usr/local/share/day/templates/app/src/pages.rs")
2285 .single_line()
2286 .truncation(mode)
2287 .width(120.0)
2288 .id(day_core::id!(tr_path)),
2289 foot(day_core::id!(tr_foot)),
2290 ))
2291 .align(HAlign::Leading),
2292 column((label("Ag").width(120.0), foot(day_core::id!(tr_one))))
2293 .align(HAlign::Leading),
2294 ))
2295 .align(VAlign::Top),
2296 button("Head")
2297 .action(move || mode.set(Truncation::Head))
2298 .id(day_core::id!(tr_head)),
2299 button("Tail")
2300 .action(move || mode.set(Truncation::Tail))
2301 .id(day_core::id!(tr_tail)),
2302 ))
2303 .align(HAlign::Leading)
2304 .spacing(8.0)
2305 })
2306 .shot("middle")
2307 .drive(|d: Drive| async move {
2308 let one_line = || FrameExpect {
2309 y: Some(0.0),
2310 relative_to: Some("tr_one".into()),
2311 ..Default::default()
2312 };
2313 d.assert_frame("tr_foot", one_line()).await?;
2314 d.tap("tr_head").await?;
2315 d.wait_idle().await?;
2316 d.assert_frame("tr_foot", one_line()).await?;
2317 d.shot("head").await?;
2318 d.tap("tr_tail").await?;
2319 d.wait_idle().await?;
2320 d.assert_frame("tr_foot", one_line()).await?;
2321 d.assert_text("tr_path", "/usr/local/share/day/templates/app/src/pages.rs")
2322 .await
2323 })
2324 }
2325
2326 #[day_macros::test(day_core)]
2332 fn label_line_height() -> Case {
2333 let multiple = Signal::new(2.0);
2334 let line = |text: &'static str| label(text).font(Font::System(20.0));
2335 Case::new()
2336 .proves(kinds::LABEL)
2337 .page(move || {
2338 column((
2339 row((
2340 column((
2341 line("Ag").line_height(multiple).id(day_core::id!(lh_one)),
2342 line("Ag").line_height(multiple),
2343 foot(day_core::id!(lh_pair_end)),
2344 ))
2345 .spacing(0.0),
2346 column((
2347 line("Ag\nAg\nAg").line_height(4.0 / 3.0),
2348 foot(day_core::id!(lh_four_end)),
2349 ))
2350 .spacing(0.0),
2351 column((
2352 line("Ag\nAg").line_height(2.0).id(day_core::id!(lh_two)),
2353 foot(day_core::id!(lh_two_end)),
2354 ))
2355 .spacing(0.0),
2356 column((
2357 line("Ag\nAg").line_height(1.5),
2358 foot(day_core::id!(lh_three_end)),
2359 ))
2360 .spacing(0.0),
2361 ))
2362 .spacing(8.0)
2363 .align(VAlign::Top),
2364 button("Tighter")
2365 .action(move || multiple.set(1.5))
2366 .id(day_core::id!(lh_tighter)),
2367 ))
2368 .align(HAlign::Leading)
2369 .spacing(8.0)
2370 })
2371 .shot("default")
2372 .drive(|d: Drive| async move {
2373 let level_with = |reference: &str| FrameExpect {
2374 y: Some(0.0),
2375 relative_to: Some(reference.into()),
2376 tolerance: Some(2.0),
2377 ..Default::default()
2378 };
2379 d.assert_frame("lh_pair_end", level_with("lh_four_end"))
2380 .await?;
2381 d.assert_frame("lh_two_end", level_with("lh_four_end"))
2382 .await?;
2383 d.tap("lh_tighter").await?;
2384 d.wait_idle().await?;
2385 d.assert_frame("lh_pair_end", level_with("lh_three_end"))
2386 .await
2387 })
2388 }
2389
2390 #[day_macros::test(day_core)]
2405 fn label_letter_spacing() -> Case {
2406 let at = |text: &'static str, points: f64| label(text).font(Font::System(points));
2407 let level = |reference: &str, tolerance: f64| FrameExpect {
2408 x: Some(0.0),
2409 relative_to: Some(reference.into()),
2410 tolerance: Some(tolerance),
2411 ..Default::default()
2412 };
2413 Case::new()
2414 .proves(kinds::LABEL)
2415 .page(move || {
2416 column((
2417 row((
2418 at("HHH", 40.0).letter_spacing(0.75),
2419 at("HHH", 20.0),
2420 foot(day_core::id!(ls_large_end)),
2421 )),
2422 row((
2423 at("HHH", 40.0),
2424 at("HHH", 20.0).letter_spacing(1.5),
2425 foot(day_core::id!(ls_small_end)),
2426 )),
2427 row((
2428 at("HHHHHHHH", 20.0)
2429 .letter_spacing(0.25)
2430 .id(day_core::id!(ls_spaced)),
2431 at("HH", 20.0),
2432 foot(day_core::id!(ls_spaced_end)),
2433 )),
2434 row((
2435 at("HHHH", 20.0).letter_spacing(0.25),
2436 at("HH\u{2003}HHHH", 20.0),
2437 foot(day_core::id!(ls_plain_end)),
2438 )),
2439 ))
2440 .align(HAlign::Leading)
2441 .spacing(8.0)
2442 })
2443 .shot("default")
2444 .drive(move |d: Drive| async move {
2445 d.assert_frame("ls_large_end", level("ls_small_end", 1.0))
2446 .await?;
2447 d.assert_frame("ls_spaced_end", level("ls_plain_end", 1.5))
2448 .await?;
2449 d.assert_text("ls_spaced", "HHHHHHHH").await
2450 })
2451 }
2452
2453 #[day_macros::test(day_core)]
2457 fn label_decorations_and_features() -> Case {
2458 Case::new()
2459 .proves(kinds::LABEL)
2460 .requires(Cap::TextRuns)
2461 .page(|| {
2462 column((
2463 label("")
2464 .runs_from(
2465 TextBuilder::new()
2466 .text("Check ")
2467 .underline_styled(
2468 "unknown",
2469 day_spec::Decoration::wavy()
2470 .color(day_spec::Color::hex(0x00D0_021B)),
2471 )
2472 .text(" and ")
2473 .strikethrough_styled("old", day_spec::DecorationStyle::Double)
2474 .text(" in ")
2475 .small_caps("Small Caps"),
2476 )
2477 .id(day_core::id!(dec_runs)),
2478 label("Doubly underlined")
2479 .underline(day_spec::Decoration::double())
2480 .id(day_core::id!(dec_whole)),
2481 label("Struck in red")
2482 .strikethrough(
2483 day_spec::Decoration::SINGLE.color(day_spec::Color::hex(0x00D0_021B)),
2484 )
2485 .id(day_core::id!(dec_struck)),
2486 label("Chapter 1234567890")
2487 .small_caps()
2488 .oldstyle_figures()
2489 .id(day_core::id!(dec_features)),
2490 ))
2491 .align(HAlign::Leading)
2492 .spacing(8.0)
2493 })
2494 .shot("default")
2495 .drive(|d: Drive| async move {
2496 d.assert_text("dec_runs", "Check unknown and old in Small Caps")
2497 .await?;
2498 d.assert_text("dec_whole", "Doubly underlined").await?;
2499 d.assert_text("dec_struck", "Struck in red").await?;
2500 d.assert_text("dec_features", "Chapter 1234567890").await
2501 })
2502 }
2503
2504 #[day_macros::test(day_core)]
2508 fn label_on_selection() -> Case {
2509 let chosen = Signal::new(String::new());
2510 Case::new()
2511 .proves(kinds::LABEL)
2512 .proves_duty("set_selectable")
2513 .page(move || {
2514 column((
2515 label("Select part of this sentence")
2516 .on_selection(move |s| chosen.set(s.text.clone()))
2517 .id(day_core::id!(sel_text)),
2518 label(move || chosen.get()).id(day_core::id!(sel_echo)),
2519 ))
2520 .align(HAlign::Leading)
2521 .spacing(8.0)
2522 })
2523 .drive(|d: Drive| async move {
2524 d.assert_text("sel_text", "Select part of this sentence")
2525 .await?;
2526 d.assert_text("sel_echo", "").await
2527 })
2528 }
2529
2530 #[day_macros::test(day_core)]
2532 fn text_scale_reads() -> Case {
2533 Case::new()
2534 .proves_duty("text_scale")
2535 .page(|| {
2536 label(|| format!("{:.2}", day_core::text_scale()))
2537 .max_text_scale(1.0)
2538 .id(day_core::id!(ts_scale))
2539 })
2540 .drive(|d: Drive| async move {
2541 let scale = day_core::text_scale();
2542 d.check(
2543 scale.is_finite() && scale > 0.0,
2544 "the text scale is positive",
2545 )?;
2546 d.check_eq(scale, day_core::text_scale_of(Font::Body))?;
2547 d.assert_text("ts_scale", &format!("{scale:.2}")).await
2548 })
2549 }
2550
2551 #[day_macros::test(day_core)]
2554 fn link_takes_label_builders() -> Case {
2555 let title = Signal::new("Read the guide".to_owned());
2556 let handled = Signal::new(String::new());
2557 Case::new()
2558 .proves_duty("open_url")
2559 .page(move || {
2560 column((
2561 link(title, "https://daybrite.dev/docs")
2562 .font(Font::Footnote)
2563 .bold()
2564 .single_line()
2565 .truncation(Truncation::Middle)
2566 .id(day_core::id!(lk_default)),
2567 link("Handled here", "app:custom")
2568 .on_link(move |target| handled.set(target.to_owned()))
2569 .id(day_core::id!(lk_handled)),
2570 label(move || handled.get()).id(day_core::id!(lk_echo)),
2571 button("Retitle")
2572 .action(move || title.set("Open the guide".into()))
2573 .id(day_core::id!(lk_retitle)),
2574 ))
2575 .align(HAlign::Leading)
2576 .spacing(8.0)
2577 })
2578 .drive(|d: Drive| async move {
2579 d.assert_text("lk_default", "Read the guide").await?;
2580 d.tap("lk_retitle").await?;
2581 d.assert_text("lk_default", "Open the guide").await?;
2582 d.tap("lk_default").await?;
2583 d.assert_opened_url("https://daybrite.dev/docs").await?;
2584 d.tap("lk_handled").await?;
2585 d.assert_text("lk_echo", "app:custom").await
2586 })
2587 }
2588
2589 #[day_macros::test(day_core)]
2592 fn label_selectable() -> Case {
2593 Case::new()
2594 .proves(kinds::LABEL)
2595 .proves_modifier("selectable")
2596 .proves_duty("set_selectable")
2597 .page(|| label("Copy me").selectable().id(day_core::id!(text)))
2598 .drive(|d: Drive| async move { d.assert_text("text", "Copy me").await })
2599 }
2600
2601 #[day_macros::test(day_core)]
2603 fn button_title() -> Case {
2604 let saved = Signal::new(false);
2605 Case::new()
2606 .proves(kinds::BUTTON)
2607 .page(move || {
2608 button(move || if saved.get() { "Saved" } else { "Save" }.to_owned())
2609 .action(move || saved.set(true))
2610 .id(day_core::id!(save))
2611 })
2612 .drive(|d: Drive| async move {
2613 d.assert_text("save", "Save").await?;
2614 d.tap("save").await?;
2615 d.assert_text("save", "Saved").await
2616 })
2617 }
2618
2619 #[day_macros::test(day_core)]
2621 fn button_a11y() -> Case {
2622 Case::new()
2623 .proves(kinds::BUTTON)
2624 .proves_modifier("a11y")
2625 .page(|| {
2626 button("Send")
2627 .a11y(|a| a.label("Send the message"))
2628 .id(day_core::id!(send))
2629 })
2630 .drive(|d: Drive| async move { d.a11y_audit(Some("send")).await })
2631 }
2632
2633 #[day_macros::test(day_core)]
2636 fn button_a11y_survives_title_change() -> Case {
2637 let playing = Signal::new(false);
2638 Case::new()
2639 .proves(kinds::BUTTON)
2640 .proves_modifier("a11y")
2641 .page(move || {
2642 button(move || if playing.get() { "Pause" } else { "Play" }.to_owned())
2643 .icon(day_spec::Symbol::Play)
2644 .action(move || playing.set(true))
2645 .a11y(|a| a.label("Playback"))
2646 .id(day_core::id!(play))
2647 })
2648 .drive(|d: Drive| async move {
2649 d.a11y_audit(Some("play")).await?;
2650 d.tap("play").await?;
2651 d.assert_text("play", "Pause").await?;
2652 d.a11y_audit(Some("play")).await
2653 })
2654 }
2655
2656 #[day_macros::test(day_core)]
2658 fn toggle_disabled() -> Case {
2659 let on = Signal::new(false);
2660 let enabled = Signal::new(false);
2661 Case::new()
2662 .proves(kinds::TOGGLE)
2663 .page(move || {
2664 column((
2665 toggle(on)
2666 .enabled(move || enabled.get())
2667 .id(day_core::id!(switch)),
2668 button("Enable")
2669 .action(move || enabled.set(true))
2670 .id(day_core::id!(enable)),
2671 ))
2672 .spacing(8.0)
2673 })
2674 .drive(|d: Drive| async move {
2675 d.assert_enabled("switch", false).await?;
2676 d.tap("enable").await?;
2677 d.assert_enabled("switch", true).await?;
2678 d.toggle("switch", true).await?;
2679 d.assert_on("switch", true).await
2680 })
2681 }
2682
2683 #[day_macros::test(day_core)]
2685 fn toggle_disabled_constant() -> Case {
2686 let on = Signal::new(true);
2687 Case::new()
2688 .proves(kinds::TOGGLE)
2689 .page(move || toggle(on).enabled(false).id(day_core::id!(switch)))
2690 .drive(|d: Drive| async move {
2691 d.assert_enabled("switch", false).await?;
2692 d.assert_on("switch", true).await
2693 })
2694 }
2695
2696 #[day_macros::test(day_core)]
2698 fn toggle_a11y() -> Case {
2699 let on = Signal::new(false);
2700 Case::new()
2701 .proves(kinds::TOGGLE)
2702 .page(move || {
2703 toggle(on)
2704 .a11y(|a| a.label("Notifications"))
2705 .id(day_core::id!(switch))
2706 })
2707 .drive(|d: Drive| async move { d.a11y_audit(Some("switch")).await })
2708 }
2709
2710 #[day_macros::test(day_core)]
2712 fn slider_disabled() -> Case {
2713 let value = Signal::new(0.5f64);
2714 let enabled = Signal::new(false);
2715 Case::new()
2716 .proves(kinds::SLIDER)
2717 .page(move || {
2718 column((
2719 slider(value)
2720 .enabled(move || enabled.get())
2721 .id(day_core::id!(slider)),
2722 button("Enable")
2723 .action(move || enabled.set(true))
2724 .id(day_core::id!(enable)),
2725 ))
2726 .spacing(8.0)
2727 })
2728 .drive(|d: Drive| async move {
2729 d.assert_enabled("slider", false).await?;
2730 d.tap("enable").await?;
2731 d.assert_enabled("slider", true).await?;
2732 d.set_value("slider", 0.25).await?;
2733 d.assert_value("slider", 0.25).await
2734 })
2735 }
2736
2737 #[day_macros::test(day_core)]
2739 fn slider_follows_signal() -> Case {
2740 let value = Signal::new(10.0f64);
2741 Case::new()
2742 .proves(kinds::SLIDER)
2743 .page(move || {
2744 column((
2745 slider(value).range(0.0..=50.0).id(day_core::id!(slider)),
2746 button("Set 40")
2747 .action(move || value.set(40.0))
2748 .id(day_core::id!(set)),
2749 ))
2750 .spacing(8.0)
2751 })
2752 .drive(|d: Drive| async move {
2753 d.assert_value("slider", 10.0).await?;
2754 d.tap("set").await?;
2755 d.assert_value("slider", 40.0).await
2756 })
2757 }
2758
2759 #[day_macros::test(day_core)]
2763 fn slider_set_by_the_app_is_not_echoed() -> Case {
2764 #[derive(Clone, Copy)]
2766 struct Counted {
2767 value: Signal<f64>,
2768 writes: Signal<u32>,
2769 }
2770 impl Binding<f64> for Counted {
2771 fn read(&self) -> f64 {
2772 self.value.get()
2773 }
2774 fn peek(&self) -> f64 {
2775 self.value.get_untracked()
2776 }
2777 fn write(&self, v: f64) {
2778 self.writes.update(|n| *n += 1);
2779 self.value.set(v);
2780 }
2781 }
2782 let value = Signal::new(10.0f64);
2783 let writes = Signal::new(0u32);
2784 Case::new()
2785 .proves(kinds::SLIDER)
2786 .page(move || {
2787 column((
2788 slider(Counted { value, writes })
2789 .range(0.0..=50.0)
2790 .id(day_core::id!(slider)),
2791 button("Step")
2792 .action(move || value.update(|v| *v += 7.5))
2793 .id(day_core::id!(step)),
2794 label(move || format!("writes {}", writes.get())).id(day_core::id!(writes)),
2795 ))
2796 .spacing(8.0)
2797 })
2798 .drive(|d: Drive| async move {
2799 d.assert_value("slider", 10.0).await?;
2800 for _ in 0..3 {
2801 d.tap("step").await?;
2802 }
2803 d.assert_value("slider", 32.5).await?;
2804 d.wait_idle().await?;
2805 d.pause(0.3).await?;
2806 d.assert_text("writes", "writes 0").await
2807 })
2808 }
2809
2810 #[day_macros::test(day_core)]
2812 fn slider_a11y() -> Case {
2813 let value = Signal::new(0.5f64);
2814 Case::new()
2815 .proves(kinds::SLIDER)
2816 .page(move || {
2817 slider(value)
2818 .a11y(|a| a.label("Volume"))
2819 .id(day_core::id!(slider))
2820 })
2821 .drive(|d: Drive| async move { d.a11y_audit(Some("slider")).await })
2822 }
2823
2824 #[day_macros::test(day_core)]
2826 fn text_field_disabled() -> Case {
2827 let text = Signal::new("Fixed".to_owned());
2828 let enabled = Signal::new(false);
2829 Case::new()
2830 .proves(kinds::TEXT_FIELD)
2831 .page(move || {
2832 column((
2833 text_field(text)
2834 .enabled(move || enabled.get())
2835 .id(day_core::id!(field)),
2836 button("Enable")
2837 .action(move || enabled.set(true))
2838 .id(day_core::id!(enable)),
2839 ))
2840 .spacing(8.0)
2841 })
2842 .drive(|d: Drive| async move {
2843 d.assert_enabled("field", false).await?;
2844 d.assert_text("field", "Fixed").await?;
2845 d.tap("enable").await?;
2846 d.assert_enabled("field", true).await?;
2847 d.input("field", "Changed").await?;
2848 d.assert_text("field", "Changed").await
2849 })
2850 }
2851
2852 #[day_macros::test(day_core)]
2854 fn text_field_read_only() -> Case {
2855 let text = Signal::new("Shown".to_owned());
2856 Case::new()
2857 .proves(kinds::TEXT_FIELD)
2858 .proves_duty("set_input_traits")
2859 .page(move || {
2860 column((
2861 text_field(text).read_only(true).id(day_core::id!(field)),
2862 button("Replace")
2863 .action(move || text.set("Replaced".into()))
2864 .id(day_core::id!(replace)),
2865 ))
2866 .spacing(8.0)
2867 })
2868 .drive(|d: Drive| async move {
2869 d.assert_text("field", "Shown").await?;
2870 d.assert_enabled("field", true).await?;
2871 d.tap("replace").await?;
2872 d.assert_text("field", "Replaced").await
2873 })
2874 }
2875
2876 #[day_macros::test(day_core)]
2878 fn text_field_submit() -> Case {
2879 let text = Signal::new(String::new());
2880 let sent = Signal::new(String::new());
2881 Case::new()
2882 .proves(kinds::TEXT_FIELD)
2883 .page(move || {
2884 column((
2885 text_field(text)
2886 .submit_label(day_spec::SubmitLabel::Send)
2887 .on_submit(move || sent.set(text.get_untracked()))
2888 .id(day_core::id!(field)),
2889 label(move || sent.get()).id(day_core::id!(sent)),
2890 ))
2891 .spacing(8.0)
2892 })
2893 .drive(|d: Drive| async move {
2894 d.input("field", "hello").await?;
2895 d.submit("field").await?;
2896 d.assert_text("sent", "hello").await
2897 })
2898 }
2899
2900 #[day_macros::test(day_core)]
2902 fn progress_value() -> Case {
2903 let done = Signal::new(0.25f64);
2904 Case::new()
2905 .proves(kinds::PROGRESS)
2906 .page(move || {
2907 column((
2908 progress(done).id(day_core::id!(bar)),
2909 button("Advance")
2910 .action(move || done.set(0.75))
2911 .id(day_core::id!(advance)),
2912 ))
2913 .spacing(8.0)
2914 })
2915 .drive(|d: Drive| async move {
2916 d.assert_value("bar", 0.25).await?;
2917 d.tap("advance").await?;
2918 d.assert_value("bar", 0.75).await
2919 })
2920 }
2921
2922 #[day_macros::test(day_core)]
2924 fn spinner_renders() -> Case {
2925 Case::new()
2926 .proves(kinds::PROGRESS)
2927 .page(|| spinner().id(day_core::id!(spin)))
2928 .drive(|d: Drive| async move {
2929 d.assert_visible("spin").await?;
2930 d.assert_native(
2931 "spin",
2932 NativeExpect {
2933 visible: Some(true),
2934 ..Default::default()
2935 },
2936 )
2937 .await
2938 })
2939 }
2940
2941 #[day_macros::test(day_core)]
2943 fn spinner_size_and_animation() -> Case {
2944 Case::new()
2945 .proves(kinds::PROGRESS)
2946 .page(|| {
2947 let running = Signal::new(true);
2948 column((
2949 spinner()
2950 .animating(running)
2951 .id(day_core::id!(spinner_fixture::small)),
2952 spinner()
2953 .animating(running)
2954 .large()
2955 .id(day_core::id!(spinner_fixture::large)),
2956 button("Stop fixture")
2957 .action(move || running.set(false))
2958 .id(day_core::id!(spinner_fixture::stop)),
2959 ))
2960 })
2961 .drive(|d: Drive| async move {
2962 let sizes = match day_core::toolkit_key() {
2963 Some("appkit") => Some((20.0, 32.0)),
2964 Some("uikit") => Some((20.0, 37.0)),
2965 Some("gtk") => Some((24.0, 48.0)),
2966 Some("arkui") => Some((32.0, 64.0)),
2967 Some("xaml" | "winui") => Some((32.0, 48.0)),
2968 Some("dom") => Some((22.0, 48.0)),
2969 _ => None, };
2971 for stopped in [false, true] {
2972 if stopped {
2973 d.tap("spinner_fixture::stop").await?;
2974 }
2975 d.assert_visible("spinner_fixture::small").await?;
2976 d.assert_visible("spinner_fixture::large").await?;
2977 if let Some((small, large)) = sizes {
2978 d.assert_size("spinner_fixture::small", small, small)
2979 .await?;
2980 d.assert_size("spinner_fixture::large", large, large)
2981 .await?;
2982 }
2983 }
2984 Ok(())
2985 })
2986 }
2987
2988 #[day_macros::test(day_core)]
2990 fn divider_renders() -> Case {
2991 Case::new()
2992 .proves(kinds::DIVIDER)
2993 .page(|| {
2994 column((
2995 label("Above"),
2996 divider().id(day_core::id!(rule)),
2997 label("Below"),
2998 ))
2999 .spacing(8.0)
3000 .width(200.0)
3001 })
3002 .drive(|d: Drive| async move {
3003 d.assert_visible("rule").await?;
3004 d.assert_frame(
3005 "rule",
3006 FrameExpect {
3007 width: Some(200.0),
3008 ..Default::default()
3009 },
3010 )
3011 .await
3012 })
3013 }
3014
3015 #[day_macros::test(day_core)]
3018 fn vertical_divider_fills_height() -> Case {
3019 Case::new()
3020 .proves(kinds::DIVIDER)
3021 .page(|| {
3022 row((
3023 label("Left"),
3024 divider().vertical().id(day_core::id!(rule)),
3025 label("Right"),
3026 ))
3027 .spacing(8.0)
3028 .height(120.0)
3029 .id(day_core::id!(row))
3030 })
3031 .drive(|d: Drive| async move {
3032 d.assert_visible("rule").await?;
3033 d.assert_frame(
3035 "rule",
3036 FrameExpect {
3037 height: Some(120.0),
3038 ..Default::default()
3039 },
3040 )
3041 .await
3042 })
3043 }
3044
3045 #[day_macros::test(day_core)]
3047 fn spacer_fills() -> Case {
3048 Case::new()
3049 .proves_modifier("width")
3050 .page(|| {
3051 row((
3052 label("A").width(50.0).wrapper_id(day_core::id!(first)),
3054 spacer(),
3055 label("B").width(50.0).wrapper_id(day_core::id!(last)),
3056 ))
3057 .width(300.0)
3058 .wrapper_id(day_core::id!(row))
3059 })
3060 .drive(|d: Drive| async move {
3061 d.assert_frame(
3062 "last",
3063 FrameExpect {
3064 width: Some(50.0),
3065 x: Some(250.0),
3066 relative_to: Some("row".into()),
3067 ..Default::default()
3068 },
3069 )
3070 .await
3071 })
3072 }
3073
3074 #[day_macros::test(day_core)]
3076 fn link_opens_url() -> Case {
3077 Case::new()
3078 .proves_duty("open_url")
3079 .page(|| link("daybrite.dev", "https://daybrite.dev/").id(day_core::id!(link)))
3080 .drive(|d: Drive| async move {
3081 d.assert_text("link", "daybrite.dev").await?;
3082 d.tap("link").await?;
3083 d.assert_opened_url("https://daybrite.dev/").await
3084 })
3085 }
3086}
3087
3088#[cfg(test)]
3089mod button_style_tests {
3090 use super::*;
3091 use day_spec::props::ButtonStyleSpec;
3092
3093 #[test]
3094 fn compact_keeps_a_plain_button_plain() {
3095 assert_eq!(
3096 button("×").plain().compact().native_style,
3097 ButtonStyleSpec::Plain
3098 );
3099 assert_eq!(button("−").compact().native_style, ButtonStyleSpec::Compact);
3100 assert_eq!(
3102 button("+").compact().plain().native_style,
3103 ButtonStyleSpec::Plain
3104 );
3105 }
3106}