1use std::cell::RefCell;
8use std::rc::Rc;
9
10use day_core::*;
11use day_reactive::{bind, bind_seeded};
12use day_spec::{Event, kinds};
13
14use crate::*;
15
16pub enum PickerOptions<T: 'static> {
22 Fixed(Vec<(T, TextSource)>),
23 Derived(Rc<dyn Fn() -> Vec<(T, TextSource)>>),
24}
25
26impl<T: Clone + 'static> PickerOptions<T> {
27 fn resolve(&self) -> (Vec<T>, Vec<String>) {
30 let pairs = match self {
31 PickerOptions::Fixed(v) => v.clone(),
32 PickerOptions::Derived(f) => f(),
33 };
34 let mut values = Vec::with_capacity(pairs.len());
35 let mut titles = Vec::with_capacity(pairs.len());
36 for (v, t) in pairs {
37 values.push(v);
38 titles.push(t.resolve());
39 }
40 (values, titles)
41 }
42}
43
44pub trait IntoPickerOptions<T: 'static, M> {
49 fn into_picker_options(self) -> PickerOptions<T>;
50}
51
52pub struct FixedOptionsMark;
54pub struct DerivedOptionsMark;
56
57impl<T: 'static, X: IntoText<M>, M, const N: usize> IntoPickerOptions<T, (FixedOptionsMark, M)>
58 for [(T, X); N]
59{
60 fn into_picker_options(self) -> PickerOptions<T> {
61 PickerOptions::Fixed(self.into_iter().map(|(v, t)| (v, t.into_text())).collect())
62 }
63}
64
65impl<T: 'static, X: IntoText<M>, M> IntoPickerOptions<T, (FixedOptionsMark, M)> for Vec<(T, X)> {
66 fn into_picker_options(self) -> PickerOptions<T> {
67 PickerOptions::Fixed(self.into_iter().map(|(v, t)| (v, t.into_text())).collect())
68 }
69}
70
71impl<T: 'static, X: IntoText<M>, M, F> IntoPickerOptions<T, (DerivedOptionsMark, M)> for F
72where
73 F: Fn() -> Vec<(T, X)> + 'static,
74{
75 fn into_picker_options(self) -> PickerOptions<T> {
76 PickerOptions::Derived(Rc::new(move || {
77 self()
78 .into_iter()
79 .map(|(v, t)| (v, t.into_text()))
80 .collect()
81 }))
82 }
83}
84
85pub trait PickerSelection<T: 'static>: Clone + 'static {
88 fn current(&self) -> Option<T>;
90 fn choose(&self, value: T);
92}
93
94#[derive(Clone)]
96pub struct Required<Sel>(Sel);
97
98impl<T: 'static, Sel: Binding<T>> PickerSelection<T> for Required<Sel> {
99 fn current(&self) -> Option<T> {
100 Some(self.0.read())
101 }
102 fn choose(&self, value: T) {
103 self.0.write(value);
104 }
105}
106
107#[derive(Clone)]
109pub struct Optional<Sel>(Sel);
110
111impl<T: 'static, Sel: Binding<Option<T>>> PickerSelection<T> for Optional<Sel> {
112 fn current(&self) -> Option<T> {
113 self.0.read()
114 }
115 fn choose(&self, value: T) {
116 self.0.write(Some(value));
117 }
118}
119
120#[must_use]
123pub struct Picker<T: Clone + PartialEq + 'static, S: PickerSelection<T>> {
124 options: PickerOptions<T>,
125 separators_before: Vec<usize>,
126 selected: S,
127 style: day_spec::props::PickerStyle,
128 enabled: Reactive<bool>,
129}
130
131pub fn picker<T, Sel, M>(
143 selected: Sel,
144 options: impl IntoPickerOptions<T, M>,
145) -> Picker<T, Required<Sel>>
146where
147 T: Clone + PartialEq + 'static,
148 Sel: Binding<T>,
149{
150 Picker {
151 options: options.into_picker_options(),
152 separators_before: Vec::new(),
153 selected: Required(selected),
154 style: day_spec::props::PickerStyle::Menu,
155 enabled: Reactive::Const(true),
156 }
157}
158
159pub fn picker_optional<T, Sel, M>(
162 selected: Sel,
163 options: impl IntoPickerOptions<T, M>,
164) -> Picker<T, Optional<Sel>>
165where
166 T: Clone + PartialEq + 'static,
167 Sel: Binding<Option<T>>,
168{
169 Picker {
170 options: options.into_picker_options(),
171 separators_before: Vec::new(),
172 selected: Optional(selected),
173 style: day_spec::props::PickerStyle::Menu,
174 enabled: Reactive::Const(true),
175 }
176}
177
178#[day_macros::builder(PickerBuilder)]
179impl<T: Clone + PartialEq + 'static, S: PickerSelection<T>> Picker<T, S> {
180 pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
182 self.enabled = v.into_reactive();
183 self
184 }
185 pub fn separators_before(mut self, indexes: impl IntoIterator<Item = usize>) -> Self {
189 self.separators_before = indexes.into_iter().collect();
190 self.separators_before.sort_unstable();
191 self.separators_before.dedup();
192 self
193 }
194 pub fn menu(mut self) -> Self {
195 self.style = day_spec::props::PickerStyle::Menu;
196 self
197 }
198 pub fn segmented(mut self) -> Self {
199 self.style = day_spec::props::PickerStyle::Segmented;
200 self
201 }
202 pub fn inline(mut self) -> Self {
203 self.style = day_spec::props::PickerStyle::Inline;
204 self
205 }
206 pub fn style(mut self, style: day_spec::props::PickerStyle) -> Self {
207 self.style = style;
208 self
209 }
210}
211
212impl<T: Clone + PartialEq + 'static, S: PickerSelection<T>> Piece for Picker<T, S> {
213 fn build(self, cx: &mut BuildCx) -> RNode {
214 let Picker {
215 options,
216 separators_before,
217 selected,
218 style,
219 enabled,
220 } = self;
221 let (values0, titles0) = day_reactive::untrack(|| options.resolve());
222 debug_assert!(
223 values0
224 .iter()
225 .enumerate()
226 .all(|(i, v)| !values0[..i].contains(v)),
227 "day: a picker's option values must be distinct"
228 );
229 let values: Rc<RefCell<Vec<T>>> = Rc::new(RefCell::new(values0));
231 let index_of = {
232 let values = values.clone();
233 move |v: Option<T>| -> Option<usize> {
234 let v = v?;
235 values.borrow().iter().position(|x| *x == v)
236 }
237 };
238 let initial_index = index_of(day_reactive::untrack(|| selected.current())).unwrap_or(0);
239 let enabled_now = enabled.get_untracked() && !titles0.is_empty();
240 let initial = day_spec::props::PickerProps {
241 options: titles0,
242 separators_before,
243 selected: initial_index,
244 style,
245 enabled: enabled_now,
246 };
247 let node = cx.leaf(kinds::PICKER, &initial, Flex::default());
248 let patch = move |p: day_spec::props::PickerPatch, affects_size: bool| {
249 with_tree(|t| t.patch(node, Box::new(p), affects_size));
250 };
251 {
253 let enabled = enabled.clone();
254 let values = values.clone();
255 bind_seeded(
256 enabled_now,
257 move || enabled.get() && !values.borrow().is_empty(),
258 move |e: &bool| patch(day_spec::props::PickerPatch::Enabled(*e), false),
259 );
260 }
261 let affects_size = matches!(initial.style, day_spec::props::PickerStyle::Menu);
266 {
271 let (values, sel) = (values.clone(), selected.clone());
272 let index_of = index_of.clone();
273 bind_seeded(
274 initial.options.clone(),
275 move || {
276 let (vs, titles) = options.resolve();
277 *values.borrow_mut() = vs;
278 titles
279 },
280 move |titles: &Vec<String>| {
281 patch(day_spec::props::PickerPatch::Options(titles.clone()), true);
282 if let Some(i) = index_of(day_reactive::untrack(|| sel.current())) {
283 patch(day_spec::props::PickerPatch::Selected(i), affects_size);
284 }
285 },
286 );
287 }
288 {
291 let sel = selected.clone();
292 let index_of = index_of.clone();
293 bind_seeded(
294 Some(initial.selected),
295 move || index_of(sel.current()),
296 move |i: &Option<usize>| {
297 if let Some(i) = i {
298 patch(day_spec::props::PickerPatch::Selected(*i), affects_size);
299 }
300 },
301 );
302 }
303 cx.on(node, move |ev| {
306 if let Event::SelectionChanged(i) = ev
307 && *i >= 0
308 && let Some(v) = values.borrow().get(*i as usize).cloned()
309 {
310 selected.choose(v);
311 }
312 });
313 node
314 }
315}
316
317#[must_use]
327pub struct TextArea<S: Binding<String>> {
328 text: S,
329 placeholder: Option<TextSource>,
330 min_lines: u32,
331 max_lines: u32,
332 editable: Reactive<bool>,
333 selectable: Reactive<bool>,
334 spellcheck: Reactive<bool>,
335 on_submit: Option<Rc<dyn Fn()>>,
336}
337
338pub fn text_area<S: Binding<String>>(text: S) -> TextArea<S> {
341 TextArea {
342 text,
343 placeholder: None,
344 min_lines: 1,
345 max_lines: 0,
346 editable: true.into_reactive(),
347 selectable: true.into_reactive(),
348 spellcheck: true.into_reactive(),
349 on_submit: None,
350 }
351}
352
353#[day_macros::builder(TextAreaBuilder)]
354impl<S: Binding<String>> TextArea<S> {
355 pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
358 self.placeholder = Some(t.into_text());
359 self
360 }
361
362 pub fn min_lines(mut self, lines: u32) -> Self {
364 self.min_lines = lines.max(1);
365 self
366 }
367
368 pub fn max_lines(mut self, lines: u32) -> Self {
371 self.max_lines = lines;
372 self
373 }
374
375 pub fn editable<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
377 self.editable = v.into_reactive();
378 self
379 }
380
381 pub fn selectable<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
384 self.selectable = v.into_reactive();
385 self
386 }
387
388 pub fn spellcheck<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
391 self.spellcheck = v.into_reactive();
392 self
393 }
394
395 pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
401 self.on_submit = Some(Rc::new(f));
402 self
403 }
404}
405
406impl<S: Binding<String>> Piece for TextArea<S> {
407 fn build(self, cx: &mut BuildCx) -> RNode {
408 let TextArea {
409 text,
410 placeholder,
411 min_lines,
412 max_lines,
413 editable,
414 selectable,
415 spellcheck,
416 on_submit,
417 } = self;
418 let initial = text.peek();
419 let ph = placeholder.map_or_default(|p| p.initial());
420 let node = cx.leaf(
421 kinds::TEXT_AREA,
422 &day_spec::props::TextAreaProps {
423 text: initial.clone(),
424 placeholder: ph,
425 min_lines,
426 max_lines: if max_lines == 0 {
429 0
430 } else {
431 max_lines.max(min_lines)
432 },
433 editable: editable.get_untracked(),
434 selectable: selectable.get_untracked(),
435 spellcheck: spellcheck.get_untracked(),
436 submit_on_enter: on_submit.is_some(),
437 },
438 Flex {
441 grow_w: true,
442 ..Default::default()
443 },
444 );
445 if let Reactive::Dyn(_) = &editable {
448 bind(
449 move || editable.get(),
450 move |v: &bool| {
451 with_tree(|t| {
452 t.patch(
453 node,
454 Box::new(day_spec::props::TextAreaPatch::SetEditable(*v)),
455 false,
456 );
457 });
458 },
459 );
460 }
461 if let Reactive::Dyn(_) = &selectable {
462 bind(
463 move || selectable.get(),
464 move |v: &bool| {
465 with_tree(|t| {
466 t.patch(
467 node,
468 Box::new(day_spec::props::TextAreaPatch::SetSelectable(*v)),
469 false,
470 );
471 });
472 },
473 );
474 }
475 if let Reactive::Dyn(_) = &spellcheck {
476 bind(
477 move || spellcheck.get(),
478 move |v: &bool| {
479 with_tree(|t| {
480 t.patch(
481 node,
482 Box::new(day_spec::props::TextAreaPatch::SetSpellCheck(*v)),
483 false,
484 );
485 });
486 },
487 );
488 }
489 let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
492 let g = guard.clone();
493 let tx = text.clone();
494 bind_seeded(
495 initial,
496 move || tx.read(),
497 move |t: &String| {
498 let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
499 if !from_native {
500 with_tree(|tr| {
501 tr.patch(
502 node,
503 Box::new(day_spec::props::TextAreaPatch::SetText(t.clone())),
504 true,
505 );
506 });
507 }
508 },
509 );
510 cx.on(node, move |ev| match ev {
511 Event::TextChanged(t) => {
512 with_tree(|tree| tree.set_probe_value(node, 0.0, t.clone()));
515 *guard.borrow_mut() = Some(t.clone());
516 text.write(t.clone());
517 }
518 Event::Submitted => {
519 if let Some(f) = &on_submit {
520 f();
521 }
522 }
523 _ => {}
524 });
525 node
526 }
527}
528
529#[cfg(feature = "conformance")]
537pub(crate) mod conformance {
538 use day_core::conformance::{Case, Drive};
539 use day_reactive::Signal;
540 use day_spec::{Cap, kinds};
541
542 use crate::*;
543
544 const FRUIT: [(usize, &str); 3] = [(0, "Apple"), (1, "Pear"), (2, "Plum")];
545
546 #[day_macros::test(day_core)]
548 fn picker_select() -> Case {
549 let choice = Signal::new(0usize);
550 Case::new()
551 .proves(kinds::PICKER)
552 .page(move || {
553 column((
554 picker(choice, FRUIT).id(day_core::id!(picker)),
555 label(move || choice.get().to_string()).id(day_core::id!(index)),
556 ))
557 .spacing(8.0)
558 })
559 .shot("default")
560 .drive(|d: Drive| async move {
561 d.assert_text("picker", "Apple").await?;
562 d.select("picker", 2).await?;
563 d.assert_text("index", "2").await?;
564 d.assert_text("picker", "Plum").await
565 })
566 }
567
568 #[day_macros::test(day_core)]
570 fn picker_segmented() -> Case {
571 let choice = Signal::new(1usize);
572 Case::new()
573 .proves(kinds::PICKER)
574 .page(move || {
575 column((
576 picker(choice, FRUIT).segmented().id(day_core::id!(picker)),
577 label(move || choice.get().to_string()).id(day_core::id!(index)),
578 ))
579 .spacing(8.0)
580 })
581 .shot("default")
582 .drive(|d: Drive| async move {
583 d.assert_text("picker", "Pear").await?;
584 d.select("picker", 0).await?;
585 d.assert_text("index", "0").await?;
586 d.assert_text("picker", "Apple").await
587 })
588 }
589
590 #[day_macros::test(day_core)]
592 fn picker_inline() -> Case {
593 let choice = Signal::new(0usize);
594 Case::new()
595 .proves(kinds::PICKER)
596 .page(move || {
597 column((
598 picker(choice, FRUIT).inline().id(day_core::id!(picker)),
599 label(move || choice.get().to_string()).id(day_core::id!(index)),
600 ))
601 .spacing(8.0)
602 })
603 .drive(|d: Drive| async move {
604 d.select("picker", 1).await?;
605 d.assert_text("index", "1").await?;
606 d.assert_text("picker", "Pear").await
607 })
608 }
609
610 #[day_macros::test(day_core)]
612 fn picker_follows_signal() -> Case {
613 let choice = Signal::new(0usize);
614 Case::new()
615 .proves(kinds::PICKER)
616 .page(move || {
617 column((
618 picker(choice, FRUIT).id(day_core::id!(picker)),
619 button("Plum")
620 .action(move || choice.set(2))
621 .id(day_core::id!(set)),
622 ))
623 .spacing(8.0)
624 })
625 .drive(|d: Drive| async move {
626 d.tap("set").await?;
627 d.assert_text("picker", "Plum").await
628 })
629 }
630
631 #[day_macros::test(day_core)]
633 fn picker_options_reactive() -> Case {
634 let choice = Signal::new(1usize);
635 let more = Signal::new(false);
636 Case::new()
637 .proves(kinds::PICKER)
638 .page(move || {
639 column((
640 picker(choice, move || {
641 let mut v = vec![(0usize, "One"), (1, "Two")];
642 if more.get() {
643 v.push((2, "Three"));
644 }
645 v
646 })
647 .id(day_core::id!(picker)),
648 button("More")
649 .action(move || more.set(true))
650 .id(day_core::id!(more)),
651 ))
652 .spacing(8.0)
653 })
654 .drive(|d: Drive| async move {
655 d.assert_text("picker", "Two").await?;
656 d.tap("more").await?;
657 d.select("picker", 2).await?;
658 d.assert_text("picker", "Three").await
659 })
660 }
661
662 #[day_macros::test(day_core)]
664 fn picker_disabled() -> Case {
665 let (a, b, c) = (
666 Signal::new(0usize),
667 Signal::new(0usize),
668 Signal::new(0usize),
669 );
670 let enabled = Signal::new(false);
671 Case::new()
672 .proves(kinds::PICKER)
673 .page(move || {
674 column((
675 picker(a, FRUIT)
676 .enabled(move || enabled.get())
677 .id(day_core::id!(menu)),
678 picker(b, FRUIT)
679 .segmented()
680 .enabled(move || enabled.get())
681 .id(day_core::id!(segmented)),
682 picker(c, FRUIT)
683 .inline()
684 .enabled(move || enabled.get())
685 .id(day_core::id!(inline)),
686 button("Enable")
687 .action(move || enabled.set(true))
688 .id(day_core::id!(enable)),
689 ))
690 .spacing(8.0)
691 })
692 .shot("disabled")
693 .drive(|d: Drive| async move {
694 for id in ["menu", "segmented", "inline"] {
695 d.assert_enabled(id, false).await?;
696 }
697 d.tap("enable").await?;
698 for id in ["menu", "segmented", "inline"] {
699 d.assert_enabled(id, true).await?;
700 }
701 Ok(())
702 })
703 }
704
705 #[day_macros::test(day_core)]
707 fn text_area_binding() -> Case {
708 let text = Signal::new(String::new());
709 Case::new()
710 .proves(kinds::TEXT_AREA)
711 .page(move || {
712 column((
713 text_area(text).placeholder("Notes").id(day_core::id!(area)),
714 label(move || text.get().chars().count().to_string()).id(day_core::id!(len)),
715 button("Set")
716 .action(move || text.set("Set from Day".into()))
717 .id(day_core::id!(set)),
718 ))
719 .spacing(8.0)
720 })
721 .drive(|d: Drive| async move {
722 d.input("area", "typed").await?;
723 d.assert_text("len", "5").await?;
724 d.tap("set").await?;
725 d.assert_text("area", "Set from Day").await
726 })
727 }
728
729 #[day_macros::test(day_core)]
731 fn text_area_multiline() -> Case {
732 let text = Signal::new("first\nsecond".to_owned());
733 Case::new()
734 .proves(kinds::TEXT_AREA)
735 .page(move || text_area(text).min_lines(3).id(day_core::id!(area)))
736 .drive(|d: Drive| async move {
737 d.assert_text("area", "first\nsecond").await?;
738 d.input("area", "one\ntwo\nthree").await?;
739 d.assert_text("area", "one\ntwo\nthree").await
740 })
741 }
742
743 #[day_macros::test(day_core)]
746 fn text_area_submit() -> Case {
747 let text = Signal::new(String::new());
748 let sent = Signal::new(String::new());
749 let count = Signal::new(0u32);
750 Case::new()
751 .proves(kinds::TEXT_AREA)
752 .page(move || {
753 column((
754 text_area(text)
755 .min_lines(3)
756 .on_submit(move || {
757 sent.set(text.get_untracked());
758 count.update(|n| *n += 1);
759 text.set(String::new());
760 })
761 .id(day_core::id!(area)),
762 label(move || sent.get()).id(day_core::id!(sent)),
763 label(move || count.get().to_string()).id(day_core::id!(count)),
764 ))
765 })
766 .drive(|d: Drive| async move {
767 d.input("area", "first\n東京").await?;
768 d.assert_text("count", "0").await?;
769 d.submit("area").await?;
770 d.assert_text("sent", "first\n東京").await?;
771 d.assert_text("count", "1").await?;
772 d.assert_text("area", "").await?;
773 d.input("area", "next").await?;
774 d.submit("area").await?;
775 d.assert_text("sent", "next").await?;
776 d.assert_text("count", "2").await?;
777 d.assert_text("area", "").await
778 })
779 }
780
781 #[day_macros::test(day_core)]
783 fn text_area_read_only() -> Case {
784 let text = Signal::new("Read me".to_owned());
785 Case::new()
786 .proves(kinds::TEXT_AREA)
787 .proves_cap(Cap::TextEditable)
788 .requires(Cap::TextEditable)
789 .page(move || {
790 column((
791 text_area(text).editable(false).id(day_core::id!(area)),
792 button("Replace")
793 .action(move || text.set("Replaced".into()))
794 .id(day_core::id!(replace)),
795 ))
796 .spacing(8.0)
797 })
798 .drive(|d: Drive| async move {
799 d.assert_text("area", "Read me").await?;
800 d.tap("replace").await?;
801 d.assert_text("area", "Replaced").await
802 })
803 }
804
805 #[day_macros::test(day_core)]
808 fn text_area_unselectable() -> Case {
809 let text = Signal::new("Fixed".to_owned());
810 Case::new()
811 .proves(kinds::TEXT_AREA)
812 .proves_cap(Cap::TextSelectable)
813 .requires(Cap::TextSelectable)
814 .page(move || {
815 text_area(text)
816 .selectable(false)
817 .editable(false)
818 .id(day_core::id!(area))
819 })
820 .drive(|d: Drive| async move { d.assert_text("area", "Fixed").await })
821 }
822
823 #[day_macros::test(day_core)]
826 fn text_area_attributes_reactive() -> Case {
827 let text = Signal::new("First\nsecond".to_owned());
828 let editable = Signal::new(true);
829 let selectable = Signal::new(true);
830 Case::new()
831 .proves(kinds::TEXT_AREA)
832 .requires(Cap::TextEditable)
833 .requires(Cap::TextSelectable)
834 .page(move || {
835 column((
836 text_area(text)
837 .editable(editable)
838 .selectable(selectable)
839 .id(day_core::id!(area)),
840 label(move || text.get()).id(day_core::id!(model)),
841 button("Lock").id(day_core::id!(lock)).action(move || {
842 editable.set(false);
843 selectable.set(false);
844 }),
845 button("Replace")
846 .id(day_core::id!(replace))
847 .action(move || text.set("Updated\n東京".into())),
848 button("Unlock").id(day_core::id!(unlock)).action(move || {
849 selectable.set(true);
850 editable.set(true);
851 }),
852 ))
853 })
854 .drive(|d: Drive| async move {
855 d.tap("lock").await?;
856 d.assert_text("area", "First\nsecond").await?;
857 d.tap("replace").await?;
858 d.assert_text("area", "Updated\n東京").await?;
859 d.assert_text("model", "Updated\n東京").await?;
860 d.tap("unlock").await?;
861 d.assert_text("area", "Updated\n東京").await?;
862 d.input("area", "Back to editing").await?;
863 d.assert_text("model", "Back to editing").await
864 })
865 }
866}