1use std::cell::{Cell, RefCell};
9use std::collections::HashSet;
10use std::hash::Hash;
11use std::rc::Rc;
12
13use day_core::*;
14use day_reactive::{AnyBinding, Binding, Scope, Signal, watch};
15use day_spec::props::*;
16
17use crate::{Decorate, Decorated, IntoReactive, IntoText, MenuEntry, Reactive, TextSource};
18use day_spec::{Event, Proposal, Rect, Size, kinds};
19
20pub fn when<P: Piece>(
38 cond: impl Fn() -> bool + 'static,
39 build_arm: impl Fn() -> P + 'static,
40) -> When {
41 When {
42 cond: Rc::new(cond),
43 then: Rc::new(move || AnyPiece::new(build_arm())),
44 otherwise: None,
45 }
46}
47
48#[must_use]
50pub struct When {
51 cond: Rc<dyn Fn() -> bool>,
52 then: Rc<dyn Fn() -> AnyPiece>,
53 otherwise: Option<Rc<dyn Fn() -> AnyPiece>>,
54}
55
56#[day_macros::builder(WhenBuilder)]
57impl When {
58 pub fn otherwise<P: Piece>(mut self, build_arm: impl Fn() -> P + 'static) -> Self {
64 self.otherwise = Some(Rc::new(move || AnyPiece::new(build_arm())));
65 self
66 }
67}
68
69impl Piece for When {
70 fn build(self, cx: &mut BuildCx) -> RNode {
71 let anchor = cx.layout_only(
72 Rc::new(PassThrough),
73 Flex {
74 is_group: true,
75 ..Default::default()
76 },
77 Boundary::No,
78 );
79 let state: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
80 let owner = Scope::current();
87 let When {
88 cond,
89 then,
90 otherwise,
91 } = self;
92
93 let mount = {
94 let state = state.clone();
95 move |on: bool| {
96 if !with_tree(|t| t.node_exists(anchor)) {
98 return;
99 }
100 if let Some(scope) = state.borrow_mut().take() {
104 scope.dispose();
105 while with_tree(|t| t.child_count(anchor)) > 0 {
107 let child = with_tree(|t| t.first_child(anchor));
108 match child {
109 Some(c) => with_tree(|t| t.remove_subtree(c)),
110 None => break,
111 }
112 }
113 }
114 let arm = if on { Some(&then) } else { otherwise.as_ref() };
115 if let Some(arm) = arm {
116 let scope = owner.enter(Scope::child);
117 scope.enter(|| {
118 let mut cx = BuildCx::new(anchor);
119 let _ = arm().build(&mut cx);
120 });
121 *state.borrow_mut() = Some(scope);
122 }
123 }
124 };
125
126 let initial = {
127 let cond = cond.clone();
128 day_reactive::untrack(move || cond())
129 };
130 mount(initial);
131 watch(
132 move || cond(),
133 move |now, old| {
134 if Some(now) != old {
135 mount(*now);
136 }
137 },
138 );
139 anchor
140 }
141}
142
143fn in_row_scope<R>(build: impl FnOnce() -> R) -> R {
151 Scope::child().enter(build)
152}
153
154pub struct ItemSlot<T: 'static, K: 'static> {
156 sig: Signal<T>,
157 key: Signal<K>,
158}
159
160impl<T: 'static, K: 'static> Clone for ItemSlot<T, K> {
161 fn clone(&self) -> Self {
162 *self
163 }
164}
165impl<T: 'static, K: 'static> Copy for ItemSlot<T, K> {}
166
167impl<T: Clone + 'static, K: Clone + 'static> ItemSlot<T, K> {
168 #[must_use]
173 pub fn get(self) -> T {
174 self.sig.get()
175 }
176 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
178 self.sig.with(f)
179 }
180 pub fn field<V: Clone>(self, f: impl FnOnce(&T) -> V) -> V {
183 self.sig.with(f)
184 }
185 #[must_use]
188 pub fn key(self) -> K {
189 self.key.get()
190 }
191}
192
193pub fn keyed<K, P>(
209 key: impl Fn() -> Option<K> + 'static,
210 build: impl Fn(&K) -> P + 'static,
211) -> Keyed<K>
212where
213 K: PartialEq + Clone + 'static,
214 P: Piece,
215{
216 Keyed {
217 key: Rc::new(key),
218 build: Rc::new(move |k| AnyPiece::new(build(k))),
219 }
220}
221
222pub fn switch<K, P>(selector: impl Fn() -> K + 'static, arm: impl Fn(&K) -> P + 'static) -> Keyed<K>
236where
237 K: PartialEq + Clone + 'static,
238 P: Piece,
239{
240 keyed(move || Some(selector()), arm)
241}
242
243pub struct Keyed<K: 'static> {
245 key: Rc<dyn Fn() -> Option<K>>,
246 build: Rc<dyn Fn(&K) -> AnyPiece>,
247}
248
249impl<K: PartialEq + Clone + 'static> Piece for Keyed<K> {
250 fn build(self, cx: &mut BuildCx) -> RNode {
251 let anchor = cx.layout_only(
252 Rc::new(PassThrough),
253 Flex {
254 is_group: true,
255 ..Default::default()
256 },
257 Boundary::No,
258 );
259 let owner = Scope::current();
263 let Keyed { key, build } = self;
264 let live: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
265 let mount = {
266 let live = live.clone();
267 move |k: &Option<K>| {
268 if !with_tree(|t| t.node_exists(anchor)) {
269 return;
270 }
271 if let Some(scope) = live.borrow_mut().take() {
274 scope.dispose();
275 while with_tree(|t| t.child_count(anchor)) > 0 {
276 match with_tree(|t| t.first_child(anchor)) {
277 Some(c) => with_tree(|t| t.remove_subtree(c)),
278 None => break,
279 }
280 }
281 }
282 if let Some(k) = k {
283 let scope = owner.enter(Scope::child);
284 scope.enter(|| {
285 let mut cx = BuildCx::new(anchor);
286 let _ = build(k).build(&mut cx);
287 });
288 *live.borrow_mut() = Some(scope);
289 }
290 }
291 };
292 let initial = {
293 let key = key.clone();
294 day_reactive::untrack(move || key())
295 };
296 mount(&initial);
297 watch(
299 move || key(),
300 move |now, old| {
301 if Some(now) != old {
302 mount(now);
303 }
304 },
305 );
306 anchor
307 }
308}
309
310pub trait LoadSource<T: 'static, M>: 'static {
313 fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>>;
314}
315
316pub struct ResourceMark;
318
319impl<T: Clone + 'static> LoadSource<T, ResourceMark> for day_reactive::Resource<T> {
320 fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
321 Rc::new(move || self.signal().get())
322 }
323}
324
325impl<T: Clone + 'static> LoadSource<T, crate::SignalMark> for Signal<day_reactive::Load<T>> {
326 fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
327 Rc::new(move || self.get())
328 }
329}
330
331impl<T: 'static, F: Fn() -> day_reactive::Load<T> + 'static> LoadSource<T, crate::FnMark> for F {
332 fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
333 Rc::new(self)
334 }
335}
336
337pub struct Loaded<T: 'static> {
340 source: Rc<dyn Fn() -> day_reactive::Load<T>>,
341 last: Rc<RefCell<T>>,
342}
343
344impl<T: 'static> Clone for Loaded<T> {
345 fn clone(&self) -> Self {
346 Loaded {
347 source: self.source.clone(),
348 last: self.last.clone(),
349 }
350 }
351}
352
353impl<T: Clone + 'static> Loaded<T> {
354 #[must_use]
358 pub fn get(&self) -> T {
359 if let day_reactive::Load::Ready(v) = (self.source)() {
360 *self.last.borrow_mut() = v.clone();
361 v
362 } else {
363 self.last.borrow().clone()
364 }
365 }
366 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
368 let v = self.get();
369 f(&v)
370 }
371}
372
373pub fn load<T, P, M>(
388 state: impl LoadSource<T, M>,
389 ready: impl Fn(Loaded<T>) -> P + 'static,
390) -> LoadPiece<T>
391where
392 T: Clone + 'static,
393 P: Piece,
394{
395 LoadPiece {
396 source: state.into_load_reader(),
397 ready: Rc::new(move |v| AnyPiece::new(ready(v))),
398 loading: None,
399 failed: None,
400 }
401}
402
403#[must_use]
405pub struct LoadPiece<T: 'static> {
406 source: Rc<dyn Fn() -> day_reactive::Load<T>>,
407 ready: Rc<dyn Fn(Loaded<T>) -> AnyPiece>,
408 loading: Option<Rc<dyn Fn() -> AnyPiece>>,
409 failed: Option<FailedArm>,
410}
411
412type FailedArm = Rc<dyn Fn(&(dyn std::error::Error + 'static)) -> AnyPiece>;
414
415impl<T: Clone + 'static> LoadPiece<T> {
416 pub fn loading<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
418 self.loading = Some(Rc::new(move || AnyPiece::new(build())));
419 self
420 }
421 pub fn failed<P: Piece>(
423 mut self,
424 build: impl Fn(&(dyn std::error::Error + 'static)) -> P + 'static,
425 ) -> Self {
426 self.failed = Some(Rc::new(move |e| AnyPiece::new(build(e))));
427 self
428 }
429}
430
431#[derive(Clone, Copy, PartialEq, Eq)]
433enum LoadArm {
434 Loading,
435 Ready,
436 Failed,
437}
438
439impl<T: Clone + 'static> Piece for LoadPiece<T> {
440 fn build(self, cx: &mut BuildCx) -> RNode {
441 let LoadPiece {
442 source,
443 ready,
444 loading,
445 failed,
446 } = self;
447 let arm_source = source.clone();
448 let error_source = source.clone();
449 keyed(
450 move || {
451 Some(match arm_source() {
452 day_reactive::Load::Loading => LoadArm::Loading,
453 day_reactive::Load::Ready(_) => LoadArm::Ready,
454 day_reactive::Load::Failed(_) => LoadArm::Failed,
455 })
456 },
457 move |arm| match arm {
458 LoadArm::Loading => loading.as_ref().map(|f| f()),
459 LoadArm::Failed => {
460 failed
461 .as_ref()
462 .and_then(|f| match day_reactive::untrack(|| error_source()) {
463 day_reactive::Load::Failed(e) => Some(f(&*e)),
464 _ => None,
465 })
466 }
467 LoadArm::Ready => match day_reactive::untrack(|| source()) {
468 day_reactive::Load::Ready(v) => Some(ready(Loaded {
469 source: source.clone(),
470 last: Rc::new(RefCell::new(v)),
471 })),
472 _ => None,
473 },
474 },
475 )
476 .build(cx)
477 }
478}
479
480pub fn adaptive<C: PieceSeq>(children: C) -> Adaptive<C> {
493 Adaptive {
494 children,
495 spacing: 0.0,
496 at: day_spec::WidthClass::Compact,
497 align: CrossAlign::Center,
498 }
499}
500
501#[must_use]
503pub struct Adaptive<C: PieceSeq> {
504 children: C,
505 spacing: f64,
506 at: day_spec::WidthClass,
507 align: CrossAlign,
508}
509
510#[day_macros::builder(AdaptiveBuilder)]
511impl<C: PieceSeq> Adaptive<C> {
512 pub fn spacing(mut self, s: impl Into<f64>) -> Self {
514 self.spacing = s.into();
515 self
516 }
517 pub fn stack_at(mut self, at: day_spec::WidthClass) -> Self {
519 self.at = at;
520 self
521 }
522 pub fn align(mut self, a: crate::VAlign) -> Self {
525 self.align = match a {
526 crate::VAlign::Top => CrossAlign::Leading,
527 crate::VAlign::Center => CrossAlign::Center,
528 crate::VAlign::Bottom => CrossAlign::Trailing,
529 crate::VAlign::FirstBaseline => CrossAlign::FirstBaseline,
530 };
531 self
532 }
533}
534
535struct AdaptiveLayout {
538 axis: std::cell::Cell<Axis>,
539 spacing: f64,
540 row_align: CrossAlign,
541}
542
543impl AdaptiveLayout {
544 fn stack(&self) -> StackLayout {
545 let axis = self.axis.get();
546 StackLayout {
547 axis,
548 spacing: self.spacing,
549 align: match axis {
550 Axis::Vertical => CrossAlign::Leading,
551 Axis::Horizontal => self.row_align,
552 },
553 }
554 }
555}
556
557impl Layout for AdaptiveLayout {
558 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
559 self.stack().measure(cx, children, p)
560 }
561 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
562 self.stack().place(cx, children, bounds);
563 }
564 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
565 self.stack().baseline(cx, children, size)
566 }
567}
568
569impl<C: PieceSeq> Piece for Adaptive<C> {
570 fn build(self, cx: &mut BuildCx) -> RNode {
571 let at = self.at;
572 let stacked = move || size_class().is_some_and(|c| c.width <= at);
573 let layout = Rc::new(AdaptiveLayout {
574 axis: std::cell::Cell::new(if day_reactive::untrack(stacked) {
575 Axis::Vertical
576 } else {
577 Axis::Horizontal
578 }),
579 spacing: self.spacing,
580 row_align: self.align,
581 });
582 let node = cx.native(
583 kinds::CONTAINER,
584 &ContainerProps::default(),
585 layout.clone(),
586 Flex::default(),
587 Boundary::No,
588 );
589 cx.under(node, |cx| self.children.build_each(cx));
590 watch(stacked, move |now: &bool, _| {
592 layout.axis.set(if *now {
593 Axis::Vertical
594 } else {
595 Axis::Horizontal
596 });
597 day_core::invalidate_size(node);
598 });
599 node
600 }
601}
602
603pub trait RowSource {
612 type Slot: Copy + 'static;
614 type Ref: 'static;
616 type Conn: RowConn<Slot = Self::Slot, Ref = Self::Ref>;
617 fn connect(self) -> Self::Conn;
618}
619
620pub trait RowConn: 'static {
623 type Slot: Copy + 'static;
624 type Ref: 'static;
625
626 fn refresh(&self) -> Vec<u64>;
631 fn len(&self) -> usize;
633 fn is_empty(&self) -> bool {
634 self.len() == 0
635 }
636 fn token_at(&self, index: usize) -> u64;
638 fn tokens_now(&self) -> Vec<u64>;
640 fn slot_at(&self, index: usize) -> Option<Self::Slot>;
643 fn rebind(&self, slot: &Self::Slot, index: usize);
645 fn select_ref(&self, index: usize) -> Option<Self::Ref>;
647 fn values_flow_by_reload(&self) -> bool;
652 fn take_row_events(&self) -> Option<Vec<day_spec::props::RowDelta>> {
657 None
658 }
659 fn commit_move(&self, from: usize, to: usize);
661 fn commit_delete(&self, index: usize);
663}
664
665pub fn items<T, K>(
668 f: impl Fn() -> Vec<T> + 'static,
669 key_of: impl Fn(&T) -> K + 'static,
670) -> Items<T, K>
671where
672 T: Clone + 'static,
673 K: Clone + Hash + 'static,
674{
675 Items {
676 f: Rc::new(f),
677 key_of: Rc::new(key_of),
678 }
679}
680
681pub struct Items<T: 'static, K: 'static> {
683 f: Rc<dyn Fn() -> Vec<T>>,
684 key_of: Rc<dyn Fn(&T) -> K>,
685}
686
687impl<T: Clone + 'static, K: Clone + Hash + 'static> RowSource for Items<T, K> {
688 type Slot = ItemSlot<T, K>;
689 type Ref = K;
690 type Conn = ItemsConn<T, K>;
691 fn connect(self) -> ItemsConn<T, K> {
692 ItemsConn {
693 f: self.f,
694 key_of: self.key_of,
695 snapshot: RefCell::new(Vec::new()),
696 tokens: RefCell::new(Vec::new()),
697 }
698 }
699}
700
701pub struct ItemsConn<T: 'static, K: 'static> {
703 f: Rc<dyn Fn() -> Vec<T>>,
704 key_of: Rc<dyn Fn(&T) -> K>,
705 snapshot: RefCell<Vec<T>>,
706 tokens: RefCell<Vec<u64>>,
707}
708
709impl<T: Clone + 'static, K: Clone + Hash + 'static> RowConn for ItemsConn<T, K> {
710 type Slot = ItemSlot<T, K>;
711 type Ref = K;
712
713 fn refresh(&self) -> Vec<u64> {
714 let its = (self.f)();
715 let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
716 *self.snapshot.borrow_mut() = its;
717 (*self.tokens.borrow_mut()).clone_from(&toks);
718 toks
719 }
720 fn len(&self) -> usize {
721 self.snapshot.borrow().len()
722 }
723 fn token_at(&self, index: usize) -> u64 {
724 self.tokens.borrow().get(index).copied().unwrap_or(0)
725 }
726 fn tokens_now(&self) -> Vec<u64> {
727 self.tokens.borrow().clone()
728 }
729 fn slot_at(&self, index: usize) -> Option<ItemSlot<T, K>> {
730 let item = self.snapshot.borrow().get(index).cloned()?;
731 let key = (self.key_of)(&item);
732 Some(ItemSlot {
733 sig: Signal::new(item),
734 key: Signal::new(key),
735 })
736 }
737 fn rebind(&self, slot: &ItemSlot<T, K>, index: usize) {
738 let Some(item) = self.snapshot.borrow().get(index).cloned() else {
739 return; };
741 slot.key.set((self.key_of)(&item));
742 slot.sig.set(item);
743 }
744 fn select_ref(&self, index: usize) -> Option<K> {
745 self.snapshot.borrow().get(index).map(|t| (self.key_of)(t))
746 }
747 fn values_flow_by_reload(&self) -> bool {
748 true
749 }
750 fn commit_move(&self, from: usize, to: usize) {
751 let mut snap = self.snapshot.borrow_mut();
752 let mut toks = self.tokens.borrow_mut();
753 if from >= snap.len() || to >= snap.len() {
754 return;
755 }
756 let item = snap.remove(from);
757 snap.insert(to, item);
758 let tok = toks.remove(from);
759 toks.insert(to, tok);
760 }
761 fn commit_delete(&self, index: usize) {
762 let mut snap = self.snapshot.borrow_mut();
763 let mut toks = self.tokens.borrow_mut();
764 if index >= snap.len() {
765 return;
766 }
767 snap.remove(index);
768 toks.remove(index);
769 }
770}
771
772struct EachRow<S: 'static> {
773 token: u64,
774 slot: S,
775 scope: Scope,
776 root: RNode,
777}
778
779pub fn each<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> impl Piece
786where
787 S: RowSource + 'static,
788 P: Piece,
789{
790 piece_fn(move |cx| {
791 let anchor = cx.layout_only(
792 Rc::new(PassThrough),
793 Flex {
794 is_group: true,
795 ..Default::default()
796 },
797 Boundary::No,
798 );
799 let owner = Scope::current();
803 let conn = Rc::new(source.connect());
804 let rows: Rc<RefCell<Vec<EachRow<S::Slot>>>> = Rc::new(RefCell::new(Vec::new()));
805 let build_row = Rc::new(build_row);
806
807 let sync = {
808 let rows = rows.clone();
809 let conn = conn.clone();
810 let build_row = build_row.clone();
811 move |tokens: &Vec<u64>| {
812 if !with_tree(|t| t.node_exists(anchor)) {
820 return;
821 }
822 if cfg!(debug_assertions) {
823 let mut seen = HashSet::new();
824 for k in tokens {
825 assert!(seen.insert(*k), "day: duplicate key in `each` diff");
826 }
827 }
828 let mut old = std::mem::take(&mut *rows.borrow_mut());
829 let mut next: Vec<EachRow<S::Slot>> = Vec::with_capacity(tokens.len());
830 for (index, tok) in tokens.iter().enumerate() {
831 if let Some(pos) = old.iter().position(|r| r.token == *tok) {
832 let row = old.remove(pos);
833 conn.rebind(&row.slot, index);
836 next.push(row);
837 } else {
838 let scope = owner.enter(Scope::child);
839 let built = scope.enter(|| {
840 let slot = conn.slot_at(index)?;
841 let mut cx = BuildCx::new(anchor);
842 Some((slot, in_row_scope(|| build_row(slot).build(&mut cx))))
843 });
844 match built {
845 Some((slot, root)) => next.push(EachRow {
846 token: *tok,
847 slot,
848 scope,
849 root,
850 }),
851 None => scope.dispose(),
852 }
853 }
854 }
855 for row in old {
857 row.scope.dispose();
858 with_tree(|t| t.remove_subtree(row.root));
859 }
860 let order: Vec<RNode> = next.iter().map(|r| r.root).collect();
862 with_tree(|t| t.reorder_children(anchor, order));
863 *rows.borrow_mut() = next;
864 }
865 };
866
867 let initial = {
868 let conn = conn.clone();
869 day_reactive::untrack(move || conn.refresh())
870 };
871 sync(&initial);
872 let conn2 = conn.clone();
873 watch(move || conn2.refresh(), move |new, _| sync(new));
874 anchor
875 })
876}
877
878fn key_token<K: Hash>(k: &K) -> u64 {
884 use std::hash::Hasher;
885 let mut h = std::collections::hash_map::DefaultHasher::new();
886 k.hash(&mut h);
887 h.finish()
888}
889
890#[must_use]
894pub struct List<S: RowSource> {
895 source: Option<S>,
896 build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
897 row_height: RowHeight,
898 on_select: Option<Rc<dyn Fn(S::Ref)>>,
899 on_activate: Option<Rc<dyn Fn(S::Ref)>>,
900 on_selection: Option<SelectionFn<S::Ref>>,
901 multi_select: bool,
902 selected_rows: Option<Rc<dyn Fn() -> Vec<usize>>>,
903 selection: Option<ListSelection<S::Ref>>,
904 scroll_to_end: Option<day_reactive::Trigger>,
905 scroll_to_row: Option<RowCommand>,
906 visible_rows: Option<AnyBinding<std::ops::Range<usize>>>,
907 follow_end: Option<f64>,
908 end_reached: Option<(f64, Rc<dyn Fn()>)>,
909 header: Option<SlotBuild>,
910 footer: Option<SlotBuild>,
911 empty: Option<SlotBuild>,
912 content_padding: day_spec::Insets,
913 reorder: Option<Reorder>,
914 delete: Option<Delete>,
915 swipe_leading: Option<SwipeProvider>,
916 swipe_trailing: Option<SwipeProvider>,
917 separators: Option<bool>,
918 inset_grouped: bool,
919 editing: crate::Reactive<bool>,
920 sections: Option<ListSections<S::Slot>>,
921}
922
923struct ListSections<Slot> {
926 key: Rc<dyn Fn(usize) -> u64>,
927 header: Rc<dyn Fn(Slot) -> AnyPiece>,
928}
929
930type SelectionFn<R> = Rc<dyn Fn(Vec<R>)>;
932
933struct RowCommand {
936 pending: Rc<dyn Fn() -> Option<RowTarget>>,
937 consume: Rc<dyn Fn()>,
938}
939
940type SlotBuild = Rc<dyn Fn() -> AnyPiece>;
942
943#[derive(Clone, Copy, Debug, PartialEq, Eq)]
952pub struct RowTarget {
953 row: usize,
954 align: day_spec::RowAlign,
955 animated: bool,
956}
957
958impl RowTarget {
959 #[must_use]
962 pub fn new(row: usize) -> Self {
963 RowTarget {
964 row,
965 align: day_spec::RowAlign::Nearest,
966 animated: true,
967 }
968 }
969 #[must_use]
972 pub fn align(mut self, align: day_spec::RowAlign) -> Self {
973 self.align = align;
974 self
975 }
976 #[must_use]
978 pub fn instant(mut self) -> Self {
979 self.animated = false;
980 self
981 }
982}
983
984impl From<usize> for RowTarget {
985 fn from(row: usize) -> Self {
986 RowTarget::new(row)
987 }
988}
989
990pub trait SelectionKey {
993 fn selection_key(&self) -> u64;
994}
995
996struct ListSelection<R> {
999 key: Rc<dyn Fn() -> Option<u64>>,
1000 write: Rc<dyn Fn(Option<u64>)>,
1001 key_of: Rc<dyn Fn(&R) -> u64>,
1002}
1003
1004#[derive(Clone)]
1010enum ItemIcon {
1011 Vector(Reactive<day_spec::VectorName>),
1012 Symbol(day_spec::Symbol),
1013}
1014
1015impl ItemIcon {
1016 fn spec(&self, tracked: bool) -> day_spec::Icon {
1018 match self {
1019 ItemIcon::Vector(r) => {
1020 let name = if tracked { r.get() } else { r.get_untracked() };
1021 day_spec::Icon::Image(name.as_str().to_owned())
1022 }
1023 ItemIcon::Symbol(s) => day_spec::Icon::Symbol(*s),
1024 }
1025 }
1026}
1027
1028#[must_use]
1030pub struct ListItem {
1031 title: TextSource,
1032 subtitle: Option<TextSource>,
1033 detail: Option<TextSource>,
1034 icon: Option<ItemIcon>,
1035 icon_tint: Option<Reactive<day_spec::Ink>>,
1036 checked: Option<Reactive<bool>>,
1037}
1038
1039pub fn list_item<M>(title: impl IntoText<M>) -> ListItem {
1055 ListItem {
1056 title: title.into_text(),
1057 subtitle: None,
1058 detail: None,
1059 icon: None,
1060 icon_tint: None,
1061 checked: None,
1062 }
1063}
1064
1065#[day_macros::builder(ListItemBuilder)]
1066impl ListItem {
1067 pub fn subtitle<M>(mut self, text: impl IntoText<M>) -> Self {
1069 self.subtitle = Some(text.into_text());
1070 self
1071 }
1072 pub fn detail<M>(mut self, text: impl IntoText<M>) -> Self {
1074 self.detail = Some(text.into_text());
1075 self
1076 }
1077 pub fn icon<M>(mut self, name: impl IntoReactive<day_spec::VectorName, M>) -> Self {
1081 self.icon = Some(ItemIcon::Vector(name.into_reactive()));
1082 self
1083 }
1084 pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1086 self.icon = Some(ItemIcon::Symbol(symbol));
1087 self
1088 }
1089 pub fn icon_tint<M>(mut self, color: impl IntoReactive<day_spec::Ink, M>) -> Self {
1091 self.icon_tint = Some(color.into_reactive());
1092 self
1093 }
1094 pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
1097 self.checked = Some(on.into_reactive());
1098 self
1099 }
1100}
1101
1102impl Piece for ListItem {
1103 fn build(self, cx: &mut BuildCx) -> RNode {
1104 if day_core::capability(day_spec::Cap::ListItem) == day_spec::Support::Native {
1105 self.build_native(cx)
1106 } else {
1107 self.compose().build(cx)
1108 }
1109 }
1110}
1111
1112impl ListItem {
1113 fn build_native(self, cx: &mut BuildCx) -> RNode {
1115 let text = |t: &Option<TextSource>| t.as_ref().map_or_default(TextSource::initial);
1116 let props = ListItemProps {
1117 title: self.title.initial(),
1118 subtitle: text(&self.subtitle),
1119 detail: text(&self.detail),
1120 icon: self.icon.as_ref().map(|i| i.spec(false)),
1121 icon_tint: self.icon_tint.as_ref().map(Reactive::get_untracked),
1122 checked: self.checked.as_ref().is_some_and(Reactive::get_untracked),
1123 };
1124 let node = cx.leaf(
1126 kinds::LIST_ITEM,
1127 &props,
1128 Flex {
1129 grow_w: true,
1130 whole_row: true,
1131 ..Default::default()
1132 },
1133 );
1134 let patch = move |p: ListItemPatch, size: bool| {
1135 with_tree(|t| t.patch(node, Box::new(p), size));
1136 };
1137 let bind_text =
1138 |src: Option<TextSource>, seed: String, make: fn(String) -> ListItemPatch| {
1139 if let Some(src @ TextSource::Dyn(_)) = src {
1140 day_reactive::bind_seeded(
1141 seed,
1142 move || src.resolve(),
1143 move |t: &String| patch(make(t.clone()), true),
1144 );
1145 }
1146 };
1147 bind_text(Some(self.title), props.title, ListItemPatch::Title);
1148 bind_text(self.subtitle, props.subtitle, ListItemPatch::Subtitle);
1149 bind_text(self.detail, props.detail, ListItemPatch::Detail);
1150 if let Some(icon @ ItemIcon::Vector(Reactive::Dyn(_))) = self.icon {
1151 day_reactive::bind_seeded(
1152 props.icon,
1153 move || Some(icon.spec(true)),
1154 move |i| patch(ListItemPatch::Icon(i.clone()), false),
1155 );
1156 }
1157 if let Some(tint @ Reactive::Dyn(_)) = self.icon_tint {
1158 day_reactive::bind_seeded(
1159 props.icon_tint,
1160 move || Some(tint.get()),
1161 move |c| patch(ListItemPatch::IconTint(*c), false),
1162 );
1163 }
1164 if let Some(on @ Reactive::Dyn(_)) = self.checked {
1165 day_reactive::bind_seeded(
1166 props.checked,
1167 move || on.get(),
1168 move |b: &bool| patch(ListItemPatch::Checked(*b), true),
1169 );
1170 }
1171 node
1172 }
1173
1174 fn compose(self) -> impl Piece {
1176 use crate::{column, image, label, row, vector, when};
1177 let tint = self.icon_tint;
1178 let leading = self.icon.map(move |icon| match icon {
1179 ItemIcon::Vector(src) => {
1180 let glyph = vector(move || src.get()).template();
1181 match tint {
1182 Some(t) => glyph
1183 .tint(move || t.get())
1184 .decorative()
1185 .frame(20.0, 20.0)
1186 .any(),
1187 None => glyph.decorative().frame(20.0, 20.0).any(),
1188 }
1189 }
1190 ItemIcon::Symbol(sym) => match sym.outline_svg() {
1191 Some(svg) => image(svg.into_bytes()).template().frame(20.0, 20.0).any(),
1192 None => crate::spacer().frame(20.0, 20.0).any(),
1193 },
1194 });
1195 let titles = column((
1196 label(self.title),
1197 self.subtitle
1198 .map(|t| label(t).font(day_spec::Font::Footnote).secondary()),
1199 ))
1200 .spacing(2.0)
1201 .align(crate::HAlign::Leading)
1202 .grow(Dimension::Width);
1203 let detail = self.detail.map(|t| label(t).secondary());
1204 let checked = self.checked.clone();
1205 let mark = checked.map(|on| {
1206 when(
1207 move || on.get(),
1208 || {
1209 let svg = day_spec::Symbol::Check.outline_svg().unwrap_or_default();
1210 image(svg.into_bytes())
1211 .template()
1212 .decorative()
1213 .frame(16.0, 16.0)
1214 },
1215 )
1216 });
1217 let selected = self.checked;
1218 row((leading, titles, detail, mark))
1219 .spacing(crate::Space::M)
1220 .align(crate::VAlign::Center)
1221 .grow(Dimension::Width)
1222 .a11y(move |a| match selected {
1223 Some(on) => a.selected(move || on.get()),
1224 None => a,
1225 })
1226 }
1227}
1228
1229type SwipeProvider = Rc<dyn Fn(usize) -> Vec<SwipeAction>>;
1232
1233#[must_use]
1237pub struct SwipeAction {
1238 label: TextSource,
1239 destructive: bool,
1240 tint: Option<day_spec::Ink>,
1241 symbol: Option<day_spec::Symbol>,
1242 handler: Rc<dyn Fn()>,
1243}
1244
1245pub fn swipe_action<M>(label: impl IntoText<M>) -> SwipeAction {
1251 SwipeAction {
1252 label: label.into_text(),
1253 destructive: false,
1254 tint: None,
1255 symbol: None,
1256 handler: Rc::new(|| {}),
1257 }
1258}
1259
1260impl SwipeAction {
1261 pub fn destructive(mut self) -> Self {
1264 self.destructive = true;
1265 self
1266 }
1267 pub fn tint(mut self, color: impl Into<day_spec::Ink>) -> Self {
1270 self.tint = Some(color.into());
1271 self
1272 }
1273 pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1277 self.symbol = Some(symbol);
1278 self
1279 }
1280 pub fn action(mut self, f: impl Fn() + 'static) -> Self {
1284 self.handler = Rc::new(f);
1285 self
1286 }
1287}
1288
1289#[derive(Clone)]
1298#[must_use]
1299pub struct Reorder {
1300 moved: Rc<dyn Fn(usize, usize)>,
1301 guard: Option<Rc<dyn Fn(usize, usize) -> ReorderVerdict>>,
1302 enabled: Reactive<bool>,
1303}
1304
1305impl Reorder {
1306 pub fn new(moved: impl Fn(usize, usize) + 'static) -> Reorder {
1311 Reorder {
1312 moved: Rc::new(moved),
1313 guard: None,
1314 enabled: Reactive::Const(true),
1315 }
1316 }
1317 pub fn guard(mut self, g: impl Fn(usize, usize) -> ReorderVerdict + 'static) -> Reorder {
1323 self.guard = Some(Rc::new(g));
1324 self
1325 }
1326 pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Reorder {
1330 self.enabled = on.into_reactive();
1331 self
1332 }
1333}
1334
1335#[derive(Clone)]
1345#[must_use]
1346pub struct Delete {
1347 deleted: Rc<dyn Fn(usize)>,
1348 label: Option<TextSource>,
1349 guard: Option<Rc<dyn Fn(usize) -> bool>>,
1350 enabled: Reactive<bool>,
1351}
1352
1353impl Delete {
1354 pub fn new(deleted: impl Fn(usize) + 'static) -> Delete {
1359 Delete {
1360 deleted: Rc::new(deleted),
1361 label: None,
1362 guard: None,
1363 enabled: Reactive::Const(true),
1364 }
1365 }
1366 pub fn label<M>(mut self, text: impl IntoText<M>) -> Delete {
1370 self.label = Some(text.into_text());
1371 self
1372 }
1373 pub fn guard(mut self, g: impl Fn(usize) -> bool + 'static) -> Delete {
1377 self.guard = Some(Rc::new(g));
1378 self
1379 }
1380 pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Delete {
1383 self.enabled = on.into_reactive();
1384 self
1385 }
1386}
1387
1388#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1392pub enum ReorderVerdict {
1393 Allow,
1395 Deny,
1397 Retarget(usize),
1399}
1400
1401pub fn list<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> List<S>
1405where
1406 S: RowSource + 'static,
1407 P: Piece,
1408{
1409 List {
1410 source: Some(source),
1411 build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
1412 row_height: RowHeight::Automatic,
1413 on_select: None,
1414 on_activate: None,
1415 on_selection: None,
1416 multi_select: false,
1417 selected_rows: None,
1418 selection: None,
1419 scroll_to_end: None,
1420 scroll_to_row: None,
1421 visible_rows: None,
1422 follow_end: None,
1423 end_reached: None,
1424 header: None,
1425 footer: None,
1426 empty: None,
1427 content_padding: day_spec::Insets::ZERO,
1428 reorder: None,
1429 delete: None,
1430 swipe_leading: None,
1431 swipe_trailing: None,
1432 separators: None,
1433 inset_grouped: false,
1434 editing: crate::Reactive::Const(false),
1435 sections: None,
1436 }
1437}
1438
1439#[day_macros::builder(ListBuilder<S>)]
1440impl<S: RowSource + 'static> List<S> {
1441 pub fn row_height(mut self, h: RowHeight) -> Self {
1443 self.row_height = h;
1444 self
1445 }
1446 pub fn on_activate(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1449 self.on_activate = Some(Rc::new(f));
1450 self
1451 }
1452
1453 pub fn on_select(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1456 self.on_select = Some(Rc::new(f));
1457 self
1458 }
1459 pub fn multi_select(mut self) -> Self {
1463 self.multi_select = true;
1464 self
1465 }
1466 pub fn on_selection(mut self, f: impl Fn(Vec<S::Ref>) + 'static) -> Self {
1470 self.on_selection = Some(Rc::new(f));
1471 self
1472 }
1473 pub fn selected_rows(mut self, rows: impl Fn() -> Vec<usize> + 'static) -> Self {
1477 self.selected_rows = Some(Rc::new(rows));
1478 self
1479 }
1480 pub fn selection(mut self, selected: impl Binding<Option<u64>>) -> Self
1489 where
1490 S::Ref: SelectionKey,
1491 {
1492 let selected = AnyBinding::new(selected);
1493 self.selection = Some(ListSelection {
1494 key: Rc::new(move || selected.get()),
1495 write: Rc::new(move |key| selected.set_if_changed(key)),
1496 key_of: Rc::new(|row: &S::Ref| row.selection_key()),
1497 });
1498 self
1499 }
1500 pub fn scroll_to_end(mut self, trigger: day_reactive::Trigger) -> Self {
1507 self.scroll_to_end = Some(trigger);
1508 self
1509 }
1510
1511 pub fn follow_end(mut self, threshold: f64) -> Self {
1524 self.follow_end = Some(threshold.max(0.0));
1525 self
1526 }
1527
1528 pub fn on_end_reached(mut self, threshold: f64, f: impl Fn() + 'static) -> Self {
1541 self.end_reached = Some((threshold.max(0.0), Rc::new(f)));
1542 self
1543 }
1544
1545 pub fn scroll_to_row<T>(mut self, target: impl Binding<Option<T>>) -> Self
1560 where
1561 T: Into<RowTarget> + Clone + 'static,
1562 {
1563 let target = AnyBinding::new(target);
1564 let consume = target;
1565 self.scroll_to_row = Some(RowCommand {
1566 pending: Rc::new(move || target.get().map(Into::into)),
1567 consume: Rc::new(move || consume.set(None)),
1568 });
1569 self
1570 }
1571
1572 pub fn visible_rows(mut self, rows: impl Binding<std::ops::Range<usize>>) -> Self {
1579 self.visible_rows = Some(AnyBinding::new(rows));
1580 self
1581 }
1582
1583 pub fn header<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1587 self.header = Some(Rc::new(move || AnyPiece::new(build())));
1588 self
1589 }
1590
1591 pub fn footer<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1594 self.footer = Some(Rc::new(move || AnyPiece::new(build())));
1595 self
1596 }
1597
1598 pub fn empty<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1607 self.empty = Some(Rc::new(move || {
1608 AnyPiece::new(build().aligned(Alignment::Center).grow(Dimension::Both))
1609 }));
1610 self
1611 }
1612
1613 pub fn content_padding(mut self, insets: impl Into<day_spec::Insets>) -> Self {
1617 self.content_padding = insets.into();
1618 self
1619 }
1620
1621 pub fn reorderable(mut self, reorder: Reorder) -> Self {
1629 self.reorder = Some(reorder);
1630 self
1631 }
1632
1633 pub fn deletable(mut self, delete: Delete) -> Self {
1642 self.delete = Some(delete);
1643 self
1644 }
1645
1646 pub fn swipe_leading(mut self, provider: impl Fn(usize) -> Vec<SwipeAction> + 'static) -> Self {
1655 self.swipe_leading = Some(Rc::new(provider));
1656 self
1657 }
1658
1659 pub fn swipe_trailing(
1662 mut self,
1663 provider: impl Fn(usize) -> Vec<SwipeAction> + 'static,
1664 ) -> Self {
1665 self.swipe_trailing = Some(Rc::new(provider));
1666 self
1667 }
1668
1669 pub fn separators(mut self) -> Self {
1677 self.separators = Some(true);
1678 self
1679 }
1680
1681 pub fn inset_grouped(mut self) -> Self {
1685 self.inset_grouped = true;
1686 self
1687 }
1688
1689 pub fn no_separators(mut self) -> Self {
1691 self.separators = Some(false);
1692 self
1693 }
1694
1695 pub fn sections<K: Hash, P: Piece>(
1721 mut self,
1722 key: impl Fn(usize) -> K + 'static,
1723 header: impl Fn(S::Slot) -> P + 'static,
1724 ) -> Self {
1725 self.sections = Some(ListSections {
1726 key: Rc::new(move |i| key_token(&key(i))),
1727 header: Rc::new(move |slot| AnyPiece::new(header(slot))),
1728 });
1729 self
1730 }
1731
1732 pub fn editing<M>(mut self, on: impl crate::IntoReactive<bool, M>) -> Self {
1740 self.editing = on.into_reactive();
1741 self
1742 }
1743}
1744
1745fn slot_builder_plain(build: SlotBuild) -> day_core::SupplementBuild {
1748 Box::new(move |anchor| {
1749 let scope = Scope::child();
1750 let build = build.clone();
1751 scope.enter(move || {
1752 let mut cx = BuildCx::new(anchor);
1753 build().build(&mut cx);
1754 });
1755 BuiltRow {
1756 scope,
1757 rebind: Rc::new(|_: usize| {}),
1758 }
1759 })
1760}
1761
1762fn slot_builder<C: RowConn>(
1765 conn: Rc<C>,
1766 builder: Rc<dyn Fn(C::Slot) -> AnyPiece>,
1767) -> Box<dyn Fn(usize, RNode) -> BuiltRow> {
1768 Box::new(move |index, anchor| {
1769 let scope = Scope::child();
1770 let conn = conn.clone();
1771 let builder = builder.clone();
1772 let rebind = scope.enter(move || {
1773 let Some(slot) = conn.slot_at(index) else {
1776 return Rc::new(|_: usize| {}) as Rc<dyn Fn(usize)>;
1777 };
1778 let mut rowcx = BuildCx::new(anchor);
1779 in_row_scope(|| builder(slot).build(&mut rowcx));
1780 Rc::new(move |i: usize| conn.rebind(&slot, i)) as Rc<dyn Fn(usize)>
1782 });
1783 BuiltRow { scope, rebind }
1784 })
1785}
1786
1787impl<S: RowSource + 'static> Piece for List<S> {
1788 fn build(mut self, cx: &mut BuildCx) -> RNode {
1789 let props = ListProps {
1790 activatable: self.on_activate.is_some(),
1791 row_height: self.row_height,
1792 selectable: self.on_select.is_some()
1793 || self.on_selection.is_some()
1794 || self.selection.is_some()
1795 || self.on_activate.is_some(),
1796 multi_select: self.multi_select,
1797 reorderable: self.reorder.is_some(),
1800 deletable: self.delete.is_some() && self.sections.is_none(),
1801 delete_label: self
1802 .delete
1803 .as_ref()
1804 .and_then(|d| d.label.as_ref())
1805 .map_or_default(TextSource::initial),
1806 swipe_actions: self.swipe_leading.is_some() || self.swipe_trailing.is_some(),
1807 separators: self.separators,
1808 editing: self.editing.get_untracked(),
1809 sections: self.sections.is_some(),
1810 inset_grouped: self.inset_grouped,
1811 };
1812 let node = cx.leaf(
1813 kinds::LIST,
1814 &props,
1815 Flex {
1816 grow_w: true,
1817 grow_h: true,
1818 ..Default::default()
1819 },
1820 );
1821
1822 let conn = Rc::new(self.source.take().expect("List built once").connect());
1826 let section_keys: Rc<RefCell<Vec<u64>>> = Rc::new(RefCell::new(Vec::new()));
1829 let key_of_row = self.sections.as_ref().map(|s| s.key.clone());
1830 let refresh = {
1831 let (conn, keys, key_of_row) = (conn.clone(), section_keys.clone(), key_of_row.clone());
1832 Rc::new(move || {
1833 let tokens = conn.refresh();
1834 if let Some(key) = &key_of_row {
1835 *keys.borrow_mut() = (0..conn.len()).map(|i| key(i)).collect();
1836 }
1837 (tokens, keys.borrow().clone())
1838 })
1839 };
1840 let pending_echo: Rc<RefCell<Option<Vec<u64>>>> = Rc::new(RefCell::new(None));
1844
1845 if let Some(activate) = self.on_activate.clone() {
1846 let conn = conn.clone();
1847 cx.on(node, move |event| {
1848 if let Event::ListActivated(row) = event
1849 && let Some(reference) = conn.select_ref(*row)
1850 {
1851 activate(reference);
1852 }
1853 });
1854 }
1855
1856 if self.on_select.is_some() || self.on_selection.is_some() {
1860 let (on_select, on_selection) = (self.on_select.clone(), self.on_selection.clone());
1861 let conn = conn.clone();
1862 cx.on(node, move |ev| match ev {
1863 Event::SelectionChanged(i) => {
1864 if let Some(f) = &on_select
1865 && let Some(r) = conn.select_ref(*i as usize)
1866 {
1867 f(r);
1868 }
1869 if let Some(f) = &on_selection {
1870 f(conn.select_ref(*i as usize).into_iter().collect());
1871 }
1872 }
1873 Event::SelectionSet(rows) => {
1874 if let Some(f) = &on_selection {
1875 f(rows
1876 .iter()
1877 .filter_map(|i| conn.select_ref(*i as usize))
1878 .collect());
1879 }
1880 }
1881 _ => {}
1882 });
1883 }
1884
1885 let user_pick: Rc<Cell<Option<Option<u64>>>> = Rc::new(Cell::new(None));
1891 let reveal = Rc::new(Cell::new(false));
1892 let apply_selection: Option<Rc<dyn Fn()>> = self.selection.as_ref().map(|sel| {
1893 let (key, conn, reveal) = (sel.key.clone(), conn.clone(), reveal.clone());
1894 Rc::new(move || {
1895 let wanted = day_reactive::untrack(|| key());
1896 let row = wanted.and_then(|k| conn.tokens_now().iter().position(|t| *t == k));
1897 let scroll = row.filter(|_| reveal.replace(false));
1898 day_reactive::on_main(move || {
1901 day_core::list_set_selected(node, row.into_iter().collect());
1902 if let Some(row) = scroll {
1903 list_scroll_to_row(node, row, day_spec::RowAlign::Nearest, true);
1904 }
1905 });
1906 }) as Rc<dyn Fn()>
1907 });
1908 if let Some(sel) = &self.selection {
1909 let (write, key_of) = (sel.write.clone(), sel.key_of.clone());
1910 let (conn, pick) = (conn.clone(), user_pick.clone());
1911 cx.on(node, move |ev| {
1912 let row = match ev {
1913 Event::SelectionChanged(i) => conn.select_ref(*i as usize),
1914 Event::SelectionSet(rows) => {
1915 rows.first().and_then(|i| conn.select_ref(*i as usize))
1916 }
1917 _ => return,
1918 };
1919 let key = row.as_ref().map(|r| key_of(r));
1920 pick.set(Some(key));
1921 write(key);
1922 });
1923 }
1924
1925 if let Some(on_reorder) = self.reorder.as_ref().map(|r| r.moved.clone()) {
1928 cx.on(node, move |ev| {
1929 if let Event::ListReorder { from, to } = ev {
1930 on_reorder(*from, *to);
1931 }
1932 });
1933 }
1934
1935 if let Some(on_delete) = self.delete.as_ref().map(|d| d.deleted.clone()) {
1938 cx.on(node, move |ev| {
1939 if let Event::ListDelete(index) = ev {
1940 on_delete(*index);
1941 }
1942 });
1943 }
1944
1945 if self.swipe_leading.is_some() || self.swipe_trailing.is_some() {
1951 let (leading, trailing) = (self.swipe_leading.clone(), self.swipe_trailing.clone());
1952 cx.on(node, move |ev| {
1953 if let Event::ListSwipe {
1954 index,
1955 edge,
1956 action,
1957 } = ev
1958 {
1959 let provider = match edge {
1960 day_spec::SwipeEdge::Leading => leading.as_ref(),
1961 day_spec::SwipeEdge::Trailing => trailing.as_ref(),
1962 };
1963 if let Some(p) = provider
1964 && let Some(a) = p(*index).get(*action)
1965 {
1966 (a.handler)();
1967 }
1968 }
1969 });
1970 }
1971
1972 let track_viewport =
1976 self.visible_rows.is_some() || self.follow_end.is_some() || self.end_reached.is_some();
1977 let end_distance: Rc<Cell<Option<f64>>> = Rc::new(Cell::new(None));
1980 let following = Rc::new(Cell::new(false));
1983 let end_armed = Rc::new(Cell::new(true));
1986 if track_viewport {
1987 let visible = self.visible_rows.take();
1988 let follow = self.follow_end;
1989 let reached = self.end_reached.take();
1990 let (distance, following, armed) =
1991 (end_distance.clone(), following.clone(), end_armed.clone());
1992 let conn = conn.clone();
1993 cx.on(node, move |event| {
1994 let (rows, end_distance) = match event {
1995 Event::ListViewport { rows, end_distance } => (rows, end_distance),
1996 Event::ListReaderScrolled => {
2000 following.set(false);
2001 distance.set(Some(f64::INFINITY));
2002 return;
2003 }
2004 _ => return,
2005 };
2006 if let Some(visible) = &visible {
2007 visible.set_if_changed(rows.clone());
2008 }
2009 let Some(now) = *end_distance else {
2010 return;
2011 };
2012 let near = follow.is_some_and(|threshold| now <= threshold);
2013 if near {
2014 following.set(false);
2015 }
2016 if near || !following.get() {
2017 distance.set(Some(now));
2018 }
2019 if let Some((threshold, reached)) = &reached {
2020 if now > *threshold {
2021 armed.set(true);
2022 } else if !conn.is_empty() && armed.replace(false) {
2023 reached();
2024 }
2025 }
2026 });
2027 }
2028 let has_empty = self.empty.is_some();
2029 let driver = ListDriver {
2030 track_viewport,
2031 track_reader: self.follow_end.is_some(),
2032 supplements: day_core::ListSupplements {
2033 header: self.header.take().map(slot_builder_plain),
2034 footer: self.footer.take().map(slot_builder_plain),
2035 empty: self.empty.take().map(slot_builder_plain),
2036 padding: self.content_padding,
2037 },
2038 row_height: self.row_height,
2039 len: {
2040 let conn = conn.clone();
2041 Box::new(move || conn.len())
2042 },
2043 token_at: {
2044 let conn = conn.clone();
2045 Box::new(move |i| conn.token_at(i))
2046 },
2047 build: slot_builder(conn.clone(), self.build_row.clone()),
2048 sections: self.sections.as_ref().map(|sections| ListSectionsDriver {
2049 key_at: {
2050 let keys = section_keys.clone();
2051 Box::new(move |i| keys.borrow().get(i).copied().unwrap_or_default())
2052 },
2053 build: slot_builder(conn.clone(), sections.header.clone()),
2054 }),
2055 delete: self.delete.as_ref().map(|delete| ListDeleteDriver {
2056 can_delete: {
2058 let (guard, enabled) = (delete.guard.clone(), delete.enabled.clone());
2059 Box::new(move |i| {
2060 enabled.get_untracked() && guard.as_ref().is_none_or(|g| g(i))
2061 })
2062 },
2063 deleted: {
2067 let (conn, echo, keys) =
2068 (conn.clone(), pending_echo.clone(), section_keys.clone());
2069 Box::new(move |index| {
2070 if index >= conn.len() {
2071 return;
2072 }
2073 conn.commit_delete(index);
2074 if index < keys.borrow().len() {
2075 keys.borrow_mut().remove(index);
2076 }
2077 *echo.borrow_mut() = Some(conn.tokens_now());
2078 enqueue_event(rnode_to_id(node), Event::ListDelete(index));
2079 })
2080 },
2081 }),
2082 reorder: self.reorder.as_ref().map(|reorder| ListReorderDriver {
2083 can_move: {
2086 let (guard, enabled) = (reorder.guard.clone(), reorder.enabled.clone());
2087 Box::new(move |from, to| {
2088 if !enabled.get_untracked() {
2089 return -1;
2090 }
2091 match guard.as_ref().map(|g| g(from, to)) {
2092 None | Some(ReorderVerdict::Allow) => to as i64,
2093 Some(ReorderVerdict::Deny) => -1,
2094 Some(ReorderVerdict::Retarget(i)) => i as i64,
2095 }
2096 })
2097 },
2098 moved: {
2102 let (conn, echo, keys) =
2103 (conn.clone(), pending_echo.clone(), section_keys.clone());
2104 Box::new(move |from, to| {
2105 if from >= conn.len() || to >= conn.len() {
2106 return;
2107 }
2108 conn.commit_move(from, to);
2109 {
2110 let mut keys = keys.borrow_mut();
2111 if from < keys.len() && to < keys.len() {
2112 let k = keys.remove(from);
2113 keys.insert(to, k);
2114 }
2115 }
2116 *echo.borrow_mut() = Some(conn.tokens_now());
2117 enqueue_event(rnode_to_id(node), Event::ListReorder { from, to });
2118 })
2119 },
2120 }),
2121 swipe: (self.swipe_leading.is_some() || self.swipe_trailing.is_some()).then(|| {
2122 ListSwipeDriver {
2123 actions_at: {
2126 let (leading, trailing) =
2127 (self.swipe_leading.clone(), self.swipe_trailing.clone());
2128 Box::new(move |i, edge| {
2129 let provider = match edge {
2130 day_spec::SwipeEdge::Leading => leading.as_ref(),
2131 day_spec::SwipeEdge::Trailing => trailing.as_ref(),
2132 };
2133 provider.map_or_else(Vec::new, |p| {
2134 p(i).iter()
2135 .map(|a| day_spec::ListSwipeAction {
2136 label: a.label.resolve(),
2137 destructive: a.destructive,
2138 tint: a.tint,
2139 symbol: a.symbol,
2140 })
2141 .collect()
2142 })
2143 })
2144 },
2145 performed: {
2148 let conn = conn.clone();
2149 Box::new(move |index, edge, action| {
2150 if index >= conn.len() {
2151 return;
2152 }
2153 enqueue_event(
2154 rnode_to_id(node),
2155 Event::ListSwipe {
2156 index,
2157 edge,
2158 action,
2159 },
2160 );
2161 })
2162 },
2163 }
2164 }),
2165 };
2166 install_list(node, driver);
2167
2168 let jump_follows = (self.follow_end.is_some(), following.clone());
2170 {
2175 let conn = conn.clone();
2176 let follow = self.follow_end;
2177 let sectioned = self.sections.is_some();
2178 let reselect = apply_selection.clone();
2179 let initial = {
2180 let refresh = refresh.clone();
2181 day_reactive::untrack(move || refresh())
2182 };
2183 list_reload(node);
2189 let last: RefCell<(Vec<u64>, Vec<u64>)> = RefCell::new(initial);
2191 watch(
2192 move || refresh(),
2193 move |rows: &(Vec<u64>, Vec<u64>), _| {
2194 let toks = &rows.0;
2195 let pending = pending_echo.borrow_mut().take();
2196 let is_echo = pending.as_ref().is_some_and(|e| e == toks)
2199 && !(has_empty && toks.is_empty());
2200 let old = last.replace(rows.clone());
2201 let unchanged = !conn.values_flow_by_reload() && old == *rows;
2203 if old.0.len() != toks.len() {
2204 end_armed.set(true);
2205 }
2206 let at_end = follow.is_some_and(|threshold| {
2209 following.get() || end_distance.get().is_none_or(|d| d <= threshold)
2210 });
2211 if !is_echo && pending.is_some() {
2212 let _ = conn.take_row_events();
2216 list_reload(node);
2217 if let Some(apply) = &reselect {
2218 apply();
2219 }
2220 } else if !is_echo && !unchanged {
2221 let sync = match conn.take_row_events() {
2225 Some(deltas) if !deltas.is_empty() => {
2226 let count = deltas.len();
2227 list_splice(node, deltas);
2228 day_core::ListSync::Spliced(count)
2229 }
2230 Some(_) => day_core::ListSync::Unchanged,
2231 None => day_core::list_sync(
2232 node,
2233 day_core::ListRows {
2234 tokens: &old.0,
2235 sections: sectioned.then_some(&old.1),
2236 },
2237 day_core::ListRows {
2238 tokens: toks,
2239 sections: sectioned.then_some(&rows.1),
2240 },
2241 ),
2242 };
2243 if at_end {
2244 following.set(true);
2247 list_scroll_to_end(node, sync != day_core::ListSync::Unchanged);
2248 }
2249 if let Some(apply) = &reselect {
2252 apply();
2253 }
2254 } else {
2255 let _ = conn.take_row_events();
2258 }
2259 },
2260 );
2261 }
2262
2263 if let Some(trigger) = self.scroll_to_end {
2267 let (follows, following) = jump_follows;
2268 watch(
2269 move || trigger.track(),
2270 move |(): &(), _| {
2271 if follows {
2274 following.set(true);
2275 }
2276 list_scroll_to_end(node, true);
2277 },
2278 );
2279 }
2280
2281 if let Some(command) = self.scroll_to_row {
2284 let RowCommand { pending, consume } = command;
2285 watch(
2286 move || pending(),
2287 move |target: &Option<RowTarget>, _| {
2288 if let Some(to) = *target {
2289 day_reactive::on_main(move || {
2292 list_scroll_to_row(node, to.row, to.align, to.animated);
2293 });
2294 consume(); }
2296 },
2297 );
2298 }
2299
2300 if let editing @ crate::Reactive::Dyn(_) =
2302 std::mem::replace(&mut self.editing, crate::Reactive::Const(false))
2303 {
2304 watch(
2305 move || editing.get(),
2306 move |on: &bool, old| {
2307 if old.is_some() {
2308 list_set_editing(node, *on);
2309 }
2310 },
2311 );
2312 }
2313
2314 if let (Some(sel), Some(apply)) = (self.selection.take(), apply_selection) {
2318 let first = Cell::new(true);
2319 day_reactive::bind(
2320 move || (sel.key)(),
2321 move |key: &Option<u64>| {
2322 let initial = first.replace(false);
2323 let picked = user_pick.take() == Some(*key);
2327 reveal.set(!initial && !picked && key.is_some());
2328 apply();
2329 },
2330 );
2331 }
2332
2333 if let Some(rows) = self.selected_rows {
2337 day_reactive::bind(
2338 move || rows(),
2339 move |rows: &Vec<usize>| {
2340 let rows = rows.clone();
2343 day_reactive::on_main(move || day_core::list_set_selected(node, rows));
2344 },
2345 );
2346 }
2347 node
2348 }
2349}
2350
2351#[cfg(feature = "model")]
2356mod model_rows {
2357 use super::*;
2358 use day_model::{Elem, Identified, Keyed, Source, Store};
2359
2360 pub struct ModelSlot<T: 'static> {
2365 store: Store<Keyed<T>>,
2366 cur: Signal<u64>,
2367 }
2368
2369 impl<T> Clone for ModelSlot<T> {
2370 fn clone(&self) -> Self {
2371 *self
2372 }
2373 }
2374 impl<T> Copy for ModelSlot<T> {}
2375
2376 impl<T: Identified + Clone + 'static> ModelSlot<T> {
2377 pub fn for_key(store: Store<Keyed<T>>, key: u64) -> ModelSlot<T> {
2380 ModelSlot {
2381 store,
2382 cur: Signal::new(key),
2383 }
2384 }
2385 pub fn rebind_key(&self, key: u64) {
2387 self.cur.set_if_changed(key);
2388 }
2389 }
2390
2391 impl<T: Identified + 'static> ModelSlot<T> {
2392 pub fn key(self) -> u64 {
2396 self.cur.get()
2397 }
2398 pub fn item(self) -> Elem<T> {
2401 self.store.elem(self.cur.get())
2402 }
2403 fn elem_now(self) -> Elem<T> {
2404 self.store.elem(self.cur.get_untracked())
2405 }
2406 }
2407
2408 impl<T: Identified + 'static> Source<T> for ModelSlot<T> {
2409 const DYNAMIC: bool = true;
2411 fn track_extra(self) {
2412 self.cur.track();
2413 }
2414 fn path(self) -> day_model::Path {
2415 self.elem_now().path()
2416 }
2417 fn node(self) -> day_model::NodeId {
2418 self.elem_now().node()
2419 }
2420 fn components(self, out: &mut Vec<u64>) {
2421 self.elem_now().components(out);
2422 }
2423 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
2424 self.elem_now().with_value_untracked(f)
2425 }
2426 fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
2427 self.elem_now().update_value(f)
2428 }
2429 fn bump_version(self) {
2430 self.elem_now().bump_version();
2431 }
2432 }
2433
2434 impl<T: Identified + 'static> SelectionKey for Elem<T> {
2436 fn selection_key(&self) -> u64 {
2437 self.key()
2438 }
2439 }
2440
2441 impl<T: Identified + Clone + 'static> RowSource for Store<Keyed<T>> {
2443 type Slot = ModelSlot<T>;
2444 type Ref = Elem<T>;
2445 type Conn = StoreConn<T>;
2446 fn connect(self) -> StoreConn<T> {
2447 StoreConn {
2448 store: self,
2449 rows: None,
2450 keys: RefCell::new(Vec::new()),
2451 }
2452 }
2453 }
2454
2455 pub struct Rows<T: 'static> {
2459 store: Store<Keyed<T>>,
2460 f: Rc<dyn Fn() -> Vec<u64>>,
2461 }
2462
2463 impl<T: Identified + Clone + 'static> RowSource for Rows<T> {
2464 type Slot = ModelSlot<T>;
2465 type Ref = Elem<T>;
2466 type Conn = StoreConn<T>;
2467 fn connect(self) -> StoreConn<T> {
2468 StoreConn {
2469 store: self.store,
2470 rows: Some(self.f),
2471 keys: RefCell::new(Vec::new()),
2472 }
2473 }
2474 }
2475
2476 pub trait StoreRows<T: 'static> {
2478 fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T>;
2479 }
2480
2481 impl<T: Identified + Clone + 'static> StoreRows<T> for Store<Keyed<T>> {
2482 fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T> {
2483 Rows {
2484 store: self,
2485 f: Rc::new(f),
2486 }
2487 }
2488 }
2489
2490 pub struct StoreConn<T: 'static> {
2492 store: Store<Keyed<T>>,
2493 rows: Option<Rc<dyn Fn() -> Vec<u64>>>,
2494 keys: RefCell<Vec<u64>>,
2495 }
2496
2497 impl<T: Identified + Clone + 'static> RowConn for StoreConn<T> {
2498 type Slot = ModelSlot<T>;
2499 type Ref = Elem<T>;
2500
2501 fn refresh(&self) -> Vec<u64> {
2502 let keys = match &self.rows {
2503 Some(f) => f(),
2504 None => self.store.keys(),
2505 };
2506 *self.keys.borrow_mut() = keys.clone();
2507 keys
2508 }
2509 fn len(&self) -> usize {
2510 self.keys.borrow().len()
2511 }
2512 fn token_at(&self, index: usize) -> u64 {
2513 self.keys.borrow().get(index).copied().unwrap_or(0)
2514 }
2515 fn tokens_now(&self) -> Vec<u64> {
2516 self.keys.borrow().clone()
2517 }
2518 fn slot_at(&self, index: usize) -> Option<ModelSlot<T>> {
2519 let key = self.keys.borrow().get(index).copied()?;
2520 Some(ModelSlot {
2521 store: self.store,
2522 cur: Signal::new(key),
2523 })
2524 }
2525 fn rebind(&self, slot: &ModelSlot<T>, index: usize) {
2526 if let Some(key) = self.keys.borrow().get(index).copied() {
2527 slot.cur.set_if_changed(key);
2530 }
2531 }
2532 fn select_ref(&self, index: usize) -> Option<Elem<T>> {
2533 let key = self.keys.borrow().get(index).copied()?;
2534 Some(self.store.elem(key))
2535 }
2536 fn values_flow_by_reload(&self) -> bool {
2537 false
2538 }
2539 fn commit_move(&self, from: usize, to: usize) {
2540 let mut keys = self.keys.borrow_mut();
2541 if from >= keys.len() || to >= keys.len() {
2542 return;
2543 }
2544 let k = keys.remove(from);
2545 keys.insert(to, k);
2546 }
2547 fn commit_delete(&self, index: usize) {
2548 let mut keys = self.keys.borrow_mut();
2549 if index >= keys.len() {
2550 return;
2551 }
2552 keys.remove(index);
2553 }
2554 }
2555
2556 pub struct StoreTree<T: 'static> {
2560 store: Store<Keyed<T>>,
2561 children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2562 }
2563
2564 pub trait StoreTrees<T: 'static> {
2566 fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T>;
2567 }
2568
2569 impl<T: Identified + Clone + 'static> StoreTrees<T> for Store<Keyed<T>> {
2570 fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T> {
2571 StoreTree {
2572 store: self,
2573 children: Rc::new(children),
2574 }
2575 }
2576 }
2577
2578 impl<T: Identified + Clone + 'static> super::NodeSource for StoreTree<T> {
2579 type Slot = ModelSlot<T>;
2580 type Key = u64;
2581 type Conn = StoreTreeConn<T>;
2582 fn connect(self) -> StoreTreeConn<T> {
2583 StoreTreeConn {
2584 store: self.store,
2585 children: self.children,
2586 shape: RefCell::new(super::TreeShape::default()),
2587 }
2588 }
2589 }
2590
2591 pub struct StoreTreeConn<T: 'static> {
2594 store: Store<Keyed<T>>,
2595 children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2596 shape: RefCell<super::TreeShape>,
2597 }
2598
2599 impl<T: Identified + Clone + 'static> super::TreeConn for StoreTreeConn<T> {
2600 type Slot = ModelSlot<T>;
2601 type Key = u64;
2602
2603 fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2604 let mut shape = super::TreeShape::default();
2605 let mut seen = HashSet::new();
2606 let mut stack: Vec<(Option<u64>, u64)> = (self.children)(None)
2609 .into_iter()
2610 .rev()
2611 .map(|k| (None, k))
2612 .collect();
2613 while let Some((parent, key)) = stack.pop() {
2614 if !seen.insert(key) {
2615 debug_assert!(false, "day: cycle or duplicate key in store tree");
2616 continue;
2617 }
2618 shape.tokens.push(key);
2619 shape.parents.insert(key, parent);
2620 shape.children.entry(parent).or_default().push(key);
2621 for child in (self.children)(Some(key)).into_iter().rev() {
2622 stack.push((Some(key), child));
2623 }
2624 }
2625 let fp = shape.fingerprint();
2626 *self.shape.borrow_mut() = shape;
2627 fp
2628 }
2629 fn tokens_now(&self) -> Vec<u64> {
2630 self.shape.borrow().tokens.clone()
2631 }
2632 fn children_len(&self, parent: Option<u64>) -> usize {
2633 self.shape
2634 .borrow()
2635 .children
2636 .get(&parent)
2637 .map(|v| v.len())
2638 .unwrap_or(0)
2639 }
2640 fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2641 self.shape
2642 .borrow()
2643 .children
2644 .get(&parent)
2645 .and_then(|v| v.get(index).copied())
2646 .unwrap_or(0)
2647 }
2648 fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2649 self.shape.borrow().parents.get(&token).copied()
2650 }
2651 fn key_of(&self, token: u64) -> Option<u64> {
2652 self.shape
2653 .borrow()
2654 .parents
2655 .contains_key(&token)
2656 .then_some(token)
2657 }
2658 fn token_of(&self, key: &u64) -> u64 {
2659 *key
2660 }
2661 fn slot_for(&self, token: u64) -> Option<ModelSlot<T>> {
2662 self.shape
2663 .borrow()
2664 .parents
2665 .contains_key(&token)
2666 .then(|| ModelSlot::for_key(self.store, token))
2667 }
2668 fn rebind(&self, slot: &ModelSlot<T>, token: u64) {
2669 slot.rebind_key(token);
2670 }
2671 fn values_flow_by_reload(&self) -> bool {
2672 false
2673 }
2674 }
2675}
2676
2677#[cfg(feature = "model")]
2678pub use model_rows::{ModelSlot, Rows, StoreRows, StoreTree, StoreTreeConn, StoreTrees};
2679
2680pub use day_spec::MoveVerdict;
2687
2688pub trait NodeSource {
2692 type Slot: Copy + 'static;
2694 type Key: Clone + Hash + Eq + 'static;
2696 type Conn: TreeConn<Slot = Self::Slot, Key = Self::Key>;
2697 fn connect(self) -> Self::Conn;
2698}
2699
2700pub trait TreeConn: 'static {
2703 type Slot: Copy + 'static;
2704 type Key: Clone + Hash + Eq + 'static;
2705
2706 fn refresh(&self) -> Vec<(u64, Option<u64>)>;
2710 fn tokens_now(&self) -> Vec<u64>;
2712 fn children_len(&self, parent: Option<u64>) -> usize;
2713 fn child_token(&self, parent: Option<u64>, index: usize) -> u64;
2714 fn parent_of(&self, token: u64) -> Option<Option<u64>>;
2716 fn key_of(&self, token: u64) -> Option<Self::Key>;
2717 fn token_of(&self, key: &Self::Key) -> u64;
2719 fn slot_for(&self, token: u64) -> Option<Self::Slot>;
2722 fn rebind(&self, slot: &Self::Slot, token: u64);
2724 fn values_flow_by_reload(&self) -> bool;
2727}
2728
2729pub fn branches<T, K>(
2734 f: impl Fn() -> Vec<T> + 'static,
2735 key_of: impl Fn(&T) -> K + 'static,
2736 parent_of: impl Fn(&T) -> Option<K> + 'static,
2737) -> Branches<T, K>
2738where
2739 T: Clone + 'static,
2740 K: Clone + Hash + Eq + 'static,
2741{
2742 Branches {
2743 f: Rc::new(f),
2744 key_of: Rc::new(key_of),
2745 parent_of: Rc::new(parent_of),
2746 }
2747}
2748
2749type ParentOf<T, K> = Rc<dyn Fn(&T) -> Option<K>>;
2751
2752pub struct Branches<T: 'static, K: 'static> {
2754 f: Rc<dyn Fn() -> Vec<T>>,
2755 key_of: Rc<dyn Fn(&T) -> K>,
2756 parent_of: ParentOf<T, K>,
2757}
2758
2759impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> NodeSource for Branches<T, K> {
2760 type Slot = ItemSlot<T, K>;
2761 type Key = K;
2762 type Conn = BranchesConn<T, K>;
2763 fn connect(self) -> BranchesConn<T, K> {
2764 BranchesConn {
2765 f: self.f,
2766 key_of: self.key_of,
2767 parent_of: self.parent_of,
2768 snapshot: RefCell::new(Vec::new()),
2769 shape: RefCell::new(TreeShape::default()),
2770 }
2771 }
2772}
2773
2774#[derive(Default)]
2776struct TreeShape {
2777 tokens: Vec<u64>,
2779 children: std::collections::HashMap<Option<u64>, Vec<u64>>,
2780 parents: std::collections::HashMap<u64, Option<u64>>,
2781 index_of: std::collections::HashMap<u64, usize>,
2783}
2784
2785impl TreeShape {
2786 fn fingerprint(&self) -> Vec<(u64, Option<u64>)> {
2787 self.tokens
2788 .iter()
2789 .map(|t| (*t, self.parents.get(t).copied().flatten()))
2790 .collect()
2791 }
2792}
2793
2794pub struct BranchesConn<T: 'static, K: 'static> {
2796 f: Rc<dyn Fn() -> Vec<T>>,
2797 key_of: Rc<dyn Fn(&T) -> K>,
2798 parent_of: ParentOf<T, K>,
2799 snapshot: RefCell<Vec<T>>,
2800 shape: RefCell<TreeShape>,
2801}
2802
2803impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> TreeConn for BranchesConn<T, K> {
2804 type Slot = ItemSlot<T, K>;
2805 type Key = K;
2806
2807 fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2808 let its = (self.f)();
2809 let mut shape = TreeShape::default();
2810 let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
2811 let present: HashSet<u64> = toks.iter().copied().collect();
2812 for (i, item) in its.iter().enumerate() {
2813 let tok = toks[i];
2814 let parent = (self.parent_of)(item)
2816 .map(|k| key_token(&k))
2817 .filter(|p| present.contains(p));
2818 shape.tokens.push(tok);
2819 shape.parents.insert(tok, parent);
2820 shape.children.entry(parent).or_default().push(tok);
2821 shape.index_of.insert(tok, i);
2822 }
2823 *self.snapshot.borrow_mut() = its;
2824 let fp = shape.fingerprint();
2825 *self.shape.borrow_mut() = shape;
2826 fp
2827 }
2828 fn tokens_now(&self) -> Vec<u64> {
2829 self.shape.borrow().tokens.clone()
2830 }
2831 fn children_len(&self, parent: Option<u64>) -> usize {
2832 self.shape
2833 .borrow()
2834 .children
2835 .get(&parent)
2836 .map_or(0, std::vec::Vec::len)
2837 }
2838 fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2839 self.shape
2840 .borrow()
2841 .children
2842 .get(&parent)
2843 .and_then(|v| v.get(index).copied())
2844 .unwrap_or(0)
2845 }
2846 fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2847 self.shape.borrow().parents.get(&token).copied()
2848 }
2849 fn key_of(&self, token: u64) -> Option<K> {
2850 let idx = self.shape.borrow().index_of.get(&token).copied()?;
2851 self.snapshot.borrow().get(idx).map(|t| (self.key_of)(t))
2852 }
2853 fn token_of(&self, key: &K) -> u64 {
2854 key_token(key)
2855 }
2856 fn slot_for(&self, token: u64) -> Option<ItemSlot<T, K>> {
2857 let idx = self.shape.borrow().index_of.get(&token).copied()?;
2858 let item = self.snapshot.borrow().get(idx).cloned()?;
2859 let key = (self.key_of)(&item);
2860 Some(ItemSlot {
2861 sig: Signal::new(item),
2862 key: Signal::new(key),
2863 })
2864 }
2865 fn rebind(&self, slot: &ItemSlot<T, K>, token: u64) {
2866 let Some(idx) = self.shape.borrow().index_of.get(&token).copied() else {
2867 return; };
2869 let Some(item) = self.snapshot.borrow().get(idx).cloned() else {
2870 return;
2871 };
2872 slot.key.set((self.key_of)(&item));
2873 slot.sig.set(item);
2874 }
2875 fn values_flow_by_reload(&self) -> bool {
2876 true
2877 }
2878}
2879
2880#[must_use]
2889pub struct Move<K: 'static> {
2890 moved: TreeMoveFn<K>,
2891 guard: Option<TreeGuardFn<K>>,
2892 enabled: Reactive<bool>,
2893}
2894
2895impl<K: 'static> Move<K> {
2896 pub fn new(moved: impl Fn(K, Option<K>, Option<usize>) + 'static) -> Move<K> {
2901 Move {
2902 moved: Rc::new(moved),
2903 guard: None,
2904 enabled: Reactive::Const(true),
2905 }
2906 }
2907 pub fn guard(
2911 mut self,
2912 g: impl Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict + 'static,
2913 ) -> Move<K> {
2914 self.guard = Some(Rc::new(g));
2915 self
2916 }
2917 pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Move<K> {
2920 self.enabled = on.into_reactive();
2921 self
2922 }
2923}
2924
2925#[must_use]
2926pub struct TreePiece<S: NodeSource> {
2927 source: Option<S>,
2928 build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
2929 row_height: RowHeight,
2930 indent: Option<f64>,
2931 section_headers: bool,
2932 on_expansion: Option<ExpansionFn<S::Key>>,
2933 expanded: Option<AnyBinding<HashSet<S::Key>>>,
2934 expandable: Option<KeyPredicate<S::Key>>,
2935 selected: Option<Rc<dyn Fn() -> Vec<S::Key>>>,
2936 on_selection: Option<SelectionKeysFn<S::Key>>,
2937 multi_select: bool,
2938 movable: bool,
2939 on_move: Option<TreeMoveFn<S::Key>>,
2940 move_guard: Option<TreeGuardFn<S::Key>>,
2941 type_ahead: Option<KeyTextFn<S::Key>>,
2942 reveal: Option<AnyBinding<Option<S::Key>>>,
2943 row_id: Option<KeyIdFn<S::Key>>,
2944 row_menu: Option<RowMenuEntriesFn<S::Key>>,
2945}
2946
2947type ExpansionFn<K> = Rc<dyn Fn(K, bool)>;
2949type TreeMoveFn<K> = Rc<dyn Fn(K, Option<K>, Option<usize>)>;
2950type TreeGuardFn<K> = Rc<dyn Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict>;
2952type KeyPredicate<K> = Rc<dyn Fn(&K) -> bool>;
2954type SelectionKeysFn<K> = Rc<dyn Fn(Vec<K>)>;
2956type KeyTextFn<K> = Rc<dyn Fn(&K) -> String>;
2958type KeyIdFn<K> = Rc<dyn Fn(&K) -> day_core::ElementId>;
2960type RowMenuEntriesFn<K> = Rc<dyn Fn(&K) -> Vec<MenuEntry>>;
2962
2963pub fn tree<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> TreePiece<S>
2967where
2968 S: NodeSource + 'static,
2969 P: Piece,
2970{
2971 TreePiece {
2972 source: Some(source),
2973 build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
2974 row_height: RowHeight::Automatic,
2975 indent: None,
2976 section_headers: false,
2977 on_expansion: None,
2978 expanded: None,
2979 expandable: None,
2980 selected: None,
2981 on_selection: None,
2982 multi_select: false,
2983 movable: false,
2984 on_move: None,
2985 move_guard: None,
2986 type_ahead: None,
2987 reveal: None,
2988 row_id: None,
2989 row_menu: None,
2990 }
2991}
2992
2993#[day_macros::builder(TreeBuilder<S>)]
2994impl<S: NodeSource + 'static> TreePiece<S> {
2995 pub fn row_height(mut self, h: RowHeight) -> Self {
2997 self.row_height = h;
2998 self
2999 }
3000 pub fn indent(mut self, pts: f64) -> Self {
3002 self.indent = Some(pts);
3003 self
3004 }
3005 pub fn section_headers(mut self) -> Self {
3009 self.section_headers = true;
3010 self
3011 }
3012 pub fn on_expansion(mut self, f: impl Fn(S::Key, bool) + 'static) -> Self {
3015 self.on_expansion = Some(Rc::new(f));
3016 self
3017 }
3018 pub fn expanded(mut self, set: impl Binding<HashSet<S::Key>>) -> Self {
3022 self.expanded = Some(AnyBinding::new(set));
3023 self
3024 }
3025 pub fn expandable(mut self, f: impl Fn(&S::Key) -> bool + 'static) -> Self {
3029 self.expandable = Some(Rc::new(f));
3030 self
3031 }
3032 pub fn selected(mut self, f: impl Fn() -> Vec<S::Key> + 'static) -> Self {
3036 self.selected = Some(Rc::new(f));
3037 self
3038 }
3039 pub fn on_selection(mut self, f: impl Fn(Vec<S::Key>) + 'static) -> Self {
3042 self.on_selection = Some(Rc::new(f));
3043 self
3044 }
3045 pub fn multi_select(mut self) -> Self {
3047 self.multi_select = true;
3048 self
3049 }
3050 pub fn movable(mut self, mv: Move<S::Key>) -> Self {
3058 self.movable = true;
3059 self.on_move = Some(mv.moved);
3060 let enabled = mv.enabled;
3063 let guard = mv.guard;
3064 self.move_guard = Some(Rc::new(move |k: &S::Key, p: Option<&S::Key>, i| {
3065 if !enabled.get_untracked() {
3066 return MoveVerdict::Deny;
3067 }
3068 match &guard {
3069 Some(g) => g(k, p, i),
3070 None => MoveVerdict::Allow,
3071 }
3072 }));
3073 self
3074 }
3075 pub fn type_ahead(mut self, f: impl Fn(&S::Key) -> String + 'static) -> Self {
3078 self.type_ahead = Some(Rc::new(f));
3079 self
3080 }
3081 pub fn reveal(mut self, target: impl Binding<Option<S::Key>>) -> Self {
3084 self.reveal = Some(AnyBinding::new(target));
3085 self
3086 }
3087 pub fn row_id(mut self, f: impl Fn(&S::Key) -> day_core::ElementId + 'static) -> Self {
3091 self.row_id = Some(Rc::new(f));
3092 self
3093 }
3094 pub fn row_context_menu(mut self, f: impl Fn(&S::Key) -> Vec<MenuEntry> + 'static) -> Self {
3100 self.row_menu = Some(Rc::new(f));
3101 self
3102 }
3103
3104 fn build_composed(mut self, cx: &mut BuildCx) -> RNode {
3111 fn visible<C: TreeConn + ?Sized>(
3114 conn: &C,
3115 is_open: &dyn Fn(u64) -> bool,
3116 parent: Option<u64>,
3117 depth: u16,
3118 out: &mut Vec<(u64, u16)>,
3119 ) {
3120 for i in 0..conn.children_len(parent) {
3121 let t = conn.child_token(parent, i);
3122 out.push((t, depth));
3123 if is_open(t) {
3124 visible(conn, is_open, Some(t), depth + 1, out);
3125 }
3126 }
3127 }
3128 const CHEVRON_W: f64 = 18.0;
3131 const DEFAULT_INDENT: f64 = 14.0;
3132
3133 let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
3134 let open_sig: Signal<HashSet<u64>> = Signal::new(HashSet::new());
3138 let expanded_sig = self.expanded;
3139
3140 let is_open: Rc<dyn Fn(u64) -> bool> = {
3142 let conn = conn.clone();
3143 match expanded_sig {
3144 Some(sig) => Rc::new(move |t| match conn.key_of(t) {
3145 Some(k) => sig.with(|s| s.contains(&k)),
3146 None => false,
3147 }),
3148 None => Rc::new(move |t| open_sig.with(|s| s.contains(&t))),
3149 }
3150 };
3151 let set_open: Rc<dyn Fn(u64, bool)> = {
3152 let (conn, is_open, changed) =
3153 (conn.clone(), is_open.clone(), self.on_expansion.clone());
3154 Rc::new(move |t, on| {
3155 if day_reactive::untrack(|| is_open(t)) == on {
3156 return;
3157 }
3158 let Some(key) = conn.key_of(t) else {
3159 return;
3160 };
3161 if let Some(sig) = expanded_sig {
3162 sig.update(|s| {
3163 if on {
3164 s.insert(key.clone());
3165 } else {
3166 s.remove(&key);
3167 }
3168 });
3169 } else {
3170 open_sig.update(|s| {
3171 if on {
3172 s.insert(t);
3173 } else {
3174 s.remove(&t);
3175 }
3176 });
3177 }
3178 if let Some(f) = &changed {
3179 f(key, on);
3180 }
3181 })
3182 };
3183
3184 let expandable_of: Rc<dyn Fn(u64) -> bool> = {
3186 let (conn, f) = (conn.clone(), self.expandable.clone());
3187 Rc::new(move |tok| match &f {
3188 Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
3189 None => conn.children_len(Some(tok)) > 0,
3190 })
3191 };
3192
3193 let flatten: Rc<dyn Fn() -> Vec<(u64, u16)>> = {
3194 let (conn, is_open) = (conn.clone(), is_open.clone());
3195 Rc::new(move || {
3196 let _shape = conn.refresh();
3197 let mut rows = Vec::new();
3198 visible(&*conn, &*is_open, None, 0, &mut rows);
3199 rows
3200 })
3201 };
3202
3203 let step = self.indent.unwrap_or(DEFAULT_INDENT);
3207 let build_row = {
3208 let (conn, user_row, row_id) =
3209 (conn.clone(), self.build_row.clone(), self.row_id.clone());
3210 let (is_open, expandable_of, set_open) =
3211 (is_open.clone(), expandable_of.clone(), set_open.clone());
3212 let row_menu = self.row_menu.clone();
3213 move |slot: ItemSlot<(u64, u16), u64>| -> AnyPiece {
3214 let (token0, depth0) = day_reactive::untrack(|| slot.get());
3215 let Some(user_slot) = conn.slot_for(token0) else {
3216 return AnyPiece::new(crate::spacer());
3218 };
3219 let depth = Rc::new(std::cell::Cell::new(f64::from(depth0)));
3220 let chevron = {
3221 let (is_open, expandable_of) = (is_open.clone(), expandable_of.clone());
3222 let (set_open, is_open_tap) = (set_open.clone(), is_open.clone());
3223 let expandable_tap = expandable_of.clone();
3224 crate::label(move || {
3225 let t = slot.get().0;
3226 if expandable_of(t) {
3230 if is_open(t) { "▼" } else { "▶" }
3231 } else {
3232 ""
3233 }
3234 .to_string()
3235 })
3236 .align(TextAlign::Center)
3237 .width(CHEVRON_W)
3238 .on_tap(move || {
3239 let t = day_reactive::untrack(|| slot.get().0);
3240 if expandable_tap(t) {
3241 set_open(t, !day_reactive::untrack(|| is_open_tap(t)));
3242 }
3243 })
3244 };
3245 let content = crate::row((chevron, user_row(user_slot)));
3246 let shell = TreeRowShell {
3247 depth: depth.clone(),
3248 step,
3249 content: AnyPiece::new(content),
3250 }
3251 .tweak({
3252 let (conn, row_id) = (conn.clone(), row_id.clone());
3253 move |n| {
3254 let id_conn = conn.clone();
3255 let set_ids = move |tok: u64| {
3256 if let Some(rid) = &row_id
3257 && let Some(k) = id_conn.key_of(tok)
3258 {
3259 with_tree(|t| t.set_id(n, rid(&k).as_str().to_owned()));
3260 }
3261 };
3262 set_ids(token0);
3263 watch(
3264 move || slot.get(),
3265 move |(tok, d), _| {
3266 conn.rebind(&user_slot, *tok);
3267 depth.set(f64::from(*d));
3268 set_ids(*tok);
3269 },
3270 );
3271 }
3272 });
3273 match &row_menu {
3274 Some(f) => {
3278 let (conn, f) = (conn.clone(), f.clone());
3279 AnyPiece::new(shell.context_menu(move |_p: day_spec::Point| {
3280 match conn.key_of(day_reactive::untrack(|| slot.get().0)) {
3281 Some(k) => f(&k),
3282 None => Vec::new(),
3283 }
3284 }))
3285 }
3286 None => AnyPiece::new(shell),
3287 }
3288 }
3289 };
3290
3291 let section_header: Rc<dyn Fn(u64) -> bool> = {
3292 let (conn, expandable, sections) =
3293 (conn.clone(), expandable_of.clone(), self.section_headers);
3294 Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3295 };
3296 let scroll_sig: Signal<Option<usize>> = Signal::new(None);
3297 let mut lst = list(
3298 items(
3299 {
3300 let flatten = flatten.clone();
3301 move || flatten()
3302 },
3303 |r: &(u64, u16)| r.0,
3304 ),
3305 build_row,
3306 )
3307 .row_height(self.row_height)
3308 .apply_if(self.multi_select, ListBuilder::multi_select)
3309 .scroll_to_row(scroll_sig);
3310 let selected_tokens = Signal::new(Vec::<u64>::new());
3313 let selection_revision = Signal::new(0u64);
3314 if self.on_selection.is_some() || (self.section_headers && self.selected.is_some()) {
3315 let conn = conn.clone();
3316 let header = section_header.clone();
3317 let callback = self.on_selection.clone();
3318 lst = lst.on_selection(move |toks: Vec<u64>| {
3319 if toks.iter().any(|t| header(*t)) {
3320 selection_revision.update(|r| *r += 1);
3321 return;
3322 }
3323 selected_tokens.set(toks.clone());
3324 if let Some(f) = &callback {
3325 f(toks.iter().filter_map(|t| conn.key_of(*t)).collect());
3326 }
3327 });
3328 }
3329 let mut repair_selection: Option<Rc<dyn Fn() -> Vec<usize>>> = None;
3330 if self.selected.is_some() || (self.section_headers && self.on_selection.is_some()) {
3331 let (conn, flatten, selected) = (conn.clone(), flatten.clone(), self.selected.clone());
3332 let section_header = section_header.clone();
3333 let rows: Rc<dyn Fn() -> Vec<usize>> = Rc::new(move || {
3334 let rows = flatten();
3335 let want: HashSet<u64> = match &selected {
3336 Some(sel) => sel().iter().map(|k| conn.token_of(k)).collect(),
3337 None => selected_tokens.get().into_iter().collect(),
3338 };
3339 rows.iter()
3340 .enumerate()
3341 .filter(|(_, r)| want.contains(&r.0) && !section_header(r.0))
3342 .map(|(i, _)| i)
3343 .collect()
3344 });
3345 repair_selection = Some(rows.clone());
3346 lst = lst.selected_rows(move || rows());
3347 }
3348 let node = lst.build(cx);
3349 if let Some(rows) = repair_selection {
3350 day_reactive::bind(
3351 move || selection_revision.get(),
3352 move |revision| {
3353 if *revision != 0 {
3354 let rows = day_reactive::untrack(|| rows());
3355 day_reactive::on_main(move || day_core::list_set_selected(node, rows));
3356 }
3357 },
3358 );
3359 }
3360
3361 {
3364 let (on_move, conn_ev, set_open) =
3365 (self.on_move.clone(), conn.clone(), set_open.clone());
3366 cx.on(node, move |ev| match ev {
3367 Event::TreeExpanded { token, expanded } => set_open(*token, *expanded),
3368 Event::TreeMove {
3369 token,
3370 parent,
3371 index,
3372 } => {
3373 if let Some(f) = &on_move
3374 && let Some(key) = conn_ev.key_of(*token)
3375 {
3376 f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3377 }
3378 }
3379 _ => {}
3380 });
3381 }
3382
3383 let driver = TreeDriver {
3385 section_header: {
3386 let f = section_header.clone();
3387 Box::new(move |t| f(t))
3388 },
3389 row_height: self.row_height,
3390 children_len: {
3391 let conn = conn.clone();
3392 Box::new(move |p| conn.children_len(p))
3393 },
3394 child_token: {
3395 let conn = conn.clone();
3396 Box::new(move |p, i| conn.child_token(p, i))
3397 },
3398 expandable: {
3399 let f = expandable_of.clone();
3400 Box::new(move |t| f(t))
3401 },
3402 expanded: {
3403 let is_open = is_open.clone();
3404 Box::new(move |t| day_reactive::untrack(|| is_open(t)))
3405 },
3406 build: Box::new(|_tok, _anchor| TreeBuiltRow {
3409 scope: Scope::child(),
3410 rebind: Rc::new(|_| {}),
3411 }),
3412 type_select_text: Box::new(|_| String::new()),
3413 resolve_row: {
3414 let (conn, row_id) = (conn.clone(), self.row_id.clone());
3415 Box::new(move |id| {
3416 let rid = row_id.as_ref()?;
3417 conn.tokens_now()
3418 .into_iter()
3419 .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3420 })
3421 },
3422 row_menu: None,
3423 moves: self.movable.then(|| {
3424 let can = {
3425 let (conn, expandable_of, guard) =
3426 (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3427 move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3428 let Some(key) = conn.key_of(tok) else {
3429 return MoveVerdict::Deny;
3430 };
3431 let parent_key = match parent {
3432 Some(p) => {
3433 if p == tok || !expandable_of(p) {
3434 return MoveVerdict::Deny;
3435 }
3436 let mut cur = Some(p);
3437 while let Some(c) = cur {
3438 if c == tok {
3439 return MoveVerdict::Deny;
3440 }
3441 cur = conn.parent_of(c).flatten();
3442 }
3443 match conn.key_of(p) {
3444 Some(k) => Some(k),
3445 None => return MoveVerdict::Deny,
3446 }
3447 }
3448 None => None,
3449 };
3450 match &guard {
3451 Some(g) => g(&key, parent_key.as_ref(), index),
3452 None => MoveVerdict::Allow,
3453 }
3454 }
3455 };
3456 let can_commit = can.clone();
3457 TreeMovesDriver {
3458 can_move: Box::new(can),
3459 moved: Box::new(move |t, p, i| {
3460 if can_commit(t, p, i) == MoveVerdict::Deny {
3461 return;
3462 }
3463 enqueue_event(
3464 rnode_to_id(node),
3465 Event::TreeMove {
3466 token: t,
3467 parent: p,
3468 index: i,
3469 },
3470 );
3471 }),
3472 }
3473 }),
3474 };
3475 install_tree(node, driver);
3476
3477 if let Some(sig) = self.reveal {
3480 let (conn, set_open, flatten) = (conn.clone(), set_open.clone(), flatten.clone());
3481 watch(
3482 move || sig.get(),
3483 move |key: &Option<S::Key>, _| {
3484 let Some(key) = key else { return };
3485 let tok = conn.token_of(key);
3486 let mut cur = conn.parent_of(tok).flatten();
3487 while let Some(p) = cur {
3488 set_open(p, true);
3489 cur = conn.parent_of(p).flatten();
3490 }
3491 let row = day_reactive::untrack(|| flatten())
3492 .iter()
3493 .position(|r| r.0 == tok);
3494 if let Some(row) = row {
3495 scroll_sig.set(Some(row));
3496 }
3497 },
3498 );
3499 }
3500
3501 node
3502 }
3503}
3504
3505struct TreeIndent {
3509 depth: Rc<std::cell::Cell<f64>>,
3510 step: f64,
3511}
3512
3513impl Layout for TreeIndent {
3514 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
3515 let pad = self.depth.get() * self.step;
3516 let child_p = Proposal::new(p.width.map(|w| (w - pad).max(0.0)), p.height);
3517 let s = match children.first() {
3518 Some(&c) => cx.measure_child(c, child_p),
3519 None => Size::ZERO,
3520 };
3521 Size::new(s.width + pad, s.height)
3522 }
3523 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
3524 if let Some(&c) = children.first() {
3525 let pad = (self.depth.get() * self.step).min(bounds.size.width);
3526 let inner = Size::new(bounds.size.width - pad, bounds.size.height);
3527 let _ = cx.measure_child(c, Proposal::exact(inner));
3528 cx.place_child(c, Rect::new(pad, 0.0, inner.width, inner.height));
3529 }
3530 }
3531}
3532
3533struct TreeRowShell {
3536 depth: Rc<std::cell::Cell<f64>>,
3537 step: f64,
3538 content: AnyPiece,
3539}
3540
3541impl Piece for TreeRowShell {
3542 fn build(self, cx: &mut BuildCx) -> RNode {
3543 let w = cx.native(
3547 kinds::CONTAINER,
3548 &ContainerProps {
3549 corner_radius: 0.0,
3550 clips: false,
3551 role: None,
3552 ..Default::default()
3553 },
3554 Rc::new(TreeIndent {
3555 depth: self.depth,
3556 step: self.step,
3557 }),
3558 Flex {
3559 grow_w: true,
3560 ..Default::default()
3561 },
3562 Boundary::No,
3563 );
3564 cx.under(w, |cx| {
3565 let _ = self.content.build(cx);
3566 });
3567 w
3568 }
3569}
3570
3571impl<S: NodeSource + 'static> Piece for TreePiece<S> {
3572 fn build(mut self, cx: &mut BuildCx) -> RNode {
3573 let cap = if self.section_headers && !self.multi_select {
3579 day_spec::Cap::TreeSections
3580 } else {
3581 day_spec::Cap::Tree
3582 };
3583 if day_core::capability(cap) != day_spec::Support::Native {
3584 return self.build_composed(cx);
3585 }
3586 let props = TreeProps {
3587 section_headers: self.section_headers,
3588 row_height: self.row_height,
3589 selectable: self.selected.is_some() || self.on_selection.is_some(),
3590 multi_select: self.multi_select,
3591 movable: self.movable,
3592 indent: self.indent,
3593 };
3594 let node = cx.leaf(
3595 kinds::TREE,
3596 &props,
3597 Flex {
3598 grow_w: true,
3599 grow_h: true,
3600 ..Default::default()
3601 },
3602 );
3603
3604 let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
3605
3606 let open_tokens: Rc<RefCell<HashSet<u64>>> = Rc::new(RefCell::new(HashSet::new()));
3610
3611 let expandable_of: Rc<dyn Fn(u64) -> bool> = {
3613 let (conn, f) = (conn.clone(), self.expandable.clone());
3614 Rc::new(move |tok| match &f {
3615 Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
3616 None => conn.children_len(Some(tok)) > 0,
3617 })
3618 };
3619
3620 let section_header: Rc<dyn Fn(u64) -> bool> = {
3621 let (conn, expandable, sections) =
3622 (conn.clone(), expandable_of.clone(), self.section_headers);
3623 Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3624 };
3625 {
3627 let (on_selection, expanded_sig) = (self.on_selection.clone(), self.expanded);
3628 let (on_move, conn_ev, open) =
3629 (self.on_move.clone(), conn.clone(), open_tokens.clone());
3630 let changed = self.on_expansion.clone();
3631 let header = section_header.clone();
3632 cx.on(node, move |ev| match ev {
3633 Event::TreeSelection(tokens) => {
3634 if let Some(f) = &on_selection {
3635 f(tokens
3636 .iter()
3637 .filter(|t| !header(**t))
3638 .filter_map(|t| conn_ev.key_of(*t))
3639 .collect());
3640 }
3641 }
3642 Event::TreeExpanded { token, expanded } => {
3643 let Some(key) = conn_ev.key_of(*token) else {
3644 return;
3645 };
3646 let was = expanded_sig.map_or_else(
3647 || open.borrow().contains(token),
3648 |sig| day_reactive::untrack(|| sig.with(|s| s.contains(&key))),
3649 );
3650 if was == *expanded {
3651 return;
3652 }
3653 if let Some(sig) = &expanded_sig {
3654 if let Some(key) = conn_ev.key_of(*token) {
3660 sig.update(|set| {
3661 if *expanded {
3662 set.insert(key.clone());
3663 } else {
3664 set.remove(&key);
3665 }
3666 });
3667 }
3668 } else {
3669 if *expanded {
3674 open.borrow_mut().insert(*token);
3675 } else {
3676 open.borrow_mut().remove(token);
3677 }
3678 day_core::tree_set_expanded(node, *token, *expanded);
3679 }
3680 if let Some(f) = &changed {
3681 f(key, *expanded);
3682 }
3683 }
3684 Event::TreeMove {
3685 token,
3686 parent,
3687 index,
3688 } => {
3689 if let Some(f) = &on_move
3690 && let Some(key) = conn_ev.key_of(*token)
3691 {
3692 f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3693 }
3694 }
3695 _ => {}
3696 });
3697 }
3698
3699 let driver = TreeDriver {
3701 section_header: {
3702 let f = section_header.clone();
3703 Box::new(move |t| f(t))
3704 },
3705 row_height: self.row_height,
3706 children_len: {
3707 let conn = conn.clone();
3708 Box::new(move |p| conn.children_len(p))
3709 },
3710 child_token: {
3711 let conn = conn.clone();
3712 Box::new(move |p, i| conn.child_token(p, i))
3713 },
3714 expandable: {
3715 let f = expandable_of.clone();
3716 Box::new(move |t| f(t))
3717 },
3718 expanded: {
3719 let open = open_tokens.clone();
3720 Box::new(move |t| open.borrow().contains(&t))
3721 },
3722 build: {
3723 let (conn, build_row, row_id) =
3724 (conn.clone(), self.build_row.clone(), self.row_id.clone());
3725 Box::new(move |token, anchor| {
3726 let scope = Scope::child();
3727 let (conn, build_row, row_id) =
3728 (conn.clone(), build_row.clone(), row_id.clone());
3729 let rebind = scope.enter(move || {
3730 let Some(slot) = conn.slot_for(token) else {
3733 return Rc::new(|_: u64| {}) as Rc<dyn Fn(u64)>;
3734 };
3735 let mut rowcx = BuildCx::new(anchor);
3736 let root = build_row(slot).build(&mut rowcx);
3737 if let Some(rid) = &row_id
3738 && let Some(k) = conn.key_of(token)
3739 {
3740 with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3741 }
3742 Rc::new(move |tok: u64| {
3745 conn.rebind(&slot, tok);
3746 if let Some(rid) = &row_id
3747 && let Some(k) = conn.key_of(tok)
3748 {
3749 with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3750 }
3751 }) as Rc<dyn Fn(u64)>
3752 });
3753 TreeBuiltRow { scope, rebind }
3754 })
3755 },
3756 type_select_text: {
3757 let (conn, f) = (conn.clone(), self.type_ahead.clone());
3758 Box::new(move |tok| match &f {
3759 Some(f) => conn.key_of(tok).map_or_default(|k| f(&k)),
3760 None => String::new(),
3761 })
3762 },
3763 resolve_row: {
3764 let (conn, row_id) = (conn.clone(), self.row_id.clone());
3765 Box::new(move |id| {
3766 let rid = row_id.as_ref()?;
3767 conn.tokens_now()
3768 .into_iter()
3769 .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3770 })
3771 },
3772 row_menu: self.row_menu.clone().map(|f| {
3773 let conn = conn.clone();
3776 let last: Rc<RefCell<Option<Scope>>> = Rc::default();
3777 {
3778 let last = last.clone();
3779 Scope::current().on_cleanup(move || {
3780 if let Some(s) = last.borrow_mut().take() {
3781 s.dispose();
3782 }
3783 });
3784 }
3785 Box::new(move |tok: u64| {
3786 let Some(key) = conn.key_of(tok) else {
3787 return Vec::new();
3788 };
3789 if let Some(s) = last.borrow_mut().take() {
3790 s.dispose();
3791 }
3792 let scope = Scope::child();
3793 let items = scope.enter(|| crate::menus::lower_menu_scoped(f(&key)));
3794 *last.borrow_mut() = Some(scope);
3795 items
3796 }) as day_core::tree_driver::RowMenuFn
3797 }),
3798 moves: self.movable.then(|| {
3799 let can = {
3803 let (conn, expandable_of, guard) =
3804 (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3805 move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3806 let Some(key) = conn.key_of(tok) else {
3807 return MoveVerdict::Deny;
3808 };
3809 let parent_key = match parent {
3810 Some(p) => {
3811 if p == tok || !expandable_of(p) {
3812 return MoveVerdict::Deny;
3813 }
3814 let mut cur = Some(p);
3816 while let Some(c) = cur {
3817 if c == tok {
3818 return MoveVerdict::Deny;
3819 }
3820 cur = conn.parent_of(c).flatten();
3821 }
3822 match conn.key_of(p) {
3823 Some(k) => Some(k),
3824 None => return MoveVerdict::Deny,
3825 }
3826 }
3827 None => None,
3828 };
3829 match &guard {
3830 Some(g) => g(&key, parent_key.as_ref(), index),
3831 None => MoveVerdict::Allow,
3832 }
3833 }
3834 };
3835 let can_commit = can.clone();
3836 TreeMovesDriver {
3837 can_move: Box::new(can),
3838 moved: Box::new(move |t, p, i| {
3841 if can_commit(t, p, i) == MoveVerdict::Deny {
3842 return;
3843 }
3844 enqueue_event(
3845 rnode_to_id(node),
3846 Event::TreeMove {
3847 token: t,
3848 parent: p,
3849 index: i,
3850 },
3851 );
3852 }),
3853 }
3854 }),
3855 };
3856 install_tree(node, driver);
3857
3858 let apply_expansion = {
3862 let (conn, open) = (conn.clone(), open_tokens.clone());
3863 let expanded_sig = self.expanded;
3864 move || {
3865 let desired: HashSet<u64> = match &expanded_sig {
3866 Some(sig) => {
3867 let conn = &conn;
3868 sig.get_untracked()
3869 .iter()
3870 .map(|k| conn.token_of(k))
3871 .collect()
3872 }
3873 None => open.borrow().clone(),
3874 };
3875 let present: HashSet<u64> = conn.tokens_now().into_iter().collect();
3876 let mut ordered: Vec<u64> = desired
3879 .iter()
3880 .filter(|t| present.contains(t))
3881 .copied()
3882 .collect();
3883 let depth_of = |mut t: u64| {
3884 let mut d = 0usize;
3885 while let Some(Some(p)) = conn.parent_of(t) {
3886 d += 1;
3887 t = p;
3888 }
3889 d
3890 };
3891 ordered.sort_by_key(|t| depth_of(*t));
3892 for t in ordered {
3893 tree_set_expanded(node, t, true);
3894 }
3895 open.borrow_mut().clone_from(&desired);
3896 }
3897 };
3898 let apply_selection = {
3899 let (conn, selected) = (conn.clone(), self.selected.clone());
3900 move || {
3901 if let Some(sel) = &selected {
3902 let keys = day_reactive::untrack(|| sel());
3903 let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3904 tree_set_selected(node, toks);
3905 }
3906 }
3907 };
3908 {
3909 let conn2 = conn.clone();
3910 let initial = {
3911 let conn = conn.clone();
3912 day_reactive::untrack(move || conn.refresh())
3913 };
3914 tree_reload(node);
3918 apply_expansion();
3919 apply_selection();
3920 let last: RefCell<Vec<(u64, Option<u64>)>> = RefCell::new(initial);
3921 let (apply_expansion, apply_selection) =
3922 (apply_expansion.clone(), apply_selection.clone());
3923 let conn3 = conn.clone();
3924 watch(
3925 move || conn2.refresh(),
3926 move |shape: &Vec<(u64, Option<u64>)>, _| {
3927 let unchanged = !conn3.values_flow_by_reload() && *last.borrow() == *shape;
3928 (*last.borrow_mut()).clone_from(shape);
3929 if unchanged {
3930 return;
3931 }
3932 tree_reload(node);
3933 apply_expansion();
3934 apply_selection();
3935 },
3936 );
3937 }
3938
3939 if let Some(sig) = self.expanded {
3941 let (conn, open) = (conn.clone(), open_tokens.clone());
3942 watch(
3943 move || sig.get(),
3944 move |set: &HashSet<S::Key>, _| {
3945 let desired: HashSet<u64> = set.iter().map(|k| conn.token_of(k)).collect();
3946 let current = open.borrow().clone();
3947 for t in desired.difference(¤t) {
3948 tree_set_expanded(node, *t, true);
3949 }
3950 for t in current.difference(&desired) {
3951 tree_set_expanded(node, *t, false);
3952 }
3953 open.borrow_mut().clone_from(&desired);
3954 },
3955 );
3956 }
3957
3958 if let Some(sel) = self.selected.clone() {
3961 let conn = conn.clone();
3962 watch(
3963 move || sel(),
3964 move |keys: &Vec<S::Key>, _| {
3965 let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3966 tree_set_selected(node, toks);
3967 },
3968 );
3969 }
3970
3971 if let Some(sig) = self.reveal {
3973 let (conn, open, expanded_sig) = (conn.clone(), open_tokens.clone(), self.expanded);
3974 watch(
3975 move || sig.get(),
3976 move |key: &Option<S::Key>, _| {
3977 let Some(key) = key else { return };
3978 let tok = conn.token_of(key);
3979 let mut ancestors = Vec::new();
3980 let mut cur = conn.parent_of(tok).flatten();
3981 while let Some(p) = cur {
3982 ancestors.push(p);
3983 cur = conn.parent_of(p).flatten();
3984 }
3985 for p in ancestors.iter().rev() {
3986 tree_set_expanded(node, *p, true);
3987 open.borrow_mut().insert(*p);
3988 if let Some(sig) = &expanded_sig
3989 && let Some(k) = conn.key_of(*p)
3990 {
3991 sig.update(|set| {
3992 set.insert(k.clone());
3993 });
3994 }
3995 }
3996 tree_reveal(node, tok);
3997 },
3998 );
3999 }
4000
4001 node
4002 }
4003}
4004
4005pub fn test_host<P: Piece>(content: impl Fn() -> P + 'static) -> impl Piece {
4023 let content = Rc::new(content);
4024 piece_fn(move |cx| {
4025 let generation = Signal::new(0u64);
4028 day_core::conformance::set_host(Some(Rc::new(move || generation.update(|g| *g += 1))));
4029 Scope::current().on_cleanup(|| day_core::conformance::set_host(None));
4030 each(
4031 items(move || vec![generation.get()], |g: &u64| *g),
4032 move |_| match day_core::conformance::active() {
4033 Some(case) => guarded_page(case),
4034 None => AnyPiece::new(content()),
4035 },
4036 )
4037 .build(cx)
4038 })
4039}
4040
4041pub fn guarded_page(case: day_core::conformance::Case) -> AnyPiece {
4044 AnyPiece::new(piece_fn(move |cx| {
4045 let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4046 case.build_page().map(|page| page.build(&mut *cx))
4047 }));
4048 match built {
4049 Ok(Some(root)) => root,
4050 Ok(None) => crate::label("").build(cx),
4051 Err(payload) => {
4052 let message = day_core::conformance::panic_message(payload.as_ref());
4053 day_core::conformance::note_page_panic(message.clone());
4054 crate::label(format!("panicked: {message}")).build(cx)
4055 }
4056 }
4057 }))
4058}
4059
4060#[cfg(feature = "conformance")]
4061pub(crate) mod conformance {
4062 use day_core::conformance::{Case, Drive, Fail, FrameExpect};
4063 use day_geometry::Insets;
4064 use day_reactive::Signal;
4065 use day_spec::props::RowHeight;
4066 use day_spec::{Cap, Font, kinds};
4067
4068 use crate::*;
4069
4070 fn names_list(names: Signal<Vec<String>>) -> List<Items<String, String>> {
4072 list(
4073 items(move || names.get(), |n: &String| n.clone()),
4074 |row: ItemSlot<String, String>| {
4075 label(move || row.get())
4078 .id_of(move || day_core::id!(conformance_row, row.get()))
4079 .padding(Insets::symmetric(12.0, 6.0))
4080 },
4081 )
4082 .row_height(RowHeight::Uniform(32.0))
4083 }
4084
4085 fn names(list: &[&str]) -> Signal<Vec<String>> {
4086 Signal::new(list.iter().map(std::string::ToString::to_string).collect())
4087 }
4088
4089 #[day_macros::test(day_core)]
4092 fn list_items_show_their_parts() -> Case {
4093 Case::new()
4094 .proves(kinds::LIST_ITEM)
4095 .proves_cap(Cap::ListItem)
4096 .requires(Cap::ListItem)
4097 .page(|| {
4098 let done = Signal::new(false);
4099 let rows = names(&["Milk", "Bread"]);
4100 column((
4101 button("Done")
4102 .action(move || done.update(|d| *d = !*d))
4103 .id(day_core::id!(toggle_done)),
4104 list(
4105 items(move || rows.get(), |n: &String| n.clone()),
4106 move |row: ItemSlot<String, String>| {
4107 list_item(move || row.get())
4108 .subtitle("aisle 4")
4109 .checked(move || done.get())
4110 .id_of(move || day_core::id!(conformance_item, row.get()))
4111 },
4112 )
4113 .height(200.0),
4114 ))
4115 })
4116 .drive(|d: Drive| async move {
4117 d.assert_visible("conformance_item:Milk").await?;
4118 d.tap("toggle_done").await?;
4119 d.assert_visible("conformance_item:Bread").await
4120 })
4121 }
4122
4123 #[day_macros::test(day_core)]
4125 fn list_rows_realize() -> Case {
4126 Case::new()
4127 .proves_duty("attach_list")
4128 .proves_duty("adopt")
4129 .proves(kinds::LIST)
4130 .proves(kinds::LIST_CELL)
4131 .page(|| {
4132 names_list(names(&["Alpha", "Beta", "Gamma"]))
4133 .id(day_core::id!(list))
4134 .height(200.0)
4135 })
4136 .drive(|d: Drive| async move {
4137 d.assert_text("conformance_row:Alpha", "Alpha").await?;
4138 d.assert_text("conformance_row:Gamma", "Gamma").await
4139 })
4140 }
4141
4142 #[day_macros::test(day_core)]
4144 fn list_follows_source() -> Case {
4145 Case::new()
4146 .proves_duty("release")
4147 .proves(kinds::LIST)
4148 .page(|| {
4149 let rows = names(&["Alpha", "Beta"]);
4150 column((
4151 button("Add")
4152 .action(move || rows.update(|v| v.push("Delta".into())))
4153 .id(day_core::id!(add)),
4154 button("Drop")
4155 .action(move || rows.update(|v| v.retain(|n| n != "Alpha")))
4156 .id(day_core::id!(drop)),
4157 names_list(rows).id(day_core::id!(list)).height(200.0),
4158 ))
4159 })
4160 .drive(|d: Drive| async move {
4161 d.assert_missing("conformance_row:Delta").await?;
4162 d.tap("add").await?;
4163 d.assert_text("conformance_row:Delta", "Delta").await?;
4164 d.tap("drop").await?;
4165 d.assert_missing("conformance_row:Alpha").await?;
4166 d.assert_text("conformance_row:Beta", "Beta").await
4167 })
4168 }
4169
4170 #[day_macros::test(day_core)]
4173 fn list_append_then_scroll() -> Case {
4174 Case::new()
4175 .proves(kinds::LIST)
4176 .page(|| {
4177 let rows = names(&[]);
4178 let scroll = Signal::new(None);
4179 column((
4180 button("Append").id(day_core::id!(append)).action(move || {
4181 rows.update(|rows| rows.push(format!("Item {}", rows.len())));
4182 scroll.set(Some(rows.with(|rows| rows.len() - 1)));
4183 }),
4184 names_list(rows)
4185 .scroll_to_row(scroll)
4186 .id(day_core::id!(list))
4187 .height(120.0),
4188 ))
4189 })
4190 .drive(|d: Drive| async move {
4191 for index in 0..8 {
4193 d.tap("append").await?;
4194 d.assert_visible(&format!("conformance_row:Item%20{index}"))
4195 .await?;
4196 }
4197 Ok(())
4198 })
4199 }
4200
4201 const SIZED: [(&str, Font, &str); 5] = [
4203 ("small", Font::Caption2, "Small print"),
4204 ("large", Font::LargeTitle, "Large"),
4205 ("body", Font::Body, "Body text"),
4206 (
4207 "wrap",
4208 Font::Footnote,
4209 "A footnote long enough to wrap onto three lines or more in a narrow list, \
4210 whatever the platform's type scale, so its row is several lines tall",
4211 ),
4212 ("end", Font::Body, "End"),
4213 ];
4214
4215 const GROWN: &str = "Body text that grew long enough to wrap onto several lines, \
4217 the way a row does when its content changes after it was first sized";
4218
4219 fn sized_list(grown: Signal<bool>) -> List<Items<&'static str, &'static str>> {
4222 list(
4223 items(|| SIZED.iter().map(|r| r.0).collect(), |k: &&str| *k),
4224 move |slot: ItemSlot<&'static str, &'static str>| {
4225 let arm = |key: &'static str, font: Font, text: &'static str| {
4228 when(
4229 move || slot.get() == key,
4230 move || {
4231 label(move || {
4232 if key == "body" && grown.get() {
4233 GROWN.to_string()
4234 } else {
4235 text.to_string()
4236 }
4237 })
4238 .font(font)
4239 .id_of(move || day_core::id!(sized, slot.get()))
4240 },
4241 )
4242 };
4243 let [a, b, c, d, e] = SIZED;
4244 column((
4245 arm(a.0, a.1, a.2),
4246 arm(b.0, b.1, b.2),
4247 arm(c.0, c.1, c.2),
4248 arm(d.0, d.1, d.2),
4249 arm(e.0, e.1, e.2),
4250 ))
4251 .spacing(0.0)
4252 },
4253 )
4254 .row_height(RowHeight::Automatic)
4255 .no_separators()
4256 }
4257
4258 struct SizedRow {
4261 key: &'static str,
4262 content: f64,
4263 row: f64,
4264 top: f64,
4265 }
4266
4267 fn sized_rows() -> Result<Vec<SizedRow>, Fail> {
4273 day_core::try_with_tree(|t| {
4274 SIZED
4275 .iter()
4276 .map(|(key, ..)| {
4277 let id = format!("sized:{key}");
4278 let node = t
4279 .find_by_id(&id)
4280 .ok_or_else(|| Fail(format!("no element {id:?}")))?;
4281 let content = t
4282 .node_frame(node)
4283 .ok_or_else(|| Fail(format!("{id:?} has no Day frame")))?;
4284 let mut anchor = node;
4285 while t.node_kind(anchor) != Some(kinds::LIST_CELL) {
4286 anchor = t
4287 .parent_of(anchor)
4288 .ok_or_else(|| Fail(format!("{id:?} is not inside a list cell")))?;
4289 }
4290 let row = t
4291 .node_frame(anchor)
4292 .ok_or_else(|| Fail(format!("{id:?}'s row has no Day frame")))?;
4293 let native = t
4294 .read_native(node)
4295 .and_then(|n| n.frame)
4296 .ok_or_else(|| Fail(format!("{id:?} has no native frame")))?;
4297 Ok(SizedRow {
4298 key,
4299 content: content.size.height,
4300 row: row.size.height,
4301 top: native.origin.y,
4302 })
4303 })
4304 .collect()
4305 })
4306 .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
4307 }
4308
4309 fn rows_fit() -> Result<Vec<(&'static str, f64)>, Fail> {
4317 let rows = sized_rows()?;
4318 let spare = |r: &SizedRow| (r.row - r.content) / 2.0;
4319 let expected = |a: &SizedRow, b: &SizedRow| a.row - spare(a) + spare(b);
4320 let chrome = (rows[1].top - rows[0].top) - expected(&rows[0], &rows[1]);
4321 for pair in rows.windows(2) {
4322 let (this, next) = (&pair[0], &pair[1]);
4323 let pitch = next.top - this.top;
4324 if pitch + 0.5 < this.content {
4325 return Err(Fail(format!(
4326 "row {:?} is {:.1} tall but the next row starts {pitch:.1} below it: the \
4327 native row clips its content",
4328 this.key, this.content
4329 )));
4330 }
4331 let want = expected(this, next) + chrome;
4332 if (pitch - want).abs() > 1.5 {
4333 return Err(Fail(format!(
4334 "row {:?} holds {:.1} of content in a {:.1} row, and the next row starts \
4335 {pitch:.1} below it where {want:.1} was expected (the first row's chrome \
4336 allowance is {chrome:.1}): the native row did not take its content's height",
4337 this.key, this.content, this.row
4338 )));
4339 }
4340 }
4341 Ok(rows.into_iter().map(|r| (r.key, r.content)).collect())
4342 }
4343
4344 fn height_of(rows: &[(&str, f64)], key: &str) -> f64 {
4345 rows.iter().find(|r| r.0 == key).map_or(0.0, |r| r.1)
4346 }
4347
4348 #[day_macros::test(day_core)]
4351 fn list_rows_size_to_content() -> Case {
4352 Case::new()
4353 .proves(kinds::LIST)
4354 .proves(kinds::LIST_CELL)
4355 .page(|| {
4356 let grown = Signal::new(false);
4357 column((
4358 button("Grow")
4359 .action(move || grown.update(|g| *g = !*g))
4360 .id(day_core::id!(grow)),
4361 sized_list(grown)
4362 .id(day_core::id!(list))
4363 .width(240.0)
4364 .height(480.0),
4365 ))
4366 })
4367 .drive(|d: Drive| async move {
4368 d.assert_visible("sized:end").await?;
4369 d.shot("sized-rows").await?;
4370 let rows = rows_fit()?;
4371 let (small, large) = (height_of(&rows, "small"), height_of(&rows, "large"));
4374 d.check(
4375 large > small * 1.5,
4376 "a large-title row is taller than a caption row",
4377 )?;
4378 let body = height_of(&rows, "body");
4379 d.check(
4380 height_of(&rows, "wrap") > body * 1.5,
4381 "the footnote wrapped",
4382 )?;
4383 d.tap("grow").await?;
4385 d.wait_idle().await?;
4386 d.pause(0.3).await?;
4387 d.shot("sized-rows-grown").await?;
4388 let grew = rows_fit()?;
4389 d.check(height_of(&grew, "body") > body * 1.5, "the body row grew")?;
4390 d.tap("grow").await?;
4391 d.wait_idle().await?;
4392 d.pause(0.3).await?;
4393 let shrank = rows_fit()?;
4394 d.check(
4395 (height_of(&shrank, "body") - body).abs() < 1.0,
4396 "the body row shrank back",
4397 )
4398 })
4399 }
4400
4401 #[day_macros::test(day_core)]
4403 fn list_select_and_activate() -> Case {
4404 Case::new()
4405 .proves(kinds::LIST)
4406 .page(|| {
4407 let picked = Signal::new(String::new());
4408 let opened = Signal::new(String::new());
4409 column((
4410 label(move || format!("picked {}", picked.get())).id(day_core::id!(picked)),
4411 label(move || format!("opened {}", opened.get())).id(day_core::id!(opened)),
4412 names_list(names(&["Alpha", "Beta", "Gamma"]))
4413 .on_select(move |k| picked.set(k))
4414 .on_activate(move |k| opened.set(k))
4415 .id(day_core::id!(list))
4416 .height(200.0),
4417 ))
4418 })
4419 .drive(|d: Drive| async move {
4420 d.select("list", 1).await?;
4421 d.assert_text("picked", "picked Beta").await?;
4422 d.activate("list", 2).await?;
4423 d.assert_text("opened", "opened Gamma").await
4424 })
4425 }
4426
4427 #[day_macros::test(day_core)]
4429 fn list_reorder_moves_row() -> Case {
4430 Case::new()
4431 .proves(kinds::LIST)
4432 .page(|| {
4433 let rows = names(&["Alpha", "Beta", "Gamma"]);
4434 column((
4435 label(move || rows.get().join(",")).id(day_core::id!(order)),
4436 names_list(rows)
4437 .reorderable(Reorder::new(move |from, to| {
4438 rows.update(|v| {
4439 let item = v.remove(from);
4440 v.insert(to.min(v.len()), item);
4441 });
4442 }))
4443 .id(day_core::id!(list))
4444 .height(200.0),
4445 ))
4446 })
4447 .drive(|d: Drive| async move {
4448 d.reorder("list", 0, 2).await?;
4449 d.assert_text("order", "Beta,Gamma,Alpha").await?;
4450 d.assert_text("conformance_row:Alpha", "Alpha").await
4451 })
4452 }
4453
4454 #[day_macros::test(day_core)]
4456 fn list_delete_row() -> Case {
4457 Case::new()
4458 .proves(kinds::LIST)
4459 .page(|| {
4460 let rows = names(&["Alpha", "Beta", "Gamma"]);
4461 column((
4462 label(move || rows.get().join(",")).id(day_core::id!(order)),
4463 names_list(rows)
4464 .deletable(Delete::new(move |at| {
4465 rows.update(|v| {
4466 v.remove(at);
4467 });
4468 }))
4469 .id(day_core::id!(list))
4470 .height(200.0),
4471 ))
4472 })
4473 .drive(|d: Drive| async move {
4474 d.delete_row("list", 1).await?;
4475 d.assert_text("order", "Alpha,Gamma").await?;
4476 d.assert_missing("conformance_row:Beta").await
4477 })
4478 }
4479
4480 #[day_macros::test(day_core)]
4482 fn list_swipe_action() -> Case {
4483 Case::new()
4484 .proves(kinds::LIST)
4485 .page(|| {
4486 let rows = names(&["Alpha", "Beta", "Gamma"]);
4487 let flagged = Signal::new(String::new());
4488 column((
4489 label(move || format!("flagged {}", flagged.get())).id(day_core::id!(flagged)),
4490 names_list(rows)
4491 .swipe_trailing(move |at| {
4492 let name = rows.get_untracked()[at].clone();
4493 vec![swipe_action("Flag").action(move || flagged.set(name.clone()))]
4494 })
4495 .id(day_core::id!(list))
4496 .height(200.0),
4497 ))
4498 })
4499 .drive(|d: Drive| async move {
4500 d.swipe_row("list", 2, false, 0).await?;
4501 d.assert_text("flagged", "flagged Gamma").await
4502 })
4503 }
4504
4505 #[day_macros::test(day_core)]
4508 fn list_scroll_to_edges_and_rows_from_dayscript() -> Case {
4509 Case::new()
4510 .proves(kinds::LIST)
4511 .proves_duty("list_scroll")
4512 .page(|| {
4513 let rows: Signal<Vec<String>> =
4514 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4515 names_list(rows).id(day_core::id!(list)).height(200.0)
4516 })
4517 .drive(|d: Drive| async move {
4518 d.assert_missing("conformance_row:Row%20299").await?;
4519 d.scroll_to("list", "bottom").await?;
4520 d.assert_text("conformance_row:Row%20299", "Row 299")
4521 .await?;
4522 d.reveal("conformance_row:Row%20297").await?;
4523 d.scroll_to("list", "top").await?;
4524 d.assert_text("conformance_row:Row%200", "Row 0").await?;
4525 d.reveal("conformance_row:Row%202").await?;
4526 d.assert_text("conformance_row:Row%202", "Row 2").await
4527 })
4528 }
4529
4530 #[day_macros::test(day_core)]
4532 fn list_scroll_to_row() -> Case {
4533 Case::new()
4534 .proves(kinds::LIST)
4535 .page(|| {
4536 let rows: Signal<Vec<String>> =
4537 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4538 let jump: Signal<Option<usize>> = Signal::new(None);
4539 column((
4540 button("Jump")
4541 .action(move || jump.set(Some(250)))
4542 .id(day_core::id!(jump)),
4543 names_list(rows)
4544 .scroll_to_row(jump)
4545 .id(day_core::id!(list))
4546 .height(200.0),
4547 ))
4548 })
4549 .drive(|d: Drive| async move {
4550 d.assert_missing("conformance_row:Row%20250").await?;
4551 d.tap("jump").await?;
4552 d.assert_text("conformance_row:Row%20250", "Row 250").await
4553 })
4554 }
4555
4556 struct RowAlive(std::rc::Rc<std::cell::Cell<usize>>);
4561
4562 impl RowAlive {
4563 fn new(live: &std::rc::Rc<std::cell::Cell<usize>>) -> Self {
4564 live.set(live.get() + 1);
4565 RowAlive(live.clone())
4566 }
4567 }
4568
4569 impl Drop for RowAlive {
4570 fn drop(&mut self) {
4571 self.0.set(self.0.get().saturating_sub(1));
4572 }
4573 }
4574
4575 const ROWS_ALIVE_BOUND: usize = 256;
4582
4583 #[day_macros::test(day_core)]
4585 fn list_recycles_distant_rows() -> Case {
4586 let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4587 let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4588 let (count, alive) = (built.clone(), live.clone());
4589 Case::new()
4590 .proves(kinds::LIST)
4591 .proves_cap(Cap::ListRecycling)
4592 .timeout(180.0)
4595 .requires_support("native list recycling", || {
4596 if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4597 day_spec::Support::Native
4598 } else {
4599 day_spec::Support::Unsupported
4600 }
4601 })
4602 .page(move || {
4603 count.set(0);
4604 alive.set(0);
4605 let (count, alive) = (count.clone(), alive.clone());
4606 let rows = Signal::new((0..4000).collect::<Vec<usize>>());
4607 let jump = Signal::new(None);
4608 let next = Signal::new(40usize);
4609 let pressed = Signal::new(String::new());
4610 column((
4611 button("Far").id(day_core::id!(far)).action(move || {
4612 jump.set(Some(next.get_untracked()));
4613 next.update(|n| *n += 40);
4614 }),
4615 button("Back")
4616 .id(day_core::id!(back))
4617 .action(move || jump.set(Some(0))),
4618 label(move || pressed.get()).id(day_core::id!(pressed)),
4619 list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4620 count.set(count.get() + 1);
4621 let guard = RowAlive::new(&alive);
4622 button(move || {
4623 let _ = &guard;
4624 format!("Row {}", slot.get())
4625 })
4626 .id_of(move || day_core::id!(conformance_row, slot.key()))
4627 .action(move || pressed.set(format!("Pressed {}", slot.get())))
4628 })
4629 .row_height(RowHeight::Uniform(32.0))
4630 .scroll_to_row(jump)
4631 .height(160.0),
4632 ))
4633 })
4634 .drive(move |d: Drive| {
4635 let (built, live) = (built.clone(), live.clone());
4636 async move {
4637 d.assert_text("conformance_row:0", "Row 0").await?;
4638 for row in (40..=3600).step_by(40) {
4646 d.tap("far").await?;
4647 d.assert_text(&format!("conformance_row:{row}"), &format!("Row {row}"))
4648 .await?;
4649 d.assert_missing("conformance_row:1").await?;
4650 d.tap(&format!("conformance_row:{row}")).await?;
4651 d.assert_text("pressed", &format!("Pressed {row}")).await?;
4652 d.tap("back").await?;
4653 d.assert_text("conformance_row:0", "Row 0").await?;
4654 d.tap("conformance_row:0").await?;
4655 d.assert_text("pressed", "Pressed 0").await?;
4656 }
4657 d.wait_idle().await?;
4660 d.pause(0.3).await?;
4661 d.check(
4662 live.get() <= ROWS_ALIVE_BOUND,
4663 &format!(
4664 "{} rows alive after 180 jumps of a five-row viewport ({} built): \
4665 discarded cells keep their rows",
4666 live.get(),
4667 built.get()
4668 ),
4669 )
4670 }
4671 })
4672 }
4673
4674 #[day_macros::test(day_core)]
4677 fn list_releases_discarded_rows() -> Case {
4678 const TOTAL: usize = 3000;
4679 const STRIDE: usize = 1237;
4680 let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4681 let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4682 let (count, alive) = (built.clone(), live.clone());
4683 Case::new()
4684 .proves(kinds::LIST)
4685 .proves_cap(Cap::ListRecycling)
4686 .timeout(90.0)
4687 .requires_support("native list recycling", || {
4688 if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4689 day_spec::Support::Native
4690 } else {
4691 day_spec::Support::Unsupported
4692 }
4693 })
4694 .page(move || {
4695 count.set(0);
4696 alive.set(0);
4697 let (count, alive) = (count.clone(), alive.clone());
4698 let rows = Signal::new((0..TOTAL).collect::<Vec<usize>>());
4699 let jump = Signal::new(None);
4700 let at = Signal::new(0usize);
4701 let pressed = Signal::new(String::new());
4702 column((
4703 button("Far").id(day_core::id!(far)).action(move || {
4706 let next = (at.get_untracked() + STRIDE) % TOTAL;
4707 at.set(next);
4708 jump.set(Some(next));
4709 }),
4710 button("Shrink")
4713 .id(day_core::id!(shrink))
4714 .action(move || rows.set((0..5).collect())),
4715 button("Regrow")
4716 .id(day_core::id!(regrow))
4717 .action(move || rows.set((0..TOTAL).collect())),
4718 button("Rotate")
4720 .id(day_core::id!(rotate))
4721 .action(move || rows.update(|r| r.rotate_left(7))),
4722 label(move || pressed.get()).id(day_core::id!(pressed)),
4723 list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4724 count.set(count.get() + 1);
4725 let guard = RowAlive::new(&alive);
4726 button(move || {
4727 let _ = &guard;
4728 format!("Row {}", slot.get())
4729 })
4730 .id_of(move || day_core::id!(conformance_row, slot.key()))
4731 .action(move || pressed.set(format!("Pressed {}", slot.get())))
4732 })
4733 .row_height(RowHeight::Uniform(32.0))
4734 .scroll_to_row(jump)
4735 .height(160.0),
4736 ))
4737 })
4738 .drive(move |d: Drive| {
4739 let (built, live) = (built.clone(), live.clone());
4740 async move {
4741 d.assert_text("conformance_row:0", "Row 0").await?;
4742 let (mut at, mut rotation) = (0usize, 0usize);
4743 let key_at = |i: usize, rotation: usize| (i + rotation) % TOTAL;
4745 for _ in 0..10 {
4746 at = (at + STRIDE) % TOTAL;
4748 d.tap("far").await?;
4749 let key = key_at(at, rotation);
4750 d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4751 .await?;
4752 d.tap(&format!("conformance_row:{key}")).await?;
4753 d.assert_text("pressed", &format!("Pressed {key}")).await?;
4754 d.tap("far").await?;
4756 d.tap("far").await?;
4757 at = (at + 2 * STRIDE) % TOTAL;
4758 let key = key_at(at, rotation);
4759 d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4760 .await?;
4761 d.tap("shrink").await?;
4764 d.assert_text("conformance_row:3", "Row 3").await?;
4765 if key >= 5 {
4766 d.assert_missing(&format!("conformance_row:{key}")).await?;
4767 }
4768 d.tap("regrow").await?;
4769 d.tap("rotate").await?;
4772 rotation = 7;
4773 at = (at + STRIDE) % TOTAL;
4774 d.tap("far").await?;
4775 let key = key_at(at, rotation);
4776 d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4777 .await?;
4778 }
4779 d.wait_idle().await?;
4780 d.pause(0.3).await?;
4781 d.check(
4782 live.get() <= ROWS_ALIVE_BOUND,
4783 &format!(
4784 "{} rows alive after the churn ({} built): discarded cells keep \
4785 their rows",
4786 live.get(),
4787 built.get()
4788 ),
4789 )
4790 }
4791 })
4792 }
4793
4794 #[day_macros::test(day_core)]
4796 fn list_shrink_and_regrow() -> Case {
4797 Case::new()
4798 .proves(kinds::LIST)
4799 .page(|| {
4800 let rows = Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4801 let jump = Signal::new(None);
4802 column((
4803 button("Jump")
4804 .id(day_core::id!(jump))
4805 .action(move || jump.set(Some(250))),
4806 button("Clear")
4807 .id(day_core::id!(clear))
4808 .action(move || rows.set(Vec::new())),
4809 button("Restore")
4810 .id(day_core::id!(restore))
4811 .action(move || {
4812 rows.set(vec!["New first".into(), "New last".into()]);
4813 jump.set(Some(1));
4814 }),
4815 names_list(rows).scroll_to_row(jump).height(160.0),
4816 ))
4817 })
4818 .drive(|d: Drive| async move {
4819 d.tap("jump").await?;
4820 d.assert_text("conformance_row:Row%20250", "Row 250")
4821 .await?;
4822 d.tap("clear").await?;
4823 d.assert_missing("conformance_row:Row%20250").await?;
4824 d.tap("restore").await?;
4825 d.assert_text("conformance_row:New%20first", "New first")
4826 .await?;
4827 d.assert_text("conformance_row:New%20last", "New last")
4828 .await
4829 })
4830 }
4831
4832 type Keyed = (u32, String);
4834
4835 fn key_color(key: u32) -> day_spec::Color {
4837 match key {
4838 1 => day_spec::Color::rgb(1.0, 0.0, 0.0),
4839 2 => day_spec::Color::rgb(0.0, 1.0, 0.0),
4840 3 => day_spec::Color::rgb(0.0, 0.0, 1.0),
4841 _ => day_spec::Color::rgb(1.0, 1.0, 0.0),
4842 }
4843 }
4844
4845 fn keyed_list(rows: Signal<Vec<Keyed>>) -> Decorated<List<Items<Keyed, u32>>> {
4849 list(
4850 items(move || rows.get(), |r: &Keyed| r.0),
4851 |slot: ItemSlot<Keyed, u32>| {
4852 row((
4853 rectangle()
4854 .fill(move || key_color(slot.field(|r| r.0)))
4855 .frame(60.0, 24.0),
4856 label(move || slot.field(|r| r.1.clone()))
4857 .id_of(move || day_core::id!(keyed, slot.field(|r| r.0))),
4858 ))
4859 .spacing(8.0)
4860 .id_of(move || day_core::id!(keyed_row, slot.field(|r| r.0)))
4861 },
4862 )
4863 .row_height(RowHeight::Uniform(32.0))
4864 .frame(240.0, 160.0)
4865 }
4866
4867 fn keyed(rows: &[(u32, &str)]) -> Signal<Vec<Keyed>> {
4868 Signal::new(rows.iter().map(|(k, t)| (*k, (*t).to_owned())).collect())
4869 }
4870
4871 async fn row_shows(d: &Drive, id: &str, index: u32, color: &str) -> Result<(), Fail> {
4874 let y = (f64::from(index) + 0.5) * 32.0 / 160.0;
4875 d.sample_pixel(id, 40.0 / 240.0, y, color).await
4876 }
4877
4878 #[day_macros::test(day_core)]
4882 fn list_keyed_changes_land_in_order() -> Case {
4883 Case::new()
4884 .proves(kinds::LIST)
4885 .timeout(60.0)
4887 .page(|| {
4888 let rows = keyed(&[(1, "One"), (2, "Two"), (3, "Three")]);
4889 column((
4890 row((
4891 button("Top")
4892 .action(move || rows.update(|v| v.insert(0, (9, "Nine".into()))))
4893 .id(day_core::id!(top)),
4894 button("Move")
4895 .action(move || {
4896 rows.update(|v| {
4897 if let Some(last) = v.pop() {
4898 v.insert(0, last);
4899 }
4900 });
4901 })
4902 .id(day_core::id!(lift)),
4903 button("Edit")
4904 .action(move || {
4905 rows.update(|v| {
4906 if let Some(two) = v.iter_mut().find(|r| r.0 == 2) {
4907 two.1 = "Deux".into();
4908 }
4909 });
4910 })
4911 .id(day_core::id!(edit)),
4912 button("Drop")
4913 .action(move || rows.update(|v| v.retain(|r| r.0 != 1)))
4914 .id(day_core::id!(drop)),
4915 )),
4916 keyed_list(rows).id(day_core::id!(list)),
4917 ))
4918 })
4919 .drive(|d: Drive| async move {
4920 d.assert_text("keyed:1", "One").await?;
4921 row_shows(&d, "list", 0, "#ff0000").await?;
4922 row_shows(&d, "list", 2, "#0000ff").await?;
4923 d.tap("top").await?;
4925 d.assert_text("keyed:9", "Nine").await?;
4926 row_shows(&d, "list", 0, "#ffff00").await?;
4927 row_shows(&d, "list", 1, "#ff0000").await?;
4928 row_shows(&d, "list", 3, "#0000ff").await?;
4929 d.tap("lift").await?;
4931 d.wait_idle().await?;
4932 row_shows(&d, "list", 0, "#0000ff").await?;
4933 row_shows(&d, "list", 1, "#ffff00").await?;
4934 row_shows(&d, "list", 3, "#00ff00").await?;
4935 d.tap("edit").await?;
4937 d.assert_text("keyed:2", "Deux").await?;
4938 row_shows(&d, "list", 3, "#00ff00").await?;
4939 d.tap("drop").await?;
4941 d.assert_missing("keyed:1").await?;
4942 d.assert_text("keyed:3", "Three").await?;
4943 row_shows(&d, "list", 0, "#0000ff").await?;
4944 row_shows(&d, "list", 1, "#ffff00").await?;
4945 row_shows(&d, "list", 2, "#00ff00").await
4946 })
4947 }
4948
4949 #[day_macros::test(day_core)]
4952 fn list_follow_end_follows_only_at_the_end() -> Case {
4953 Case::new()
4954 .proves(kinds::LIST)
4955 .proves_cap(Cap::ListViewport)
4956 .requires(Cap::ListViewport)
4957 .page(|| {
4958 let rows: Signal<Vec<String>> =
4959 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4960 let end = day_reactive::Trigger::new();
4961 column((
4962 row((
4963 button("Add")
4964 .action(move || {
4965 rows.update(|v| v.push(format!("New {}", v.len() - 300)));
4966 })
4967 .id(day_core::id!(add)),
4968 button("End")
4969 .action(move || end.notify())
4970 .id(day_core::id!(end)),
4971 )),
4972 names_list(rows)
4973 .follow_end(40.0)
4974 .scroll_to_end(end)
4975 .id(day_core::id!(list))
4976 .height(200.0),
4977 ))
4978 })
4979 .drive(|d: Drive| async move {
4980 d.assert_text("conformance_row:Row%200", "Row 0").await?;
4981 d.wait_idle().await?;
4982 d.tap("add").await?;
4984 d.wait_idle().await?;
4985 d.assert_missing("conformance_row:New%200").await?;
4986 d.assert_text("conformance_row:Row%200", "Row 0").await?;
4987 d.tap("end").await?;
4989 d.assert_text("conformance_row:New%200", "New 0").await?;
4990 d.wait_idle().await?;
4991 d.tap("add").await?;
4992 d.assert_text("conformance_row:New%201", "New 1").await
4993 })
4994 }
4995
4996 #[day_macros::test(day_core)]
5001 fn list_follow_end_keeps_up_with_rows_in_flight() -> Case {
5002 Case::new()
5003 .proves(kinds::LIST)
5004 .proves_cap(Cap::ListReaderScroll)
5005 .requires(Cap::ListViewport)
5006 .timeout(30.0)
5007 .page(|| {
5008 let rows: Signal<Vec<String>> =
5009 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5010 let end = day_reactive::Trigger::new();
5011 column((
5012 row((
5013 button("Burst")
5014 .action(move || {
5015 day_core::task(async move {
5016 for n in 0..12 {
5017 rows.update(|v| v.push(format!("Burst {n}")));
5018 day_core::sleep(40).await;
5019 }
5020 });
5021 })
5022 .id(day_core::id!(burst)),
5023 button("End")
5024 .action(move || end.notify())
5025 .id(day_core::id!(end)),
5026 )),
5027 names_list(rows)
5028 .follow_end(40.0)
5029 .scroll_to_end(end)
5030 .id(day_core::id!(list))
5031 .height(200.0),
5032 ))
5033 })
5034 .drive(|d: Drive| async move {
5035 d.assert_text("conformance_row:Row%200", "Row 0").await?;
5036 d.wait_idle().await?;
5037 d.tap("end").await?;
5038 d.assert_text("conformance_row:Row%20299", "Row 299")
5039 .await?;
5040 d.wait_idle().await?;
5041 d.tap("burst").await?;
5044 d.assert_text("conformance_row:Burst%2011", "Burst 11")
5045 .await?;
5046 d.wait_idle().await?;
5047 d.assert_text("conformance_row:Burst%2011", "Burst 11")
5048 .await
5049 })
5050 }
5051
5052 #[day_macros::test(day_core)]
5055 fn list_end_reached_fires_once_per_end() -> Case {
5056 Case::new()
5057 .proves(kinds::LIST)
5058 .proves_cap(Cap::ListViewport)
5059 .requires(Cap::ListViewport)
5060 .page(|| {
5061 let rows: Signal<Vec<String>> =
5062 Signal::new((0..60).map(|n| format!("Row {n}")).collect());
5063 let loads = Signal::new(0_u32);
5064 let end = day_reactive::Trigger::new();
5065 column((
5066 button("End")
5067 .action(move || end.notify())
5068 .id(day_core::id!(end)),
5069 label(move || format!("loads {}", loads.get())).id(day_core::id!(loads)),
5070 names_list(rows)
5071 .on_end_reached(100.0, move || {
5072 loads.update(|n| *n += 1);
5073 rows.update(|v| {
5074 let from = v.len();
5075 v.extend((from..from + 40).map(|n| format!("Row {n}")));
5076 });
5077 })
5078 .scroll_to_end(end)
5079 .id(day_core::id!(list))
5080 .height(200.0),
5081 ))
5082 })
5083 .drive(|d: Drive| async move {
5084 d.assert_text("conformance_row:Row%200", "Row 0").await?;
5085 d.wait_idle().await?;
5086 d.assert_text("loads", "loads 0").await?;
5087 d.tap("end").await?;
5088 d.assert_text("loads", "loads 1").await?;
5089 d.pause(0.3).await?;
5091 d.assert_text("loads", "loads 1").await?;
5092 d.tap("end").await?;
5093 d.assert_text("loads", "loads 2").await
5094 })
5095 }
5096
5097 #[day_macros::test(day_core)]
5101 fn list_end_reached_fills_a_short_list() -> Case {
5102 Case::new()
5103 .proves(kinds::LIST)
5104 .proves_cap(Cap::ListViewport)
5105 .requires(Cap::ListViewport)
5106 .page(|| {
5107 let rows: Signal<Vec<String>> =
5108 Signal::new((0..4).map(|n| format!("Row {n}")).collect());
5109 let loads = Signal::new(0_u32);
5110 column((
5111 label(move || format!("loads {}", loads.get())).id(day_core::id!(loads)),
5112 names_list(rows)
5113 .on_end_reached(200.0, move || {
5114 loads.update(|n| *n += 1);
5115 rows.update(|v| {
5117 let from = v.len();
5118 v.extend((from..(from + 4).min(12)).map(|n| format!("Row {n}")));
5119 });
5120 })
5121 .id(day_core::id!(list))
5122 .height(300.0),
5123 ))
5124 })
5125 .drive(|d: Drive| async move {
5126 d.assert_text("loads", "loads 3").await?;
5130 d.assert_text("conformance_row:Row%208", "Row 8").await?;
5132 d.pause(0.3).await?;
5133 d.assert_text("loads", "loads 3").await
5134 })
5135 }
5136
5137 #[day_macros::test(day_core)]
5140 fn list_visible_rows_follow_an_aligned_scroll() -> Case {
5141 Case::new()
5142 .proves(kinds::LIST)
5143 .proves_cap(Cap::ListViewport)
5144 .proves_cap(Cap::ListScrollAlign)
5145 .proves_duty("list_scroll")
5146 .requires(Cap::ListViewport)
5147 .requires(Cap::ListScrollAlign)
5148 .page(|| {
5149 let rows: Signal<Vec<String>> =
5150 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5151 let jump: Signal<Option<RowTarget>> = Signal::new(None);
5152 let visible = Signal::new(0_usize..0);
5153 column((
5154 row((
5155 button("Start")
5156 .action(move || {
5157 jump.set(Some(
5158 RowTarget::new(100)
5159 .align(day_spec::RowAlign::Start)
5160 .instant(),
5161 ));
5162 })
5163 .id(day_core::id!(to_start)),
5164 button("End")
5165 .action(move || {
5166 jump.set(Some(
5167 RowTarget::new(200).align(day_spec::RowAlign::End).instant(),
5168 ));
5169 })
5170 .id(day_core::id!(to_end)),
5171 )),
5172 label(move || format!("first {}", visible.get().start))
5173 .id(day_core::id!(first)),
5174 label(move || format!("last {}", visible.get().end.max(1) - 1))
5175 .id(day_core::id!(last)),
5176 label(move || {
5177 if visible.get().len() > 1 {
5178 "several"
5179 } else {
5180 "one or none"
5181 }
5182 })
5183 .id(day_core::id!(span)),
5184 names_list(rows)
5185 .scroll_to_row(jump)
5186 .visible_rows(visible)
5187 .id(day_core::id!(list))
5188 .height(160.0),
5189 ))
5190 })
5191 .drive(|d: Drive| async move {
5192 d.assert_text("first", "first 0").await?;
5193 d.assert_text("span", "several").await?;
5194 d.tap("to_start").await?;
5196 d.assert_text("first", "first 100").await?;
5197 d.assert_text("conformance_row:Row%20100", "Row 100")
5198 .await?;
5199 d.tap("to_end").await?;
5201 d.assert_text("last", "last 200").await?;
5202 d.assert_text("conformance_row:Row%20200", "Row 200").await
5203 })
5204 }
5205
5206 #[day_macros::test(day_core)]
5209 fn list_header_footer_and_empty_state() -> Case {
5210 Case::new()
5211 .proves(kinds::LIST)
5212 .page(|| {
5213 let rows = names(&[]);
5214 column((
5215 row((
5216 button("Add")
5217 .action(move || rows.update(|v| v.push(format!("Item {}", v.len()))))
5218 .id(day_core::id!(add)),
5219 button("Clear")
5220 .action(move || rows.set(Vec::new()))
5221 .id(day_core::id!(clear)),
5222 )),
5223 names_list(rows)
5224 .header(|| {
5225 label("Inbox")
5226 .id(day_core::id!(list_header))
5227 .padding(Insets::symmetric(12.0, 6.0))
5228 })
5229 .footer(|| {
5230 label("End of list")
5231 .id(day_core::id!(list_footer))
5232 .padding(Insets::symmetric(12.0, 6.0))
5233 })
5234 .empty(|| label("Nothing yet").id(day_core::id!(list_empty)))
5235 .id(day_core::id!(list))
5236 .height(260.0),
5237 ))
5238 })
5239 .drive(|d: Drive| async move {
5240 d.assert_text("list_header", "Inbox").await?;
5241 d.assert_text("list_empty", "Nothing yet").await?;
5242 d.assert_text("list_footer", "End of list").await?;
5243 d.tap("add").await?;
5245 d.assert_text("conformance_row:Item%200", "Item 0").await?;
5246 d.assert_missing("list_empty").await?;
5247 d.assert_text("list_header", "Inbox").await?;
5248 d.tap("add").await?;
5249 d.assert_text("conformance_row:Item%201", "Item 1").await?;
5250 d.assert_text("list_footer", "End of list").await?;
5251 d.tap("clear").await?;
5253 d.assert_missing("conformance_row:Item%200").await?;
5254 d.assert_text("list_empty", "Nothing yet").await
5255 })
5256 }
5257
5258 #[day_macros::test(day_core)]
5264 fn list_empty_state_shows_after_the_last_row_leaves() -> Case {
5265 Case::new()
5266 .proves(kinds::LIST)
5267 .page(|| {
5268 let rows: Signal<Vec<String>> =
5269 Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5270 let jump: Signal<Option<RowTarget>> = Signal::new(None);
5271 column((
5272 row((
5273 button("Down")
5274 .action(move || jump.set(Some(RowTarget::new(200).instant())))
5275 .id(day_core::id!(down)),
5276 button("Clear")
5277 .action(move || rows.set(Vec::new()))
5278 .id(day_core::id!(clear)),
5279 )),
5280 names_list(rows)
5281 .header(|| {
5282 label("A header taller than the list")
5283 .id(day_core::id!(list_header))
5284 .padding(Insets::symmetric(12.0, 6.0))
5285 .height(160.0)
5286 })
5287 .empty(|| label("Nothing here").id(day_core::id!(list_empty)))
5288 .scroll_to_row(jump)
5289 .id(day_core::id!(list))
5290 .height(120.0),
5291 ))
5292 })
5293 .drive(|d: Drive| async move {
5294 d.assert_text("list_header", "A header taller than the list")
5295 .await?;
5296 d.tap("down").await?;
5297 d.wait_idle().await?;
5298 d.assert_text("conformance_row:Row%20200", "Row 200")
5299 .await?;
5300 d.tap("clear").await?;
5301 d.wait_idle().await?;
5302 d.assert_missing("conformance_row:Row%20200").await?;
5303 d.assert_text("list_empty", "Nothing here").await
5304 })
5305 }
5306
5307 #[day_macros::test(day_core)]
5310 fn list_content_padding_insets_rows() -> Case {
5311 Case::new()
5312 .proves(kinds::LIST)
5313 .page(|| {
5314 let plain = keyed(&[(1, "Plain")]);
5315 let padded = keyed(&[(2, "Padded")]);
5316 column((
5317 keyed_list(plain),
5318 keyed_list(padded)
5319 .content_padding(Insets {
5320 top: 16.0,
5321 leading: 24.0,
5322 bottom: 16.0,
5323 trailing: 24.0,
5324 })
5325 .id(day_core::id!(padded_list)),
5326 ))
5327 .spacing(0.0)
5328 .align(HAlign::Leading)
5329 })
5330 .drive(|d: Drive| async move {
5331 d.assert_text("keyed:1", "Plain").await?;
5332 d.assert_text("keyed:2", "Padded").await?;
5333 d.assert_frame(
5335 "keyed_row:2",
5336 FrameExpect {
5337 x: Some(24.0),
5338 relative_to: Some("keyed_row:1".into()),
5339 ..Default::default()
5340 },
5341 )
5342 .await?;
5343 d.sample_pixel("padded_list", 64.0 / 240.0, 32.0 / 160.0, "#00ff00")
5345 .await
5346 })
5347 }
5348
5349 const SECTIONED: [(&str, u32); 9] = [
5352 ("A", 1),
5353 ("A", 2),
5354 ("A", 3),
5355 ("B", 4),
5356 ("B", 5),
5357 ("B", 6),
5358 ("C", 7),
5359 ("C", 8),
5360 ("C", 9),
5361 ];
5362
5363 fn sectioned_tops() -> Result<Vec<f64>, Fail> {
5365 day_core::try_with_tree(|t| {
5366 SECTIONED
5367 .iter()
5368 .map(|(_, key)| {
5369 let id = format!("sectioned:{key}");
5370 let node = t
5371 .find_by_id(&id)
5372 .ok_or_else(|| Fail(format!("no element {id:?}")))?;
5373 t.read_native(node)
5374 .and_then(|n| n.frame)
5375 .map(|f| f.origin.y)
5376 .ok_or_else(|| Fail(format!("{id:?} has no native frame")))
5377 })
5378 .collect()
5379 })
5380 .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
5381 }
5382
5383 #[day_macros::test(day_core)]
5389 fn list_sectioned_rows_keep_their_height_after_a_splice() -> Case {
5390 Case::new()
5391 .proves(kinds::LIST)
5392 .page(|| {
5393 let rows = Signal::new(vec![SECTIONED[0], SECTIONED[3]]);
5394 column((
5395 button("Load")
5396 .action(move || rows.set(SECTIONED.to_vec()))
5397 .id(day_core::id!(load)),
5398 list(
5399 items(move || rows.get(), |r: &(&str, u32)| r.1),
5400 |slot: ItemSlot<(&'static str, u32), u32>| {
5401 label(move || format!("Row {}", slot.field(|r| r.1)))
5402 .id_of(move || day_core::id!(sectioned, slot.field(|r| r.1)))
5403 .padding(Insets::symmetric(12.0, 6.0))
5404 },
5405 )
5406 .sections(
5407 move |i| rows.with(|r| r.get(i).map(|r| r.0)),
5408 |slot: ItemSlot<(&'static str, u32), u32>| {
5409 label(move || format!("Section {}", slot.field(|r| r.0)))
5410 .font(Font::Caption)
5411 .padding(Insets::symmetric(12.0, 2.0))
5412 },
5413 )
5414 .row_height(RowHeight::Uniform(32.0))
5415 .id(day_core::id!(list))
5416 .width(240.0)
5417 .height(480.0),
5418 ))
5419 })
5420 .drive(|d: Drive| async move {
5421 d.assert_text("sectioned:4", "Row 4").await?;
5422 d.tap("load").await?;
5423 d.assert_text("sectioned:9", "Row 9").await?;
5424 d.wait_idle().await?;
5425 d.pause(0.3).await?;
5426 d.shot("sectioned-splice").await?;
5427 let tops = sectioned_tops()?;
5428 let pitch = tops[1] - tops[0];
5430 d.check(
5431 pitch >= 31.5,
5432 &format!("the first row is {pitch:.1} tall, under its 32-point height"),
5433 )?;
5434 let mut step = None;
5435 for (i, pair) in tops.windows(2).enumerate() {
5436 let gap = pair[1] - pair[0];
5437 if SECTIONED[i].0 == SECTIONED[i + 1].0 {
5438 d.check(
5439 (gap - pitch).abs() <= 1.0,
5440 &format!(
5441 "row {} starts {gap:.1} below row {} where every row of a \
5442 section is {pitch:.1} below the one before",
5443 SECTIONED[i + 1].1,
5444 SECTIONED[i].1
5445 ),
5446 )?;
5447 } else {
5448 let step = *step.get_or_insert(gap);
5450 d.check(
5451 gap > pitch && (gap - step).abs() <= 1.0,
5452 &format!(
5453 "row {} starts {gap:.1} below row {} across a header, where \
5454 the first header's step was {step:.1}",
5455 SECTIONED[i + 1].1,
5456 SECTIONED[i].1
5457 ),
5458 )?;
5459 }
5460 }
5461 Ok(())
5462 })
5463 }
5464
5465 type Node = (String, Option<String>);
5466
5467 fn names_tree(rows: Signal<Vec<Node>>) -> TreePiece<Branches<Node, String>> {
5470 tree(
5471 branches(
5472 move || rows.get(),
5473 |n: &Node| n.0.clone(),
5474 |n: &Node| n.1.clone(),
5475 ),
5476 |row: ItemSlot<Node, String>| {
5477 label(move || row.get().0)
5478 .id_of(move || day_core::id!(conformance_row, row.get().0))
5479 .padding(Insets::symmetric(8.0, 4.0))
5480 },
5481 )
5482 .row_height(RowHeight::Uniform(28.0))
5483 .row_id(|k: &String| day_core::id!(tree_row, k))
5484 }
5485
5486 fn fruit() -> Signal<Vec<Node>> {
5487 let n = |name: &str, parent: Option<&str>| (name.to_string(), parent.map(str::to_owned));
5488 Signal::new(vec![
5489 n("Fruit", None),
5490 n("Apple", Some("Fruit")),
5491 n("Pear", Some("Fruit")),
5492 n("Nuts", None),
5493 ])
5494 }
5495
5496 #[day_macros::test(day_core)]
5498 fn tree_rows_disclose() -> Case {
5499 Case::new()
5500 .proves_duty("attach_tree")
5501 .proves_cap(Cap::Tree)
5502 .proves(kinds::TREE)
5503 .requires(Cap::Tree)
5504 .page(|| names_tree(fruit()).id(day_core::id!(tree)).height(240.0))
5505 .drive(|d: Drive| async move {
5506 d.assert_text("conformance_row:Fruit", "Fruit").await?;
5507 d.assert_text("conformance_row:Nuts", "Nuts").await?;
5508 d.assert_missing("conformance_row:Apple").await?;
5509 d.expand("tree", "tree_row:Fruit", true).await?;
5510 d.assert_text("conformance_row:Apple", "Apple").await?;
5511 d.expand("tree", "tree_row:Fruit", false).await?;
5512 d.assert_missing("conformance_row:Apple").await
5513 })
5514 }
5515
5516 #[day_macros::test(day_core)]
5518 fn tree_expanded_signal() -> Case {
5519 Case::new()
5520 .proves(kinds::TREE)
5521 .requires(Cap::Tree)
5522 .page(|| {
5523 let open = Signal::new(std::collections::HashSet::from(["Fruit".to_string()]));
5524 names_tree(fruit())
5525 .expanded(open)
5526 .id(day_core::id!(tree))
5527 .height(240.0)
5528 })
5529 .drive(|d: Drive| async move { d.assert_text("conformance_row:Pear", "Pear").await })
5530 }
5531
5532 #[day_macros::test(day_core)]
5535 fn tree_section_expansion_contract() -> Case {
5536 Case::new()
5537 .proves_duty("attach_tree")
5538 .proves_cap(Cap::TreeSections)
5539 .proves(kinds::TREE)
5540 .requires(Cap::TreeSections)
5541 .page(|| {
5542 let rows = fruit();
5543 let open = Signal::new(std::collections::HashSet::from(["Fruit".to_owned()]));
5544 let changes = Signal::new(0usize);
5545 column((
5546 label(move || {
5547 format!("{}:{}", open.with(|s| s.contains("Fruit")), changes.get())
5548 })
5549 .id(day_core::id!(state)),
5550 button("restore")
5551 .id(day_core::id!(restore))
5552 .action(move || {
5553 open.set(std::collections::HashSet::from(["Fruit".to_owned()]));
5554 }),
5555 button("filter")
5556 .id(day_core::id!(filter))
5557 .action(move || rows.update(|r| r.retain(|n| n.0 != "Apple"))),
5558 names_tree(rows)
5559 .section_headers()
5560 .expanded(open)
5561 .on_expansion(move |_, _| changes.update(|n| *n += 1))
5562 .id(day_core::id!(tree))
5563 .height(240.0),
5564 ))
5565 })
5566 .drive(|d: Drive| async move {
5567 d.assert_text("state", "true:0").await?;
5568 d.assert_text("conformance_row:Apple", "Apple").await?;
5569 d.expand("tree", "tree_row:Fruit", false).await?;
5570 d.assert_text("state", "false:1").await?;
5571 d.assert_missing("conformance_row:Apple").await?;
5572 d.expand("tree", "tree_row:Fruit", false).await?;
5573 d.assert_text("state", "false:1").await?;
5574 d.tap("filter").await?;
5575 d.assert_missing("conformance_row:Pear").await?;
5576 d.tap("restore").await?;
5577 d.assert_text("conformance_row:Pear", "Pear").await?;
5578 d.assert_text("state", "true:1").await
5579 })
5580 }
5581
5582 #[day_macros::test(day_core)]
5584 fn tree_move_reparents() -> Case {
5585 Case::new()
5586 .proves_cap(Cap::TreeMove)
5587 .proves(kinds::TREE)
5588 .requires(Cap::Tree)
5589 .page(|| {
5590 let rows = fruit();
5591 let open = Signal::new(std::collections::HashSet::from([
5592 "Fruit".to_string(),
5593 "Nuts".to_string(),
5594 ]));
5595 column((
5596 label(move || {
5597 rows.get()
5598 .iter()
5599 .map(|(n, p)| format!("{n}<{}", p.clone().unwrap_or_default()))
5600 .collect::<Vec<_>>()
5601 .join(",")
5602 })
5603 .id(day_core::id!(shape)),
5604 names_tree(rows)
5606 .expanded(open)
5607 .expandable(|k: &String| k == "Fruit" || k == "Nuts")
5608 .movable(Move::new(move |key, parent, _at| {
5609 rows.update(|v| {
5610 if let Some(n) = v.iter_mut().find(|n| n.0 == key) {
5611 n.1 = parent;
5612 }
5613 });
5614 }))
5615 .id(day_core::id!(tree))
5616 .height(240.0),
5617 ))
5618 })
5619 .drive(|d: Drive| async move {
5620 d.tree_move("tree", "tree_row:Pear", Some("tree_row:Nuts"), None)
5621 .await?;
5622 d.assert_text("shape", "Fruit<,Apple<Fruit,Pear<Nuts,Nuts<")
5623 .await?;
5624 d.assert_text("conformance_row:Pear", "Pear").await
5625 })
5626 }
5627}