1use std::cell::Cell;
12use std::rc::Rc;
13
14use day_core::*;
15use day_reactive::{Scope, Signal, bind};
16use day_spec::props::*;
17use day_spec::{
18 A11yProps, Angle, AnimSpec, Cursor, Event, Ink, Insets, Paint, Role, Transform, kinds,
19};
20
21use crate::menus::lower_menu_scoped;
22use crate::*;
23
24pub trait Modifier {
51 fn apply(self, content: AnyPiece) -> AnyPiece;
52}
53
54impl<F> Modifier for F
55where
56 F: FnOnce(AnyPiece) -> AnyPiece,
57{
58 fn apply(self, content: AnyPiece) -> AnyPiece {
59 self(content)
60 }
61}
62
63#[derive(Clone)]
76pub struct NativeRef {
77 cell: Rc<std::cell::Cell<Option<day_core::RNode>>>,
78 changed: day_reactive::Trigger,
79}
80
81impl Default for NativeRef {
82 fn default() -> Self {
83 Self::new()
84 }
85}
86
87impl NativeRef {
88 #[must_use]
89 pub fn new() -> Self {
90 NativeRef {
91 cell: Rc::new(std::cell::Cell::new(None)),
92 changed: day_reactive::Trigger::new(),
93 }
94 }
95
96 #[must_use]
98 pub fn node(&self) -> Option<day_core::RNode> {
99 self.changed.track();
100 let node = self.cell.get()?;
101 let live = day_core::try_with_tree(|t| t.node_kind(node).is_some()).unwrap_or(false);
103 live.then_some(node)
104 }
105
106 pub fn with<R>(&self, f: impl FnOnce(day_core::RNode) -> R) -> Option<R> {
108 self.node().map(f)
109 }
110
111 fn transition(&self, node: Option<day_core::RNode>) {
112 self.cell.set(node);
113 self.changed.notify();
114 }
115}
116
117fn layer_node(cx: &mut BuildCx) -> RNode {
121 cx.native(
122 kinds::CONTAINER,
123 &ContainerProps {
124 corner_radius: 0.0,
125 clips: false,
126 role: None,
127 ..Default::default()
128 },
129 Rc::new(FillThrough),
130 Flex::default(),
131 Boundary::No,
132 )
133}
134
135type Build = Box<dyn FnOnce(&mut BuildCx) -> RNode>;
141
142#[must_use]
167pub struct Decorated<P> {
168 inner: P,
169 ops: Vec<Box<dyn FnOnce(Build) -> Build>>,
171 node_ops: Vec<Box<dyn FnOnce(RNode)>>,
173 outer_ops: Vec<Box<dyn FnOnce(RNode)>>,
175}
176
177impl<P: Piece> Decorated<P> {
178 pub fn new(inner: P) -> Self {
190 Decorated {
191 inner,
192 ops: Vec::new(),
193 node_ops: Vec::new(),
194 outer_ops: Vec::new(),
195 }
196 }
197
198 fn push(mut self, op: impl FnOnce(Build) -> Build + 'static) -> Self {
199 self.ops.push(Box::new(op));
200 self
201 }
202
203 fn push_node(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
204 self.node_ops.push(Box::new(op));
205 self
206 }
207
208 fn push_outer(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
209 self.outer_ops.push(Box::new(op));
210 self
211 }
212
213 pub fn map_inner<Q: Piece>(self, f: impl FnOnce(P) -> Q) -> Decorated<Q> {
217 Decorated {
218 inner: f(self.inner),
219 ops: self.ops,
220 node_ops: self.node_ops,
221 outer_ops: self.outer_ops,
222 }
223 }
224
225 pub fn apply_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
235 if cond { f(self) } else { self }
236 }
237
238 pub fn apply_some<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
241 match value {
242 Some(v) => f(self, v),
243 None => self,
244 }
245 }
246}
247
248impl<P: Piece> Piece for Decorated<P> {
249 fn build(self, cx: &mut BuildCx) -> RNode {
250 let Decorated {
251 inner,
252 ops,
253 node_ops,
254 outer_ops,
255 } = self;
256 let wraps = !ops.is_empty();
260 let own = Rc::new(Cell::new(None::<RNode>));
261 let own_out = own.clone();
262 let mut build: Build = Box::new(move |cx| {
263 let n = inner.build(cx);
264 for op in node_ops {
265 op(n);
266 }
267 own_out.set(Some(n));
268 n
269 });
270 for op in ops {
271 build = op(build);
272 }
273 let outer = build(cx);
274 if wraps && let Some(n) = own.get() {
277 with_tree(|t| t.set_element_outer(n, outer));
278 }
279 for op in outer_ops {
280 op(outer);
281 }
282 outer
283 }
284}
285
286fn op_id(id: day_core::ElementId) -> impl FnOnce(RNode) {
289 move |n| with_tree(|t| t.set_id(t.element_target(n), id.as_str().to_owned()))
290}
291
292fn op_id_of(id: impl Fn() -> day_core::ElementId + 'static) -> impl FnOnce(RNode) {
293 move |n| {
294 day_reactive::bind(id, move |s: &day_core::ElementId| {
295 let s = s.as_str().to_owned();
296 with_tree(|t| t.set_id(t.element_target(n), s));
297 });
298 }
299}
300
301fn op_wrapper_id(id: day_core::ElementId) -> impl FnOnce(Build) -> Build {
303 move |inner| {
304 Box::new(move |cx| {
305 let n = inner(cx);
306 with_tree(|t| t.set_id(n, id.as_str().to_owned()));
307 n
308 })
309 }
310}
311
312fn op_tweak(f: impl FnOnce(day_core::RNode) + 'static) -> impl FnOnce(Build) -> Build {
313 move |inner| {
314 Box::new(move |cx| {
315 let n = inner(cx);
316 f(n);
317 with_tree(|t| t.note_node_tweaked(n));
321 n
322 })
323 }
324}
325
326fn op_selectable() -> impl FnOnce(Build) -> Build {
327 move |inner| {
328 Box::new(move |cx| {
329 let n = inner(cx);
330 with_tree(|t| t.set_node_selectable(n, true));
331 n
332 })
333 }
334}
335
336fn op_cursor(cursor: Reactive<Cursor>) -> impl FnOnce(Build) -> Build {
337 move |inner| {
338 Box::new(move |cx| {
339 let n = inner(cx);
340 let shape = cursor.get_untracked();
343 with_tree(|t| t.set_node_cursor(n, shape));
344 if let Reactive::Dyn(_) = &cursor {
347 bind(
348 move || cursor.get(),
349 move |c: &Cursor| {
350 with_tree(|t| t.set_node_cursor(n, c.clone()));
351 },
352 );
353 }
354 n
355 })
356 }
357}
358
359fn op_layout_direction(
360 direction: Reactive<day_spec::LayoutDirection>,
361) -> impl FnOnce(Build) -> Build {
362 move |inner| {
363 Box::new(move |cx| {
364 let n = inner(cx);
365 let seed = direction.get_untracked();
366 with_tree(|t| t.set_node_direction(n, Some(seed)));
367 if let Reactive::Dyn(_) = &direction {
368 bind(
369 move || direction.get(),
370 move |d: &day_spec::LayoutDirection| {
371 with_tree(|t| {
372 t.set_node_direction(n, Some(*d));
373 t.layout_if_needed();
374 });
375 },
376 );
377 }
378 n
379 })
380 }
381}
382
383fn op_window_drag_region() -> impl FnOnce(Build) -> Build {
384 move |inner| {
385 Box::new(move |cx| {
386 let n = inner(cx);
387 with_tree(|t| t.set_node_drag_region(n, true));
388 n
389 })
390 }
391}
392
393fn op_native_ref(r: NativeRef) -> impl FnOnce(Build) -> Build {
394 move |inner| {
395 Box::new(move |cx| {
396 let n = inner(cx);
397 r.transition(Some(n));
398 let cleared = r.clone();
399 Scope::current().on_cleanup(move || cleared.transition(None));
400 n
401 })
402 }
403}
404
405fn op_padding(insets: Reactive<Insets>) -> impl FnOnce(Build) -> Build {
406 move |inner| {
407 Box::new(move |cx| {
408 let seed = insets.get_untracked();
409 let layout = Rc::new(PaddingLayout {
410 insets: Cell::new(seed),
411 });
412 let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
413 cx.under(w, |cx| {
414 let _ = inner(cx);
415 });
416 if let Reactive::Dyn(_) = &insets {
419 day_reactive::bind_seeded(
420 seed,
421 move || insets.get(),
422 move |v: &Insets| {
423 layout.insets.set(*v);
424 with_tree(|t| t.mark_needs_measure(w));
425 },
426 );
427 }
428 w
429 })
430 }
431}
432
433fn bind_length(value: Reactive<f64>, cell: impl Fn(f64) + 'static, node: RNode) {
436 if let Reactive::Dyn(_) = &value {
437 let seed = value.get_untracked();
438 day_reactive::bind_seeded(
439 seed,
440 move || value.get(),
441 move |v: &f64| {
442 cell(*v);
443 with_tree(|t| t.mark_needs_measure(node));
444 },
445 );
446 }
447}
448
449fn op_max_width(max: Reactive<f64>) -> impl FnOnce(Build) -> Build {
450 move |inner| {
451 Box::new(move |cx| {
452 let layout = Rc::new(MaxWidthLayout {
453 max: Cell::new(max.get_untracked()),
454 });
455 let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
456 cx.under(w, |cx| {
457 let _ = inner(cx);
458 });
459 bind_length(max, move |v| layout.max.set(v), w);
460 w
461 })
462 }
463}
464
465fn op_max_height(max: Reactive<f64>) -> impl FnOnce(Build) -> Build {
466 move |inner| {
467 Box::new(move |cx| {
468 let layout = Rc::new(day_core::MaxHeightLayout {
472 max: Cell::new(max.get_untracked()),
473 });
474 let h = cx.layout_only(
475 layout.clone(),
476 Flex {
477 yields_h: true,
478 ..Flex::default()
479 },
480 Boundary::No,
481 );
482 cx.under(h, |cx| {
483 let _ = inner(cx);
484 });
485 bind_length(max, move |v| layout.max.set(v), h);
486 h
487 })
488 }
489}
490
491fn op_min_width(min: Reactive<f64>) -> impl FnOnce(Build) -> Build {
492 move |inner| {
493 Box::new(move |cx| {
494 let layout = Rc::new(day_core::MinWidthLayout {
495 min: Cell::new(min.get_untracked()),
496 });
497 let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
498 cx.under(w, |cx| {
499 let _ = inner(cx);
500 });
501 bind_length(min, move |v| layout.min.set(v), w);
502 w
503 })
504 }
505}
506
507fn op_min_height(min: Reactive<f64>) -> impl FnOnce(Build) -> Build {
508 move |inner| {
509 Box::new(move |cx| {
510 let layout = Rc::new(MinHeightLayout {
511 min: Cell::new(min.get_untracked().max(0.0)),
512 });
513 let node = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
514 cx.under(node, |cx| {
515 let _ = inner(cx);
516 });
517 bind_length(min, move |v| layout.min.set(v.max(0.0)), node);
518 node
519 })
520 }
521}
522
523fn op_reserving(sample: TextSource) -> impl FnOnce(Build) -> Build {
524 move |inner| {
525 Box::new(move |cx| {
526 let wrapper = cx.layout_only(
527 Rc::new(day_core::ReserveLayout),
528 Flex::default(),
529 Boundary::No,
530 );
531 cx.under(wrapper, |cx| {
532 let content = inner(cx);
533 let font = with_tree(|tree| {
536 let mut node = content;
537 loop {
538 if let Some(font) = tree.node_probe(node).and_then(|p| p.font) {
539 break font;
540 }
541 if tree.child_count(node) != 1 {
542 break day_spec::FontSpec::from(day_spec::Font::Body);
543 }
544 let Some(child) = tree.first_child(node) else {
545 break day_spec::FontSpec::from(day_spec::Font::Body);
546 };
547 node = child;
548 }
549 });
550 let sample_node = cx.leaf(
551 day_spec::kinds::LABEL,
552 &LabelProps {
553 text: sample.initial(),
554 font,
555 wraps: false,
556 ..Default::default()
557 },
558 Flex::default(),
559 );
560 with_tree(|tree| {
561 tree.set_node_opacity(sample_node, 0.0);
562 tree.set_a11y(
563 sample_node,
564 A11yProps {
565 hidden: true,
566 decorative: true,
567 ..Default::default()
568 },
569 );
570 });
571 sample.bind_to(sample_node, |s| Box::new(LabelPatch::Text(s)), true);
572 });
573 wrapper
574 })
575 }
576}
577
578struct ReactiveFrameLayout {
581 size: Cell<(Option<f64>, Option<f64>)>,
582}
583impl ReactiveFrameLayout {
584 fn frame(&self) -> FrameLayout {
585 let (width, height) = self.size.get();
586 FrameLayout { width, height }
587 }
588}
589impl Layout for ReactiveFrameLayout {
590 fn measure(
591 &self,
592 cx: &mut dyn LayoutOps,
593 children: &[RNode],
594 p: day_spec::Proposal,
595 ) -> day_spec::Size {
596 self.frame().measure(cx, children, p)
597 }
598 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: day_spec::Rect) {
599 self.frame().place(cx, children, bounds);
600 }
601 fn baseline(
602 &self,
603 cx: &mut dyn LayoutOps,
604 children: &[RNode],
605 size: day_spec::Size,
606 ) -> Option<f64> {
607 self.frame().baseline(cx, children, size)
608 }
609}
610
611fn frame_extent(value: f64) -> f64 {
612 if value.is_finite() {
613 value.max(0.0)
614 } else {
615 0.0
616 }
617}
618
619fn op_frame(
620 width: Option<Reactive<f64>>,
621 height: Option<Reactive<f64>>,
622) -> impl FnOnce(Build) -> Build {
623 move |inner| {
624 Box::new(move |cx| {
625 let dynamic =
626 matches!(width, Some(Reactive::Dyn(_))) || matches!(height, Some(Reactive::Dyn(_)));
627 let read = move || {
628 (
629 width.as_ref().map(|v| frame_extent(v.get())),
630 height.as_ref().map(|v| frame_extent(v.get())),
631 )
632 };
633 let seed = day_reactive::untrack(&read);
634 let layout = Rc::new(ReactiveFrameLayout {
635 size: Cell::new(seed),
636 });
637 let boundary = if !dynamic && seed.0.is_some() && seed.1.is_some() {
640 Boundary::Yes
641 } else {
642 Boundary::No
643 };
644 let node = cx.layout_only(layout.clone(), Flex::default(), boundary);
645 cx.under(node, |cx| {
646 let _ = inner(cx);
647 });
648 if dynamic {
649 day_reactive::bind_seeded(seed, read, move |size| {
650 layout.size.set(*size);
651 with_tree(|t| t.mark_needs_measure(node));
652 });
653 }
654 node
655 })
656 }
657}
658
659fn op_a11y(f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> impl FnOnce(Build) -> Build {
660 move |inner| {
661 Box::new(move |cx| {
662 let n = inner(cx);
663 let (props, live, selected) = f(A11yBuilder::default()).split();
664 let seed = props.selected;
665 with_tree(|t| t.set_a11y(n, props));
666 if let Some(selected) = selected {
669 day_reactive::bind_seeded(
670 seed.unwrap_or(false),
671 move || selected.get(),
672 move |on: &bool| {
673 with_tree(|t| {
674 t.set_a11y(
675 n,
676 A11yProps {
677 selected: Some(*on),
678 ..Default::default()
679 },
680 );
681 });
682 },
683 );
684 }
685 for (src, patch) in live {
688 if let TextSource::Dyn(read) = src {
689 let seed = day_reactive::untrack(|| read());
690 day_reactive::bind_seeded(
691 seed,
692 move || read(),
693 move |s: &String| with_tree(|t| t.set_a11y(n, patch(s.clone()))),
694 );
695 }
696 }
697 n
698 })
699 }
700}
701
702fn op_on_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
703 move |inner| {
704 Box::new(move |cx| {
705 let n = inner(cx);
706 with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
707 cx.on(n, move |ev| {
708 if matches!(ev, Event::Tap(_)) {
709 f();
710 }
711 });
712 n
713 })
714 }
715}
716
717fn op_on_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
718 move |inner| {
719 Box::new(move |cx| {
720 let n = inner(cx);
721 with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
722 cx.on(n, move |ev| {
723 if let Event::Tap(p) = ev {
724 f(*p);
725 }
726 });
727 n
728 })
729 }
730}
731
732fn op_on_key(
734 released: bool,
735 f: impl Fn(&day_spec::KeyEvent) + 'static,
736) -> impl FnOnce(Build) -> Build {
737 move |inner| {
738 Box::new(move |cx| {
739 let n = inner(cx);
740 day_spec::keys::mark(day_core::rnode_to_id(n));
746 if let Some(view) = with_tree(|t| t.native_view_of(n))
747 && view != n
748 {
749 day_spec::keys::mark(day_core::rnode_to_id(view));
750 }
751 cx.on(n, move |ev| {
752 if let Event::Key(k) = ev
753 && k.is_release() == released
754 {
755 f(k);
756 }
757 });
758 n
759 })
760 }
761}
762
763fn op_toolbar(source: crate::ToolbarSource) -> impl FnOnce(Build) -> Build {
770 move |inner| {
771 Box::new(move |cx| {
772 let n = inner(cx);
773 crate::contribute(day_core::current_chrome(), source);
774 n
775 })
776 }
777}
778
779fn op_focusable() -> impl FnOnce(Build) -> Build {
780 move |inner| {
781 Box::new(move |cx| {
782 let n = inner(cx);
783 with_tree(|t| t.set_focusable(n, true));
784 n
785 })
786 }
787}
788
789fn op_keyboard() -> impl FnOnce(Build) -> Build {
790 move |inner| {
791 Box::new(move |cx| {
792 let n = inner(cx);
793 day_spec::keys::mark_text(day_core::rnode_to_id(n));
796 if let Some(view) = with_tree(|t| t.native_view_of(n))
797 && view != n
798 {
799 day_spec::keys::mark_text(day_core::rnode_to_id(view));
800 }
801 n
802 })
803 }
804}
805
806fn op_focused(
807 want: Box<dyn Fn() -> bool>,
808 on_native: Box<dyn Fn(bool)>,
809) -> impl FnOnce(Build) -> Build {
810 move |inner| {
811 Box::new(move |cx| {
812 let n = inner(cx);
813 let native = Rc::new(Cell::new(false));
817 {
818 let native = native.clone();
819 cx.on(n, move |ev| {
820 if let Event::FocusChanged(f) = ev {
821 native.set(*f);
822 on_native(*f);
823 }
824 });
825 }
826 let first = Cell::new(true);
831 bind(want, move |want: &bool| {
832 let want = *want;
833 if first.replace(false) && !want {
834 return;
835 }
836 if native.get() == want {
837 return;
838 }
839 day_reactive::on_main(move || with_tree(|t| t.focus_node(n, want)));
840 });
841 n
842 })
843 }
844}
845
846fn op_context_menu(items: Vec<MenuEntry>) -> impl FnOnce(Build) -> Build {
847 move |inner| {
848 Box::new(move |cx| {
849 let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
853 let mut n = w;
854 cx.under(w, |cx| {
855 n = inner(cx);
856 let model = lower_menu_scoped(items);
859 with_tree(|t| t.set_context_menu(n, model.clone()));
860 let model = std::rc::Rc::new(model);
863 crate::menus::mount_composed_menu(cx, n, Rc::new(move |_p| (*model).clone()));
864 });
865 with_tree(|t| t.forward_whole_row(w, n));
867 n
870 })
871 }
872}
873
874pub(crate) struct OverlayHost;
879
880impl Layout for OverlayHost {
881 fn measure(
882 &self,
883 cx: &mut dyn LayoutOps,
884 children: &[day_core::RNode],
885 p: day_spec::Proposal,
886 ) -> day_spec::Size {
887 match children.first() {
888 Some(&c) => cx.measure_child(c, p),
889 None => day_spec::Size::ZERO,
890 }
891 }
892 fn place(&self, cx: &mut dyn LayoutOps, children: &[day_core::RNode], bounds: day_spec::Rect) {
893 let mut it = children.iter();
894 if let Some(&c) = it.next() {
895 cx.place_child(c, day_spec::Rect::from_size(bounds.size));
896 }
897 for &c in it {
898 cx.place_child(c, day_spec::Rect::ZERO);
899 }
900 }
901 fn baseline(
902 &self,
903 cx: &mut dyn LayoutOps,
904 children: &[day_core::RNode],
905 size: day_spec::Size,
906 ) -> Option<f64> {
907 children.first().and_then(|&c| cx.baseline_of(c, size))
908 }
909}
910
911fn op_context_menu_fn(
912 f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
913) -> impl FnOnce(Build) -> Build {
914 move |inner| {
915 Box::new(move |cx| {
916 let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
917 let mut out = w;
918 cx.under(w, |cx| {
919 out = op_context_menu_fn_body(inner, f, cx);
920 });
921 with_tree(|t| t.forward_whole_row(w, out));
923 out
924 })
925 }
926}
927
928fn op_context_menu_fn_body(
929 inner: Build,
930 f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
931 cx: &mut day_core::BuildCx,
932) -> day_core::RNode {
933 {
934 {
935 let n = inner(cx);
936 let last: Rc<std::cell::RefCell<Option<day_reactive::Scope>>> = Rc::default();
940 {
941 let last = last.clone();
942 day_reactive::Scope::current().on_cleanup(move || {
943 if let Some(s) = last.borrow_mut().take() {
944 s.dispose();
945 }
946 });
947 }
948 let provider: day_spec::ContextMenuFn = Rc::new(move |p| {
949 if let Some(s) = last.borrow_mut().take() {
950 s.dispose();
951 }
952 let scope = day_reactive::Scope::child();
953 let items = scope.enter(|| crate::menus::lower_menu_scoped(f(p)));
954 *last.borrow_mut() = Some(scope);
955 items
956 });
957 with_tree(|t| t.set_context_menu_fn(n, provider.clone()));
958 crate::menus::mount_composed_menu(cx, n, provider);
961 n
962 }
963 }
964}
965
966fn op_gesture(
968 kind: GestureKind,
969 on: impl Fn(RNode, &Event) + 'static,
970) -> impl FnOnce(Build) -> Build {
971 move |inner| {
972 Box::new(move |cx| {
973 let n = inner(cx);
974 with_tree(|t| t.enable_gesture(n, kind));
975 cx.on(n, move |ev| on(n, ev));
976 n
977 })
978 }
979}
980
981fn op_on_drag(
982 axis: Option<day_spec::DragAxis>,
983 f: impl Fn(Drag) + 'static,
984) -> impl FnOnce(Build) -> Build {
985 move |inner| {
986 Box::new(move |cx| {
987 let n = inner(cx);
988 with_tree(|t| {
989 t.enable_gesture(n, GestureKind::Drag);
990 if axis.is_some() {
991 t.set_drag_axis(n, axis);
992 }
993 });
994 cx.on(n, move |ev| {
995 if let Event::Drag {
996 phase,
997 location,
998 translation,
999 } = ev
1000 {
1001 let velocity =
1002 day_core::gesture::velocity(day_core::rnode_to_id(n), GestureKind::Drag);
1003 f(Drag::new(*phase, *location, *translation).with_velocity(velocity));
1004 }
1005 });
1006 n
1007 })
1008 }
1009}
1010
1011fn op_on_pinch(f: impl Fn(Pinch) + 'static) -> impl FnOnce(Build) -> Build {
1012 op_gesture(GestureKind::Pinch, move |_, ev| {
1013 if let Event::Pinch {
1014 phase,
1015 scale,
1016 location,
1017 } = ev
1018 {
1019 f(Pinch::new(*phase, *scale, *location));
1020 }
1021 })
1022}
1023
1024fn op_on_rotate(f: impl Fn(Rotate) + 'static) -> impl FnOnce(Build) -> Build {
1025 op_gesture(GestureKind::Rotate, move |_, ev| {
1026 if let Event::Rotate {
1027 phase,
1028 rotation,
1029 location,
1030 } = ev
1031 {
1032 f(Rotate::new(*phase, Angle::rad(*rotation), *location));
1033 }
1034 })
1035}
1036
1037fn op_on_hover(f: impl Fn(Option<day_spec::Point>) + 'static) -> impl FnOnce(Build) -> Build {
1038 op_gesture(GestureKind::Hover, move |_, ev| {
1039 if let Event::Hover { phase, location } = ev {
1040 f(match phase {
1045 day_spec::DragPhase::Ended => None,
1046 _ => Some(*location),
1047 });
1048 }
1049 })
1050}
1051
1052fn op_on_pan(f: impl Fn(Pan) + 'static) -> impl FnOnce(Build) -> Build {
1053 op_gesture(GestureKind::Pan, move |n, ev| {
1054 if let Event::Pan {
1055 phase,
1056 delta,
1057 location,
1058 } = ev
1059 {
1060 let velocity = day_core::gesture::velocity(day_core::rnode_to_id(n), GestureKind::Pan);
1061 f(Pan::new(*phase, *delta, *location).with_velocity(velocity));
1062 }
1063 })
1064}
1065
1066fn op_on_long_press(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
1067 op_gesture(GestureKind::LongPress, move |_, ev| {
1068 if let Event::LongPress(at) = ev {
1069 f(*at);
1070 }
1071 })
1072}
1073
1074fn op_on_double_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
1075 op_gesture(GestureKind::DoubleTap, move |_, ev| {
1076 if matches!(ev, Event::DoubleTap(_)) {
1077 f();
1078 }
1079 })
1080}
1081
1082fn op_on_double_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
1083 op_gesture(GestureKind::DoubleTap, move |_, ev| {
1084 if let Event::DoubleTap(at) = ev {
1085 f(*at);
1086 }
1087 })
1088}
1089
1090fn op_on_pressed(f: impl Fn(bool) + 'static) -> impl FnOnce(Build) -> Build {
1091 op_gesture(GestureKind::Press, move |_, ev| {
1092 if let Event::Press { pressed, .. } = ev {
1093 f(*pressed);
1094 }
1095 })
1096}
1097
1098fn op_on_touches(f: impl Fn(&[day_spec::Touch]) + 'static) -> impl FnOnce(Build) -> Build {
1099 op_gesture(GestureKind::Touches, move |_, ev| {
1100 if let Event::Touches(touches) = ev {
1101 f(touches);
1102 }
1103 })
1104}
1105
1106fn op_hit_slop(slop: Insets) -> impl FnOnce(Build) -> Build {
1107 move |inner| {
1108 Box::new(move |cx| {
1109 let n = inner(cx);
1110 with_tree(|t| t.set_hit_slop(n, slop));
1111 n
1112 })
1113 }
1114}
1115
1116fn op_interaction(state: InteractionState) -> impl FnOnce(Build) -> Build {
1117 move |inner| {
1118 Box::new(move |cx| {
1119 let n = inner(cx);
1120 with_tree(|t| {
1121 t.enable_gesture(n, GestureKind::Hover);
1122 t.enable_gesture(n, GestureKind::Press);
1123 });
1124 cx.on(n, move |ev| match ev {
1125 Event::Hover { phase, .. } => {
1126 state.hovered.set(*phase != day_spec::DragPhase::Ended);
1127 }
1128 Event::Press { pressed, .. } => state.pressed.set(*pressed),
1129 Event::FocusChanged(focused) => state.focused.set(*focused),
1130 _ => {}
1131 });
1132 n
1133 })
1134 }
1135}
1136
1137fn op_enabled(enabled: Reactive<bool>) -> impl FnOnce(Build) -> Build {
1138 move |inner| {
1139 Box::new(move |cx| {
1140 let n = inner(cx);
1141 let apply = move |on: bool| {
1142 day_core::gesture::set_subtree_enabled(n, on);
1143 if !on {
1145 day_core::enqueue_event(
1146 day_core::rnode_to_id(n),
1147 Event::Hover {
1148 phase: day_spec::DragPhase::Ended,
1149 location: day_spec::Point::ZERO,
1150 },
1151 );
1152 }
1153 };
1154 if !enabled.get_untracked() {
1156 apply(false);
1157 }
1158 if let Reactive::Dyn(_) = &enabled {
1159 bind(move || enabled.get(), move |on: &bool| apply(*on));
1160 }
1161 n
1162 })
1163 }
1164}
1165
1166#[derive(Clone, Copy)]
1186pub struct InteractionState {
1187 hovered: Signal<bool>,
1188 pressed: Signal<bool>,
1189 focused: Signal<bool>,
1190}
1191
1192impl Default for InteractionState {
1193 fn default() -> Self {
1194 Self::new()
1195 }
1196}
1197
1198impl InteractionState {
1199 #[must_use]
1201 pub fn new() -> Self {
1202 InteractionState {
1203 hovered: Signal::new(false),
1204 pressed: Signal::new(false),
1205 focused: Signal::new(false),
1206 }
1207 }
1208 #[must_use]
1210 pub fn hovered(&self) -> bool {
1211 self.hovered.get()
1212 }
1213 #[must_use]
1215 pub fn pressed(&self) -> bool {
1216 self.pressed.get()
1217 }
1218 #[must_use]
1220 pub fn focused(&self) -> bool {
1221 self.focused.get()
1222 }
1223}
1224
1225fn op_background(fill: Reactive<Paint>) -> impl FnOnce(Build) -> Build {
1226 move |inner| {
1227 Box::new(move |cx| {
1228 let seed = fill.get_untracked();
1229 let node = cx.native(
1230 kinds::CONTAINER,
1231 &ContainerProps {
1232 fill: Some(seed.clone()),
1233 ..Default::default()
1234 },
1235 Rc::new(FillThrough),
1236 Flex::default(),
1237 Boundary::No,
1238 );
1239 cx.under(node, |cx| {
1240 let _ = inner(cx);
1241 });
1242 if let Reactive::Dyn(_) = &fill {
1245 day_reactive::bind_seeded(
1246 seed,
1247 move || fill.get(),
1248 move |p: &Paint| {
1249 with_tree(|t| {
1250 t.patch(node, Box::new(ContainerPatch::Fill(Some(p.clone()))), false);
1251 });
1252 },
1253 );
1254 }
1255 node
1256 })
1257 }
1258}
1259
1260fn op_surface(role: day_spec::SurfaceRole, radius: f64) -> impl FnOnce(Build) -> Build {
1263 move |inner| {
1264 Box::new(move |cx| {
1265 let w = cx.native(
1266 kinds::CONTAINER,
1267 &ContainerProps {
1268 corner_radius: radius,
1269 clips: true,
1270 role: Some(role),
1271 ..Default::default()
1272 },
1273 Rc::new(FillThrough),
1274 Flex::default(),
1275 Boundary::No,
1276 );
1277 cx.under(w, |cx| {
1278 let _ = inner(cx);
1279 });
1280 w
1281 })
1282 }
1283}
1284
1285#[derive(Clone, Debug, Default, PartialEq)]
1311#[must_use]
1312pub struct Surface {
1313 fill: Option<Paint>,
1314 radius: crate::Corner,
1315 corners: day_spec::Corners,
1316 border: Option<day_spec::Border>,
1317 shadow: Option<day_spec::Shadow>,
1318}
1319
1320impl Surface {
1321 pub fn new() -> Self {
1323 Surface::default()
1324 }
1325 pub fn fill(mut self, fill: impl Into<Paint>) -> Self {
1329 self.fill = Some(fill.into());
1330 self
1331 }
1332 pub fn corner_radius(mut self, radius: impl Into<crate::Corner>) -> Self {
1336 self.radius = radius.into();
1337 self
1338 }
1339 pub fn corners(mut self, corners: day_spec::Corners) -> Self {
1341 self.corners = corners;
1342 self
1343 }
1344 pub fn border(mut self, color: impl Into<Ink>, width: f64) -> Self {
1347 self.border = (width > 0.0).then(|| day_spec::Border::new(color, width));
1348 self
1349 }
1350 pub fn shadow(mut self, shadow: day_spec::Shadow) -> Self {
1354 self.shadow = Some(shadow);
1355 self
1356 }
1357
1358 fn props(&self, size: day_spec::Size, clip: Clip) -> ContainerProps {
1361 let radius = match self.radius {
1362 crate::Corner::Fixed(points) => points.max(0.0),
1363 relative @ crate::Corner::Fraction(_) => relative.points(size),
1364 };
1365 let rounded = radius > 0.0 || self.radius.is_relative();
1366 ContainerProps {
1367 fill: self.fill.clone(),
1368 corner_radius: radius,
1369 corners: self.corners,
1370 border: self.border,
1371 shadow: self.shadow,
1372 clips: match clip {
1373 Clip::Always => true,
1374 Clip::WhenRounded => rounded && self.shadow.is_none(),
1375 },
1376 role: None,
1377 }
1378 }
1379}
1380
1381#[derive(Clone, Copy)]
1383enum Clip {
1384 WhenRounded,
1386 Always,
1389}
1390
1391fn op_styled_surface(surface: Reactive<Surface>, clip: Clip) -> impl FnOnce(Build) -> Build {
1395 move |inner| {
1396 Box::new(move |cx| {
1397 let seed = surface.get_untracked();
1398 let size = Rc::new(Cell::new(day_spec::Size::ZERO));
1399 let node = cx.native(
1400 kinds::CONTAINER,
1401 &seed.props(size.get(), clip),
1402 Rc::new(FillThrough),
1403 Flex::default(),
1404 Boundary::No,
1405 );
1406 cx.under(node, |cx| {
1407 let _ = inner(cx);
1408 });
1409 let current = Rc::new(std::cell::RefCell::new(seed.clone()));
1410 let send = {
1411 let (size, current) = (size.clone(), current.clone());
1412 move || {
1413 let props = current.borrow().props(size.get(), clip);
1414 with_tree(|t| {
1415 t.patch(
1416 node,
1417 Box::new(ContainerPatch::Surface(Box::new(props))),
1418 false,
1419 );
1420 });
1421 }
1422 };
1423 let relative = match &surface {
1424 Reactive::Const(s) => s.radius.is_relative(),
1425 Reactive::Dyn(_) => true,
1427 };
1428 if relative {
1429 let (size, current) = (size.clone(), current.clone());
1432 day_core::patch_on_frame(
1433 node,
1434 Rc::new(move |new: day_spec::Size| {
1435 if new.approx_eq(size.get(), 0.25) {
1436 return None;
1437 }
1438 size.set(new);
1439 let surface = current.try_borrow().ok()?;
1440 surface.radius.is_relative().then(|| {
1441 Box::new(ContainerPatch::Surface(Box::new(surface.props(new, clip))))
1442 as Box<dyn std::any::Any>
1443 })
1444 }),
1445 );
1446 day_reactive::Scope::current()
1447 .on_cleanup(move || day_core::stop_frame_patches(node));
1448 }
1449 if let Reactive::Dyn(_) = &surface {
1450 day_reactive::bind_seeded(
1451 seed,
1452 move || surface.get(),
1453 move |s: &Surface| {
1454 *current.borrow_mut() = s.clone();
1455 send();
1456 },
1457 );
1458 }
1459 node
1460 })
1461 }
1462}
1463
1464fn reactive_map2<A: Clone + 'static, B: Clone + 'static, T: Clone + 'static>(
1466 a: Reactive<A>,
1467 b: Reactive<B>,
1468 f: impl Fn(A, B) -> T + 'static,
1469) -> Reactive<T> {
1470 match (&a, &b) {
1471 (Reactive::Const(x), Reactive::Const(y)) => Reactive::Const(f(x.clone(), y.clone())),
1472 _ => Reactive::Dyn(Rc::new(move || f(a.get(), b.get()))),
1473 }
1474}
1475
1476fn reactive_map<A: Clone + 'static, T: Clone + 'static>(
1478 a: Reactive<A>,
1479 f: impl Fn(A) -> T + 'static,
1480) -> Reactive<T> {
1481 match &a {
1482 Reactive::Const(x) => Reactive::Const(f(x.clone())),
1483 Reactive::Dyn(_) => Reactive::Dyn(Rc::new(move || f(a.get()))),
1484 }
1485}
1486
1487fn op_opacity(op: Reactive<f64>) -> impl FnOnce(Build) -> Build {
1488 move |inner| {
1489 Box::new(move |cx| {
1490 let node = layer_node(cx);
1491 cx.under(node, |cx| {
1492 let _ = inner(cx);
1493 });
1494 bind(
1495 move || op.get(),
1496 move |v: &f64| with_tree(|t| t.set_node_opacity(node, *v)),
1497 );
1498 node
1499 })
1500 }
1501}
1502
1503fn op_transform(t: Reactive<Transform>) -> impl FnOnce(Build) -> Build {
1504 move |inner| {
1505 Box::new(move |cx| {
1506 let node = layer_node(cx);
1507 cx.under(node, |cx| {
1508 let _ = inner(cx);
1509 });
1510 bind(
1511 move || t.get(),
1512 move |v: &Transform| with_tree(|tr| tr.set_node_transform(node, *v)),
1513 );
1514 node
1515 })
1516 }
1517}
1518
1519fn op_animation(anim: AnimSpec) -> impl FnOnce(Build) -> Build {
1520 move |inner| {
1521 Box::new(move |cx| {
1522 let node = cx.layout_only(Rc::new(FillThrough), Flex::default(), Boundary::No);
1528 with_tree(|t| t.set_implicit_anim(node, Some(anim)));
1529 cx.under(node, |cx| {
1530 let _ = inner(cx);
1531 });
1532 node
1533 })
1534 }
1535}
1536
1537fn op_overlay_aligned(align: Alignment, over: impl Piece) -> impl FnOnce(Build) -> Build {
1538 move |inner| {
1539 Box::new(move |cx| {
1540 let node = cx.native(
1541 kinds::CONTAINER,
1542 &ContainerProps::default(),
1543 Rc::new(OverlayLayout {
1544 align,
1545 size_to_first: true,
1546 }),
1547 Flex::default(),
1548 Boundary::No,
1549 );
1550 cx.under(node, |cx| {
1551 let _ = inner(cx); let _ = over.build(cx); });
1554 node
1555 })
1556 }
1557}
1558
1559fn op_aspect_ratio(ratio: Reactive<f64>) -> impl FnOnce(Build) -> Build {
1560 move |inner| {
1561 Box::new(move |cx| {
1562 if let Reactive::Const(r) = &ratio
1563 && !(r.is_finite() && *r > 0.0)
1564 {
1565 return inner(cx);
1566 }
1567 let layout = Rc::new(AspectRatioLayout {
1568 ratio: Cell::new(ratio.get_untracked()),
1569 });
1570 let node = cx.layout_only(
1571 layout.clone(),
1572 Flex::default(),
1573 Boundary::No,
1576 );
1577 cx.under(node, |cx| {
1578 let _ = inner(cx);
1579 });
1580 bind_length(ratio, move |v| layout.ratio.set(v), node);
1581 node
1582 })
1583 }
1584}
1585
1586fn op_aligned(align: Alignment) -> impl FnOnce(Build) -> Build {
1587 move |inner| {
1588 Box::new(move |cx| {
1589 let node = cx.layout_only(
1590 Rc::new(AlignmentLayout { align }),
1591 Flex::default(),
1592 Boundary::No,
1593 );
1594 cx.under(node, |cx| {
1595 let _ = inner(cx);
1596 });
1597 node
1598 })
1599 }
1600}
1601
1602fn op_grow(grow: Grow) -> impl FnOnce(Build) -> Build {
1603 let w = matches!(grow.dimension, Dimension::Width | Dimension::Both);
1604 let h = matches!(grow.dimension, Dimension::Height | Dimension::Both);
1605 move |inner| {
1606 Box::new(move |cx| {
1607 let node = cx.layout_only(
1608 Rc::new(GrowLayout { w, h }),
1609 Flex {
1610 grow_w: w,
1611 grow_h: h,
1612 grow_weight: grow.weight,
1613 ..Default::default()
1614 },
1615 Boundary::No,
1616 );
1617 cx.under(node, |cx| {
1618 let _ = inner(cx);
1619 });
1620 node
1621 })
1622 }
1623}
1624
1625fn op_grid_facts(facts: GridFacts) -> impl FnOnce(RNode) {
1626 move |node| with_tree(|t| t.set_grid_facts(node, facts))
1627}
1628
1629fn op_defers_system_gestures(edges: day_spec::Edges) -> impl FnOnce(Build) -> Build {
1630 move |inner| {
1631 Box::new(move |cx| {
1632 let token = day_core::shield::push_gesture_deferral(edges);
1633 Scope::current().on_cleanup(move || day_core::shield::pop_gesture_deferral(token));
1634 inner(cx)
1635 })
1636 }
1637}
1638
1639fn op_status_bar_hidden(hidden: Reactive<bool>) -> impl FnOnce(Build) -> Build {
1640 move |inner| {
1641 Box::new(move |cx| {
1642 let token = day_core::shield::push_status_bar_request(hidden.get_untracked());
1643 Scope::current().on_cleanup(move || day_core::shield::pop_status_bar_request(token));
1644 if let Reactive::Dyn(_) = &hidden {
1647 bind(
1648 move || hidden.get(),
1649 move |h: &bool| day_core::shield::set_status_bar_request(token, *h),
1650 );
1651 }
1652 inner(cx)
1653 })
1654 }
1655}
1656
1657fn op_on_system_back(
1658 enabled: Reactive<bool>,
1659 handler: Rc<dyn Fn()>,
1660) -> impl FnOnce(Build) -> Build {
1661 move |inner| {
1662 Box::new(move |cx| {
1663 crate::nav::install_back_handler(cx.parent(), enabled, handler);
1664 inner(cx)
1665 })
1666 }
1667}
1668
1669fn op_interactive_dismiss_disabled() -> impl FnOnce(Build) -> Build {
1670 move |inner| {
1671 Box::new(move |cx| {
1672 let token = day_core::shield::push_dismiss_disabled();
1673 Scope::current().on_cleanup(move || day_core::shield::pop_dismiss_disabled(token));
1674 inner(cx)
1675 })
1676 }
1677}
1678
1679impl<P: Piece> Decorated<P> {
1686 pub fn id(self, id: day_core::ElementId) -> Self {
1687 self.push_node(op_id(id))
1688 }
1689 pub fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Self {
1690 self.push_node(op_id_of(id))
1691 }
1692 pub fn wrapper_id(self, id: day_core::ElementId) -> Self {
1693 self.push(op_wrapper_id(id))
1694 }
1695 pub fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Self {
1696 self.push(op_tweak(f))
1697 }
1698 pub fn selectable(self) -> Self {
1699 self.push(op_selectable())
1700 }
1701 pub fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Self {
1702 self.push(op_cursor(cursor.into_reactive()))
1703 }
1704 pub fn layout_direction<M>(
1705 self,
1706 direction: impl IntoReactive<day_spec::LayoutDirection, M>,
1707 ) -> Self {
1708 self.push(op_layout_direction(direction.into_reactive()))
1709 }
1710 pub fn native_ref(self, r: &NativeRef) -> Self {
1711 self.push(op_native_ref(r.clone()))
1712 }
1713 pub fn window_drag_region(self) -> Self {
1714 self.push(op_window_drag_region())
1715 }
1716 pub fn padding<M>(self, insets: impl IntoReactive<Insets, M>) -> Self {
1717 self.push(op_padding(insets.into_reactive()))
1718 }
1719 pub fn max_width<M>(self, max: impl IntoReactive<f64, M>) -> Self {
1720 self.push(op_max_width(max.into_reactive()))
1721 }
1722 pub fn max_height<M>(self, max: impl IntoReactive<f64, M>) -> Self {
1727 self.push(op_max_height(max.into_reactive()))
1728 }
1729 pub fn min_width<M>(self, min: impl IntoReactive<f64, M>) -> Self {
1733 self.push(op_min_width(min.into_reactive()))
1734 }
1735 pub fn reserving<M>(self, sample: impl IntoText<M>) -> Self {
1736 self.push(op_reserving(sample.into_text()))
1737 }
1738 pub fn frame<Mw, Mh>(
1741 self,
1742 width: impl IntoReactive<f64, Mw>,
1743 height: impl IntoReactive<f64, Mh>,
1744 ) -> Self {
1745 self.push(op_frame(
1746 Some(width.into_reactive()),
1747 Some(height.into_reactive()),
1748 ))
1749 }
1750 pub fn width<M>(self, width: impl IntoReactive<f64, M>) -> Self {
1752 self.push(op_frame(Some(width.into_reactive()), None))
1753 }
1754 pub fn height<M>(self, height: impl IntoReactive<f64, M>) -> Self {
1756 self.push(op_frame(None, Some(height.into_reactive())))
1757 }
1758 pub fn min_height<M>(self, min: impl IntoReactive<f64, M>) -> Self {
1760 self.push(op_min_height(min.into_reactive()))
1761 }
1762 pub fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Self {
1763 self.push(op_a11y(f))
1764 }
1765 pub fn on_tap(self, f: impl Fn() + 'static) -> Self {
1771 self.push(op_on_tap(f))
1772 }
1773 pub fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1776 self.push(op_on_tap_at(f))
1777 }
1778 pub fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Self {
1779 let (want, on_native) = binding.into_focus_binding();
1780 self.push(op_focused(want, on_native))
1781 }
1782 pub fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
1783 self.push(op_on_key(false, f))
1784 }
1785 pub fn on_key_up(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
1786 self.push(op_on_key(true, f))
1787 }
1788 pub fn focusable(self) -> Self {
1789 self.push(op_focusable())
1790 }
1791 pub fn keyboard(self) -> Self {
1792 self.push(op_keyboard())
1793 }
1794 pub fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Self {
1795 self.push(op_toolbar(content.into_source()))
1796 }
1797 pub fn searchable(self, search: crate::Search) -> Self {
1799 self.push(move |inner| {
1800 Box::new(move |cx| {
1801 let n = inner(cx);
1802 crate::nav::install_page_search(search);
1803 n
1804 })
1805 })
1806 }
1807 pub fn drag_source(
1809 self,
1810 source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
1811 ) -> Self {
1812 self.push(move |inner| {
1813 Box::new(move |cx| {
1814 let n = layer_node(cx);
1815 cx.under(n, |cx| {
1816 inner(cx);
1817 });
1818 let source = scoped_drag_source(Rc::new(source));
1819 with_tree(|t| t.set_drag_source(n, source));
1820 n
1821 })
1822 })
1823 }
1824 pub fn drop_target(self, target: day_spec::transfer::Target) -> Self {
1826 self.push(move |inner| {
1827 Box::new(move |cx| {
1828 let n = layer_node(cx);
1829 cx.under(n, |cx| {
1830 inner(cx);
1831 });
1832 let target = scoped_drop_target(target);
1833 with_tree(|t| t.set_drop_target(n, target));
1834 n
1835 })
1836 })
1837 }
1838 pub fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Self {
1839 match menu.into_context_menu() {
1840 ContextMenuSource::Fixed(items) => self.push(op_context_menu(items)),
1841 ContextMenuSource::OnSummon(f) => self.push(op_context_menu_fn(f)),
1842 }
1843 }
1844 pub fn on_drag(self, f: impl Fn(Drag) + 'static) -> Self {
1845 self.push(op_on_drag(None, f))
1846 }
1847 pub fn on_drag_along(self, axis: day_spec::DragAxis, f: impl Fn(Drag) + 'static) -> Self {
1848 self.push(op_on_drag(Some(axis), f))
1849 }
1850 pub fn on_long_press(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1851 self.push(op_on_long_press(f))
1852 }
1853 pub fn on_double_tap(self, f: impl Fn() + 'static) -> Self {
1854 self.push(op_on_double_tap(f))
1855 }
1856 pub fn on_double_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1858 self.push(op_on_double_tap_at(f))
1859 }
1860 pub fn on_pressed(self, f: impl Fn(bool) + 'static) -> Self {
1861 self.push(op_on_pressed(f))
1862 }
1863 pub fn on_touches(self, f: impl Fn(&[day_spec::Touch]) + 'static) -> Self {
1864 self.push(op_on_touches(f))
1865 }
1866 pub fn hit_slop(self, slop: impl Into<Insets>) -> Self {
1867 self.push(op_hit_slop(slop.into()))
1868 }
1869 pub fn interaction(self, state: InteractionState) -> Self {
1870 self.push(op_interaction(state))
1871 }
1872 pub fn enabled<M>(self, enabled: impl IntoReactive<bool, M>) -> Self {
1873 self.push(op_enabled(enabled.into_reactive()))
1874 }
1875 pub fn on_files_dropped(self, f: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Self {
1876 self.drop_target(day_spec::transfer::Target::files().on_drop(move |drop| {
1877 let paths = drop.file_paths();
1878 let any = !paths.is_empty();
1879 if any {
1880 f(paths);
1881 }
1882 any
1883 }))
1884 }
1885 pub fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Self {
1886 self.push(op_on_pinch(f))
1887 }
1888 pub fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Self {
1889 self.push(op_on_rotate(f))
1890 }
1891 pub fn on_pan(self, f: impl Fn(Pan) + 'static) -> Self {
1892 self.push(op_on_pan(f))
1893 }
1894 pub fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Self {
1902 self.push(op_on_hover(f))
1903 }
1904 pub fn card(self) -> Self {
1908 self.padding(crate::Space::M).push(op_surface(
1909 day_spec::SurfaceRole::SectionCard,
1910 crate::Radius::M.points(),
1911 ))
1912 }
1913 pub fn background<M>(self, fill: impl IntoReactive<Paint, M>) -> Self {
1914 self.push(op_background(fill.into_reactive()))
1915 }
1916 pub fn corner_radius<M>(self, radius: impl IntoReactive<crate::Corner, M>) -> Self {
1917 let surface = reactive_map(radius.into_reactive(), |r| Surface::new().corner_radius(r));
1918 self.push(op_styled_surface(surface, Clip::Always))
1919 }
1920 pub fn surface<M>(self, surface: impl IntoReactive<Surface, M>) -> Self {
1921 self.push(op_styled_surface(
1922 surface.into_reactive(),
1923 Clip::WhenRounded,
1924 ))
1925 }
1926 pub fn border<Mc, Mw>(
1927 self,
1928 color: impl IntoReactive<Ink, Mc>,
1929 width: impl IntoReactive<f64, Mw>,
1930 ) -> Self {
1931 let surface = reactive_map2(color.into_reactive(), width.into_reactive(), |c, w| {
1932 Surface::new().border(c, w)
1933 });
1934 self.push(op_styled_surface(surface, Clip::WhenRounded))
1935 }
1936 pub fn shadow<M>(self, shadow: impl IntoReactive<day_spec::Shadow, M>) -> Self {
1937 let surface = reactive_map(shadow.into_reactive(), |s| Surface::new().shadow(s));
1938 self.push(op_styled_surface(surface, Clip::WhenRounded))
1939 }
1940 pub fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Self {
1941 self.push(op_opacity(opacity.into_reactive()))
1942 }
1943 pub fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Self {
1944 self.push(op_transform(t.into_reactive()))
1945 }
1946 pub fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Self {
1947 let f = factor.into_reactive();
1948 self.transform(move || Transform::scale(f.get(), f.get()))
1949 }
1950 pub fn rotation<M>(self, angle: impl IntoReactive<Angle, M>) -> Self {
1951 let a = angle.into_reactive();
1952 self.transform(move || Transform::rotate(a.get()))
1953 }
1954 pub fn translation<Mx, My>(
1955 self,
1956 x: impl IntoReactive<f64, Mx>,
1957 y: impl IntoReactive<f64, My>,
1958 ) -> Self {
1959 let (x, y) = (x.into_reactive(), y.into_reactive());
1960 self.transform(move || Transform::translate(x.get(), y.get()))
1961 }
1962 pub fn animation(self, anim: AnimSpec) -> Self {
1963 self.push(op_animation(anim))
1964 }
1965 pub fn modifier(self, m: impl Modifier) -> AnyPiece {
1967 m.apply(self.any())
1968 }
1969 pub fn overlay(self, over: impl Piece) -> Self {
1970 self.overlay_aligned(Alignment::Center, over)
1971 }
1972 pub fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Self {
1973 self.push(op_overlay_aligned(align, over))
1974 }
1975 pub fn aspect_ratio<M>(self, ratio: impl IntoReactive<f64, M>) -> Self {
1976 self.push(op_aspect_ratio(ratio.into_reactive()))
1977 }
1978 pub fn aligned(self, alignment: Alignment) -> Self {
1980 self.push(op_aligned(alignment))
1981 }
1982 pub fn grow(self, grow: impl Into<Grow>) -> Self {
1984 self.push(op_grow(grow.into()))
1985 }
1986 #[deprecated(note = "use .grow(Dimension::Width)")]
1987 pub fn grow_w(self) -> Self {
1988 self.grow(Dimension::Width)
1989 }
1990 #[deprecated(note = "use .grow(Dimension::Height)")]
1991 pub fn grow_h(self) -> Self {
1992 self.grow(Dimension::Height)
1993 }
1994 pub fn grid_span(self, n: usize) -> Self {
1995 self.push_outer(op_grid_facts(GridFacts {
1996 col_span: n.clamp(1, u16::MAX as usize) as u16,
1997 ..Default::default()
1998 }))
1999 }
2000 pub fn grid_align(self, a: Alignment) -> Self {
2001 self.push_outer(op_grid_facts(GridFacts {
2002 align: Some(a),
2003 ..Default::default()
2004 }))
2005 }
2006 pub fn defers_system_gestures(self, edges: day_spec::Edges) -> Self {
2007 self.push(op_defers_system_gestures(edges))
2008 }
2009 pub fn interactive_dismiss_disabled(self) -> Self {
2010 self.push(op_interactive_dismiss_disabled())
2011 }
2012 pub fn on_system_back<M>(
2013 self,
2014 enabled: impl IntoReactive<bool, M>,
2015 handler: impl Fn() + 'static,
2016 ) -> Self {
2017 self.push(op_on_system_back(enabled.into_reactive(), Rc::new(handler)))
2018 }
2019 pub fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Self {
2020 self.push(op_status_bar_hidden(hidden.into_reactive()))
2021 }
2022 pub fn any(self) -> AnyPiece {
2024 AnyPiece::new(self)
2025 }
2026}
2027
2028pub enum ContextMenuSource {
2030 Fixed(Vec<MenuEntry>),
2031 OnSummon(Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>),
2032}
2033
2034pub trait ContextMenuContent<M> {
2038 fn into_context_menu(self) -> ContextMenuSource;
2039}
2040
2041pub struct AtPointMark;
2043
2044impl ContextMenuContent<crate::ManyMark> for Vec<MenuEntry> {
2045 fn into_context_menu(self) -> ContextMenuSource {
2046 ContextMenuSource::Fixed(self)
2047 }
2048}
2049
2050impl<const N: usize> ContextMenuContent<crate::ManyMark> for [MenuEntry; N] {
2051 fn into_context_menu(self) -> ContextMenuSource {
2052 ContextMenuSource::Fixed(Vec::from(self))
2053 }
2054}
2055
2056impl<C, F> ContextMenuContent<crate::DerivedMark> for F
2057where
2058 C: IntoIterator<Item = MenuEntry>,
2059 F: Fn() -> C + 'static,
2060{
2061 fn into_context_menu(self) -> ContextMenuSource {
2062 ContextMenuSource::OnSummon(Rc::new(move |_| self().into_iter().collect()))
2063 }
2064}
2065
2066impl<C, F> ContextMenuContent<AtPointMark> for F
2067where
2068 C: IntoIterator<Item = MenuEntry>,
2069 F: Fn(day_spec::Point) -> C + 'static,
2070{
2071 fn into_context_menu(self) -> ContextMenuSource {
2072 ContextMenuSource::OnSummon(Rc::new(move |p| self(p).into_iter().collect()))
2073 }
2074}
2075
2076pub trait Decorate: Piece + Sized {
2077 fn id(self, id: day_core::ElementId) -> Decorated<Self> {
2083 Decorated::new(self).id(id)
2084 }
2085
2086 fn wrapper_id(self, id: day_core::ElementId) -> Decorated<Self> {
2090 Decorated::new(self).wrapper_id(id)
2091 }
2092
2093 fn apply_if(
2098 self,
2099 cond: bool,
2100 f: impl FnOnce(Decorated<Self>) -> Decorated<Self>,
2101 ) -> Decorated<Self> {
2102 Decorated::new(self).apply_if(cond, f)
2103 }
2104
2105 fn apply_some<T>(
2108 self,
2109 value: Option<T>,
2110 f: impl FnOnce(Decorated<Self>, T) -> Decorated<Self>,
2111 ) -> Decorated<Self> {
2112 Decorated::new(self).apply_some(value, f)
2113 }
2114
2115 fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Decorated<Self> {
2122 Decorated::new(self).id_of(id)
2123 }
2124
2125 fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Decorated<Self> {
2138 Decorated::new(self).tweak(f)
2139 }
2140
2141 fn selectable(self) -> Decorated<Self> {
2153 Decorated::new(self).selectable()
2154 }
2155
2156 fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Decorated<Self> {
2163 Decorated::new(self).cursor(cursor)
2164 }
2165
2166 fn layout_direction<M>(
2182 self,
2183 direction: impl IntoReactive<day_spec::LayoutDirection, M>,
2184 ) -> Decorated<Self> {
2185 Decorated::new(self).layout_direction(direction)
2186 }
2187
2188 fn window_drag_region(self) -> Decorated<Self> {
2198 Decorated::new(self).window_drag_region()
2199 }
2200
2201 fn native_ref(self, r: &NativeRef) -> Decorated<Self> {
2204 Decorated::new(self).native_ref(r)
2205 }
2206
2207 fn padding<M>(self, insets: impl IntoReactive<Insets, M>) -> Decorated<Self> {
2212 Decorated::new(self).padding(insets)
2213 }
2214
2215 fn max_width<M>(self, max: impl IntoReactive<f64, M>) -> Decorated<Self> {
2220 Decorated::new(self).max_width(max)
2221 }
2222 fn max_height<M>(self, max: impl IntoReactive<f64, M>) -> Decorated<Self> {
2226 Decorated::new(self).max_height(max)
2227 }
2228 fn min_width<M>(self, min: impl IntoReactive<f64, M>) -> Decorated<Self> {
2232 Decorated::new(self).min_width(min)
2233 }
2234
2235 fn min_height<M>(self, min: impl IntoReactive<f64, M>) -> Decorated<Self> {
2238 Decorated::new(self).min_height(min)
2239 }
2240
2241 fn reserving<M>(self, sample: impl IntoText<M>) -> Decorated<Self> {
2255 Decorated::new(self).reserving(sample)
2256 }
2257
2258 fn frame<Mw, Mh>(
2259 self,
2260 width: impl IntoReactive<f64, Mw>,
2261 height: impl IntoReactive<f64, Mh>,
2262 ) -> Decorated<Self> {
2263 Decorated::new(self).frame(width, height)
2264 }
2265
2266 fn width<M>(self, width: impl IntoReactive<f64, M>) -> Decorated<Self> {
2270 Decorated::new(self).width(width)
2271 }
2272
2273 fn height<M>(self, height: impl IntoReactive<f64, M>) -> Decorated<Self> {
2276 Decorated::new(self).height(height)
2277 }
2278
2279 fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Decorated<Self> {
2280 Decorated::new(self).a11y(f)
2281 }
2282
2283 fn on_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
2289 Decorated::new(self).on_tap(f)
2290 }
2291
2292 fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2306 Decorated::new(self).on_tap_at(f)
2307 }
2308
2309 fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Decorated<Self> {
2316 Decorated::new(self).focused(binding)
2317 }
2318
2319 fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
2342 Decorated::new(self).on_key(f)
2343 }
2344
2345 fn on_key_up(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
2350 Decorated::new(self).on_key_up(f)
2351 }
2352
2353 fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Decorated<Self> {
2369 Decorated::new(self).toolbar(content)
2370 }
2371
2372 fn searchable(self, search: crate::Search) -> Decorated<Self> {
2380 Decorated::new(self).searchable(search)
2381 }
2382
2383 fn focusable(self) -> Decorated<Self> {
2389 Decorated::new(self).focusable()
2390 }
2391
2392 fn keyboard(self) -> Decorated<Self> {
2418 Decorated::new(self).keyboard()
2419 }
2420
2421 fn drag_source(
2425 self,
2426 source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
2427 ) -> Decorated<Self> {
2428 Decorated::new(self).drag_source(source)
2429 }
2430 fn drop_target(self, target: day_spec::transfer::Target) -> Decorated<Self> {
2443 Decorated::new(self).drop_target(target)
2444 }
2445
2446 fn on_files_dropped(self, f: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Decorated<Self> {
2450 Decorated::new(self).on_files_dropped(f)
2451 }
2452 fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Decorated<Self> {
2463 Decorated::new(self).context_menu(menu)
2464 }
2465
2466 fn on_drag(self, f: impl Fn(Drag) + 'static) -> Decorated<Self> {
2471 Decorated::new(self).on_drag(f)
2472 }
2473
2474 fn on_drag_along(
2483 self,
2484 axis: day_spec::DragAxis,
2485 f: impl Fn(Drag) + 'static,
2486 ) -> Decorated<Self> {
2487 Decorated::new(self).on_drag_along(axis, f)
2488 }
2489
2490 fn on_long_press(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2496 Decorated::new(self).on_long_press(f)
2497 }
2498
2499 fn on_double_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
2503 Decorated::new(self).on_double_tap(f)
2504 }
2505
2506 fn on_double_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2510 Decorated::new(self).on_double_tap_at(f)
2511 }
2512
2513 fn on_pressed(self, f: impl Fn(bool) + 'static) -> Decorated<Self> {
2519 Decorated::new(self).on_pressed(f)
2520 }
2521
2522 fn on_touches(self, f: impl Fn(&[day_spec::Touch]) + 'static) -> Decorated<Self> {
2528 Decorated::new(self).on_touches(f)
2529 }
2530
2531 fn hit_slop(self, slop: impl Into<Insets>) -> Decorated<Self> {
2536 Decorated::new(self).hit_slop(slop)
2537 }
2538
2539 fn interaction(self, state: InteractionState) -> Decorated<Self> {
2542 Decorated::new(self).interaction(state)
2543 }
2544
2545 fn enabled<M>(self, enabled: impl IntoReactive<bool, M>) -> Decorated<Self> {
2557 Decorated::new(self).enabled(enabled)
2558 }
2559
2560 fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Decorated<Self> {
2564 Decorated::new(self).on_pinch(f)
2565 }
2566
2567 fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Decorated<Self> {
2572 Decorated::new(self).on_rotate(f)
2573 }
2574
2575 fn on_pan(self, f: impl Fn(Pan) + 'static) -> Decorated<Self> {
2579 Decorated::new(self).on_pan(f)
2580 }
2581
2582 fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Decorated<Self> {
2586 Decorated::new(self).on_hover(f)
2587 }
2588
2589 fn card(self) -> Decorated<Self> {
2593 Decorated::new(self).card()
2594 }
2595
2596 fn background<M>(self, fill: impl IntoReactive<Paint, M>) -> Decorated<Self> {
2604 Decorated::new(self).background(fill)
2605 }
2606
2607 fn corner_radius<M>(self, radius: impl IntoReactive<crate::Corner, M>) -> Decorated<Self> {
2613 Decorated::new(self).corner_radius(radius)
2614 }
2615
2616 fn surface<M>(self, surface: impl IntoReactive<Surface, M>) -> Decorated<Self> {
2621 Decorated::new(self).surface(surface)
2622 }
2623
2624 fn border<Mc, Mw>(
2628 self,
2629 color: impl IntoReactive<Ink, Mc>,
2630 width: impl IntoReactive<f64, Mw>,
2631 ) -> Decorated<Self> {
2632 Decorated::new(self).border(color, width)
2633 }
2634
2635 fn shadow<M>(self, shadow: impl IntoReactive<day_spec::Shadow, M>) -> Decorated<Self> {
2639 Decorated::new(self).shadow(shadow)
2640 }
2641
2642 fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Decorated<Self> {
2646 Decorated::new(self).opacity(opacity)
2647 }
2648
2649 fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Decorated<Self> {
2653 Decorated::new(self).transform(t)
2654 }
2655
2656 fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Decorated<Self> {
2659 Decorated::new(self).scale(factor)
2660 }
2661
2662 fn rotation<M>(self, angle: impl IntoReactive<Angle, M>) -> Decorated<Self> {
2665 Decorated::new(self).rotation(angle)
2666 }
2667
2668 fn translation<Mx, My>(
2671 self,
2672 x: impl IntoReactive<f64, Mx>,
2673 y: impl IntoReactive<f64, My>,
2674 ) -> Decorated<Self> {
2675 Decorated::new(self).translation(x, y)
2676 }
2677
2678 fn animation(self, anim: AnimSpec) -> Decorated<Self> {
2682 Decorated::new(self).animation(anim)
2683 }
2684
2685 fn modifier(self, m: impl Modifier) -> AnyPiece {
2691 m.apply(self.any())
2692 }
2693
2694 fn overlay(self, over: impl Piece) -> Decorated<Self> {
2699 Decorated::new(self).overlay(over)
2700 }
2701
2702 fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Decorated<Self> {
2705 Decorated::new(self).overlay_aligned(align, over)
2706 }
2707
2708 fn aspect_ratio<M>(self, ratio: impl IntoReactive<f64, M>) -> Decorated<Self> {
2719 Decorated::new(self).aspect_ratio(ratio)
2720 }
2721
2722 fn aligned(self, alignment: Alignment) -> Decorated<Self> {
2730 Decorated::new(self).aligned(alignment)
2731 }
2732
2733 fn grow(self, grow: impl Into<Grow>) -> Decorated<Self> {
2747 Decorated::new(self).grow(grow)
2748 }
2749
2750 #[deprecated(note = "use .grow(Dimension::Width)")]
2751 fn grow_w(self) -> Decorated<Self> {
2752 Decorated::new(self).grow(Dimension::Width)
2753 }
2754
2755 #[deprecated(note = "use .grow(Dimension::Height)")]
2756 fn grow_h(self) -> Decorated<Self> {
2757 Decorated::new(self).grow(Dimension::Height)
2758 }
2759
2760 fn grid_span(self, n: usize) -> Decorated<Self> {
2763 Decorated::new(self).grid_span(n)
2764 }
2765
2766 fn grid_align(self, a: Alignment) -> Decorated<Self> {
2770 Decorated::new(self).grid_align(a)
2771 }
2772
2773 fn defers_system_gestures(self, edges: day_spec::Edges) -> Decorated<Self> {
2780 Decorated::new(self).defers_system_gestures(edges)
2781 }
2782
2783 fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Decorated<Self> {
2790 Decorated::new(self).status_bar_hidden(hidden)
2791 }
2792
2793 fn interactive_dismiss_disabled(self) -> Decorated<Self> {
2798 Decorated::new(self).interactive_dismiss_disabled()
2799 }
2800
2801 fn on_system_back<M>(
2823 self,
2824 enabled: impl IntoReactive<bool, M>,
2825 handler: impl Fn() + 'static,
2826 ) -> Decorated<Self> {
2827 Decorated::new(self).on_system_back(enabled, handler)
2828 }
2829
2830 fn any(self) -> AnyPiece {
2834 AnyPiece::new(self)
2835 }
2836}
2837
2838impl<P: Piece> Decorate for P {}
2839
2840type LiveA11yString = (TextSource, fn(String) -> A11yProps);
2842
2843#[derive(Default)]
2847#[must_use]
2848pub struct A11yBuilder {
2849 label: Option<TextSource>,
2850 hint: Option<TextSource>,
2851 value: Option<TextSource>,
2852 selected: Option<Reactive<bool>>,
2854 props: A11yProps,
2855}
2856
2857impl A11yBuilder {
2858 pub fn label<M>(mut self, s: impl IntoText<M>) -> Self {
2860 self.label = Some(s.into_text());
2861 self
2862 }
2863 pub fn hint<M>(mut self, s: impl IntoText<M>) -> Self {
2865 self.hint = Some(s.into_text());
2866 self
2867 }
2868 pub fn value<M>(mut self, s: impl IntoText<M>) -> Self {
2872 self.value = Some(s.into_text());
2873 self
2874 }
2875 pub fn role(mut self, r: Role) -> Self {
2876 self.props.role = r;
2877 self
2878 }
2879 pub fn selected<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
2883 self.selected = Some(on.into_reactive());
2884 self
2885 }
2886 pub fn hidden(mut self) -> Self {
2889 self.props.hidden = true;
2890 self
2891 }
2892 pub fn decorative(mut self) -> Self {
2895 self.props.decorative = true;
2896 self.props.hidden = true;
2897 self
2898 }
2899
2900 fn split(self) -> (A11yProps, Vec<LiveA11yString>, Option<Reactive<bool>>) {
2904 let mut props = self.props;
2905 let mut live = Vec::new();
2906 let selected = match self.selected {
2907 Some(Reactive::Const(on)) => {
2908 props.selected = Some(on);
2909 None
2910 }
2911 Some(dynamic @ Reactive::Dyn(_)) => {
2912 props.selected = Some(day_reactive::untrack(|| dynamic.get()));
2913 Some(dynamic)
2914 }
2915 None => None,
2916 };
2917 let mut take =
2918 |src: Option<TextSource>, slot: &mut Option<String>, patch: fn(String) -> A11yProps| {
2919 if let Some(src) = src {
2920 *slot = Some(src.initial());
2921 if matches!(src, TextSource::Dyn(_)) {
2922 live.push((src, patch));
2923 }
2924 }
2925 };
2926 take(self.label, &mut props.label, |label| A11yProps {
2927 label: Some(label),
2928 ..Default::default()
2929 });
2930 take(self.hint, &mut props.hint, |hint| A11yProps {
2931 hint: Some(hint),
2932 ..Default::default()
2933 });
2934 take(self.value, &mut props.value, |value| A11yProps {
2935 value: Some(value),
2936 ..Default::default()
2937 });
2938 (props, live, selected)
2939 }
2940}
2941
2942fn scoped_drag_source(source: day_spec::transfer::Source) -> day_spec::transfer::Source {
2945 let scope = Scope::current();
2946 let alive = Rc::new(Cell::new(true));
2947 let cleanup = alive.clone();
2948 scope.on_cleanup(move || cleanup.set(false));
2949 Rc::new(move |point| alive.get().then(|| scope.enter(|| source(point))).flatten())
2950}
2951fn scoped_drop_target(target: day_spec::transfer::Target) -> day_spec::transfer::Target {
2952 let scope = Scope::current();
2953 let alive = Rc::new(Cell::new(true));
2954 let cleanup = alive.clone();
2955 scope.on_cleanup(move || cleanup.set(false));
2956 target.guarded(Rc::new(move |run: &mut dyn FnMut()| {
2957 if alive.get() {
2958 scope.enter(run);
2959 }
2960 }))
2961}
2962
2963#[cfg(feature = "conformance")]
2969pub(crate) mod conformance {
2970 use day_core::AnyPiece;
2971 use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
2972 use day_reactive::{Signal, untrack};
2973 use day_spec::{Cap, Color, DragPhase, Point, Transform};
2974
2975 use crate::*;
2976
2977 fn size(width: f64, height: f64) -> FrameExpect {
2978 FrameExpect {
2979 width: Some(width),
2980 height: Some(height),
2981 ..Default::default()
2982 }
2983 }
2984
2985 #[day_macros::test(day_core)]
2986 fn reactive_frame_and_minimum_height() -> Case {
2987 let width = Signal::new(80.0);
2988 let height = Signal::new(44.0);
2989 Case::new()
2990 .proves_modifier("width")
2991 .proves_modifier("height")
2992 .proves_modifier("frame")
2993 .proves_modifier("min_height")
2994 .page(move || {
2995 column((
2996 rectangle()
2997 .fill(day_spec::Color::hex(0x0033_6699))
2998 .frame(width, height)
2999 .id(day_core::id!(resizing)),
3000 rectangle()
3001 .fill(day_spec::Color::hex(0x0066_3399))
3002 .width(width)
3003 .height(20.0)
3004 .min_height(44.0)
3005 .id(day_core::id!(minimum)),
3006 button("Resize fixture")
3007 .action(move || {
3008 width.set(120.0);
3009 height.set(64.0);
3010 })
3011 .id(day_core::id!(resize)),
3012 ))
3013 .spacing(0.0)
3014 })
3015 .drive(|d: Drive| async move {
3016 d.assert_frame("resizing", size(80.0, 44.0)).await?;
3017 d.assert_frame("minimum", size(80.0, 44.0)).await?;
3018 d.tap("resize").await?;
3019 d.assert_frame("resizing", size(120.0, 64.0)).await?;
3020 d.assert_frame("minimum", size(120.0, 44.0)).await
3021 })
3022 }
3023
3024 #[day_macros::test(day_core)]
3028 fn layout_direction_mirrors_a_subtree() -> Case {
3029 let direction = Signal::new(day_spec::LayoutDirection::Rtl);
3030 let pair = |first: day_core::ElementId, second: day_core::ElementId| {
3031 row((
3032 rectangle()
3033 .fill(Color::hex(0x0033_6699))
3034 .frame(40.0, 20.0)
3035 .id(first),
3036 rectangle()
3037 .fill(Color::hex(0x0099_3366))
3038 .frame(60.0, 20.0)
3039 .id(second),
3040 ))
3041 };
3042 Case::new()
3043 .proves_modifier("layout_direction")
3044 .proves_duty("set_layout_direction")
3045 .page(move || {
3046 column((
3047 column((
3048 pair(day_core::id!(dir_a), day_core::id!(dir_b))
3049 .width(200.0)
3050 .wrapper_id(day_core::id!(dir_outer)),
3051 pair(day_core::id!(dir_c), day_core::id!(dir_d))
3052 .width(200.0)
3053 .wrapper_id(day_core::id!(dir_inner))
3054 .layout_direction(day_spec::LayoutDirection::Ltr),
3055 label("Text in the subtree").id(day_core::id!(dir_text)),
3056 ))
3057 .align(HAlign::Leading)
3058 .layout_direction(direction),
3059 button("Flip")
3060 .action(move || direction.set(day_spec::LayoutDirection::Ltr))
3061 .id(day_core::id!(dir_flip)),
3062 ))
3063 .align(HAlign::Leading)
3064 .spacing(8.0)
3065 })
3066 .shot("rtl")
3067 .drive(|d: Drive| async move {
3068 let at = |x: f64, outer: &str| FrameExpect {
3069 x: Some(x),
3070 relative_to: Some(outer.into()),
3071 ..Default::default()
3072 };
3073 d.assert_frame("dir_a", at(160.0, "dir_outer")).await?;
3075 d.assert_frame("dir_b", at(100.0, "dir_outer")).await?;
3076 d.assert_frame("dir_c", at(0.0, "dir_inner")).await?;
3078 d.assert_frame("dir_d", at(40.0, "dir_inner")).await?;
3079 d.assert_text("dir_text", "Text in the subtree").await?;
3080 d.tap("dir_flip").await?;
3081 d.wait_idle().await?;
3082 d.assert_frame("dir_a", at(0.0, "dir_outer")).await?;
3083 d.assert_frame("dir_b", at(40.0, "dir_outer")).await
3084 })
3085 }
3086
3087 #[day_macros::test(day_core)]
3088 fn text_reservation() -> Case {
3089 let value = Signal::new("1".to_owned());
3090 let sample = Signal::new("8888".to_owned());
3091 Case::new()
3092 .proves_modifier("reserving")
3093 .page(move || {
3094 column((
3095 label(value)
3096 .reserving(sample)
3097 .font(day_spec::Font::Title2)
3098 .tabular()
3099 .id(day_core::id!(reserved_readout)),
3100 label("8888")
3101 .font(day_spec::Font::Title2)
3102 .tabular()
3103 .id(day_core::id!(reservation_reference)),
3104 label("88888888")
3105 .font(day_spec::Font::Title2)
3106 .tabular()
3107 .id(day_core::id!(reservation_expanded)),
3108 button("Update fixture value")
3109 .action(move || value.set("88".into()))
3110 .id(day_core::id!(reservation_update)),
3111 button("Expand fixture sample")
3112 .action(move || sample.set("88888888".into()))
3113 .id(day_core::id!(reservation_expand)),
3114 ))
3115 .align(HAlign::Leading)
3116 })
3117 .drive(|d: Drive| async move {
3118 let dimensions = |id: &str| {
3119 day_core::with_tree(|tree| {
3120 tree.node_frame(tree.find_by_id(id).unwrap()).unwrap().size
3121 })
3122 };
3123 let reference = dimensions("reservation_reference");
3124 d.assert_frame("reserved_readout", size(reference.width, reference.height))
3125 .await?;
3126 d.tap("reservation_update").await?;
3127 d.assert_text("reserved_readout", "88").await?;
3128 d.assert_frame("reserved_readout", size(reference.width, reference.height))
3129 .await?;
3130 d.tap("reservation_expand").await?;
3131 let expanded = dimensions("reservation_expanded");
3132 d.assert_frame("reserved_readout", size(expanded.width, expanded.height))
3133 .await?;
3134 d.assert_text("reserved_readout", "88").await
3135 })
3136 }
3137
3138 #[day_macros::test(day_core)]
3140 fn padding_insets() -> Case {
3141 Case::new()
3142 .proves_modifier("padding")
3143 .proves_modifier("wrapper_id")
3144 .page(|| {
3145 rectangle()
3148 .fill(Color::rgb(1.0, 0.0, 0.0))
3149 .id(day_core::id!(inner))
3150 .frame(40.0, 20.0)
3151 .padding(10.0)
3152 .wrapper_id(day_core::id!(outer))
3153 })
3154 .drive(|d: Drive| async move {
3155 d.assert_frame("outer", size(60.0, 40.0)).await?;
3156 d.assert_frame(
3157 "inner",
3158 FrameExpect {
3159 x: Some(10.0),
3160 y: Some(10.0),
3161 relative_to: Some("outer".into()),
3162 ..Default::default()
3163 },
3164 )
3165 .await
3166 })
3167 }
3168
3169 #[day_macros::test(day_core)]
3171 fn min_max_width() -> Case {
3172 Case::new()
3173 .proves_modifier("min_width")
3174 .proves_modifier("max_width")
3175 .page(|| {
3176 column((
3177 label("Hi").min_width(120.0).wrapper_id(day_core::id!(min)),
3179 label("A label long enough that it would run past eighty points")
3180 .max_width(80.0)
3181 .wrapper_id(day_core::id!(max)),
3182 ))
3183 .align(HAlign::Leading)
3184 })
3185 .drive(|d: Drive| async move {
3186 d.assert_frame(
3187 "min",
3188 FrameExpect {
3189 width: Some(120.0),
3190 ..Default::default()
3191 },
3192 )
3193 .await?;
3194 d.assert_frame(
3195 "max",
3196 FrameExpect {
3197 width: Some(80.0),
3198 ..Default::default()
3199 },
3200 )
3201 .await
3202 })
3203 }
3204
3205 #[day_macros::test(day_core)]
3207 fn max_height_caps_a_scroll() -> Case {
3208 Case::new()
3209 .proves_modifier("max_height")
3210 .page(|| {
3211 column((
3212 scroll(column((
3213 label("One"),
3214 label("Two"),
3215 label("Three"),
3216 label("Four"),
3217 label("Five"),
3218 label("Six"),
3219 )))
3220 .max_height(60.0)
3221 .wrapper_id(day_core::id!(capped)),
3222 spacer(),
3223 ))
3224 .align(HAlign::Leading)
3225 })
3226 .drive(|d: Drive| async move {
3227 d.assert_frame(
3228 "capped",
3229 FrameExpect {
3230 height: Some(60.0),
3231 ..Default::default()
3232 },
3233 )
3234 .await
3235 })
3236 }
3237
3238 #[day_macros::test(day_core)]
3240 fn aspect_ratio_height() -> Case {
3241 Case::new()
3242 .proves_modifier("aspect_ratio")
3243 .page(|| {
3244 rectangle()
3245 .fill(Color::rgb(0.0, 0.0, 1.0))
3246 .aspect_ratio(2.0)
3247 .id(day_core::id!(shape))
3248 .width(100.0)
3249 })
3250 .drive(|d: Drive| async move { d.assert_frame("shape", size(100.0, 50.0)).await })
3251 }
3252
3253 #[day_macros::test(day_core)]
3255 fn grow_width() -> Case {
3256 Case::new()
3257 .proves_modifier("grow")
3258 .page(|| {
3259 row((
3260 rectangle()
3261 .fill(Color::rgb(1.0, 0.0, 0.0))
3262 .frame(40.0, 20.0),
3263 rectangle()
3264 .fill(Color::rgb(0.0, 0.0, 1.0))
3265 .height(20.0)
3266 .grow(Dimension::Width)
3267 .id(day_core::id!(grower)),
3268 ))
3269 .spacing(0.0)
3270 .width(200.0)
3271 })
3272 .drive(|d: Drive| async move {
3273 d.assert_frame(
3274 "grower",
3275 FrameExpect {
3276 width: Some(160.0),
3277 ..Default::default()
3278 },
3279 )
3280 .await
3281 })
3282 }
3283
3284 #[day_macros::test(day_core)]
3286 fn aligned_intrinsic_frame() -> Case {
3287 Case::new()
3288 .proves_modifier("aligned")
3289 .page(|| {
3290 zstack((rectangle()
3293 .fill(Color::rgb(0.2, 0.5, 0.8))
3294 .frame(40.0, 20.0)
3295 .id(day_core::id!(aligned_child))
3296 .aligned(day_core::Alignment::BottomTrailing)
3297 .frame(200.0, 100.0),))
3298 .id(day_core::id!(aligned_container))
3299 .frame(200.0, 100.0)
3300 })
3301 .drive(|d: Drive| async move {
3302 d.assert_frame("aligned_container", size(200.0, 100.0))
3303 .await?;
3304 d.assert_frame(
3305 "aligned_child",
3306 FrameExpect {
3307 x: Some(160.0),
3308 y: Some(80.0),
3309 width: Some(40.0),
3310 height: Some(20.0),
3311 relative_to: Some("aligned_container".into()),
3312 ..Default::default()
3313 },
3314 )
3315 .await
3316 })
3317 }
3318
3319 #[day_macros::test(day_core)]
3321 fn overlay_aligned_corner() -> Case {
3322 Case::new()
3323 .proves_modifier("overlay_aligned")
3324 .requires(Cap::Snapshot)
3325 .page(|| {
3326 rectangle()
3327 .fill(Color::rgb(1.0, 0.0, 0.0))
3328 .frame(100.0, 60.0)
3329 .overlay_aligned(
3330 day_core::Alignment::BottomTrailing,
3331 rectangle()
3332 .fill(Color::rgb(0.0, 0.0, 1.0))
3333 .frame(20.0, 20.0),
3334 )
3335 .id(day_core::id!(base))
3336 })
3337 .drive(|d: Drive| async move {
3338 d.sample_pixel("base", 0.95, 0.9, "#0000ff").await?;
3339 d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
3340 })
3341 }
3342
3343 #[day_macros::test(day_core)]
3345 fn background_fill() -> Case {
3346 Case::new()
3347 .proves_modifier("background")
3348 .requires(Cap::Snapshot)
3349 .page(|| {
3350 label("")
3351 .frame(80.0, 40.0)
3352 .background(Color::rgb(1.0, 0.0, 0.0))
3353 .id(day_core::id!(filled))
3354 })
3355 .drive(|d: Drive| async move { d.sample_pixel("filled", 0.5, 0.5, "#ff0000").await })
3356 }
3357
3358 #[day_macros::test(day_core)]
3360 fn corner_radius_cuts() -> Case {
3361 Case::new()
3362 .proves_modifier("corner_radius")
3363 .requires(Cap::Snapshot)
3364 .page(|| {
3365 zstack((
3366 rectangle().fill(Color::WHITE),
3367 label("")
3368 .frame(80.0, 80.0)
3369 .background(Color::rgb(0.0, 0.0, 1.0))
3370 .corner_radius(30.0),
3371 ))
3372 .id(day_core::id!(ground))
3373 .frame(80.0, 80.0)
3374 })
3375 .drive(|d: Drive| async move {
3376 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3377 d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await
3378 })
3379 }
3380
3381 #[day_macros::test(day_core)]
3383 fn surface_border_frames_fill() -> Case {
3384 Case::new()
3385 .proves_modifier("surface")
3386 .proves_modifier("border")
3387 .requires(Cap::Snapshot)
3388 .page(|| {
3389 label("")
3390 .frame(80.0, 80.0)
3391 .surface(
3392 Surface::new()
3393 .fill(Color::rgb(0.0, 0.0, 1.0))
3394 .border(Color::rgb(1.0, 0.0, 0.0), 8.0),
3395 )
3396 .id(day_core::id!(framed))
3397 })
3398 .drive(|d: Drive| async move {
3399 d.sample_pixel("framed", 0.5, 0.5, "#0000ff").await?;
3400 d.sample_pixel("framed", 0.5, 0.05, "#ff0000").await?;
3401 d.sample_pixel("framed", 0.05, 0.5, "#ff0000").await?;
3402 d.sample_pixel("framed", 0.95, 0.5, "#ff0000").await?;
3403 d.sample_pixel("framed", 0.5, 0.95, "#ff0000").await
3404 })
3405 }
3406
3407 #[day_macros::test(day_core)]
3410 fn surface_rounds_named_corners() -> Case {
3411 Case::new()
3412 .proves_modifier("surface")
3413 .requires(Cap::Snapshot)
3414 .page(|| {
3415 zstack((
3416 rectangle().fill(Color::WHITE),
3417 label("").frame(80.0, 80.0).surface(
3418 Surface::new()
3419 .fill(Color::rgb(0.0, 0.0, 1.0))
3420 .corner_radius(30.0)
3421 .corners(day_spec::Corners::TOP),
3422 ),
3423 ))
3424 .id(day_core::id!(ground))
3425 .frame(80.0, 80.0)
3426 })
3427 .drive(|d: Drive| async move {
3428 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3429 d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await?;
3430 d.sample_pixel("ground", 0.97, 0.03, "#ffffff").await?;
3431 d.sample_pixel("ground", 0.03, 0.97, "#0000ff").await?;
3432 d.sample_pixel("ground", 0.97, 0.97, "#0000ff").await
3433 })
3434 }
3435
3436 #[day_macros::test(day_core)]
3438 fn surface_gradient_fill() -> Case {
3439 Case::new()
3440 .proves_modifier("surface")
3441 .requires(Cap::Snapshot)
3442 .page(|| {
3443 label("")
3444 .frame(80.0, 80.0)
3445 .surface(Surface::new().fill(day_spec::LinearGradient::vertical(
3446 Color::rgb(1.0, 0.0, 0.0),
3447 Color::rgb(0.0, 0.0, 1.0),
3448 )))
3449 .id(day_core::id!(graded))
3450 })
3451 .drive(|d: Drive| async move {
3452 d.sample_pixel("graded", 0.5, 0.06, "#ff0000").await?;
3453 d.sample_pixel("graded", 0.5, 0.5, "#800080").await?;
3454 d.sample_pixel("graded", 0.5, 0.94, "#0000ff").await
3455 })
3456 }
3457
3458 #[day_macros::test(day_core)]
3461 fn surface_shadow_falls_outside() -> Case {
3462 Case::new()
3463 .proves_modifier("surface")
3464 .proves_modifier("shadow")
3465 .requires(Cap::Snapshot)
3466 .page(|| {
3467 zstack((
3470 rectangle().fill(Color::WHITE),
3471 label("").frame(60.0, 60.0).surface(
3472 Surface::new().fill(Color::rgb(0.0, 0.0, 1.0)).shadow(
3473 day_spec::Shadow::new(Color::rgb(0.0, 0.0, 0.0), 4.0).offset(0.0, 16.0),
3474 ),
3475 ),
3476 ))
3477 .id(day_core::id!(ground))
3478 .frame(120.0, 120.0)
3479 })
3480 .drive(|d: Drive| async move {
3481 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3482 d.sample_pixel("ground", 0.5, 0.815, "#000000").await?;
3483 d.sample_pixel("ground", 0.5, 0.97, "#ffffff").await?;
3484 d.sample_pixel("ground", 0.5, 0.1, "#ffffff").await
3485 })
3486 }
3487
3488 fn appearance_switches() -> impl day_core::Piece {
3490 row((
3491 button("Light")
3492 .action(|| day_core::set_appearance(Some(false)))
3493 .id(day_core::id!(appearance::light)),
3494 button("Dark")
3495 .action(|| day_core::set_appearance(Some(true)))
3496 .id(day_core::id!(appearance::dark)),
3497 button("System")
3498 .action(|| day_core::set_appearance(None))
3499 .id(day_core::id!(appearance::system)),
3500 ))
3501 .spacing(8.0)
3502 }
3503
3504 #[day_macros::test(day_core)]
3508 fn ink_follows_the_appearance() -> Case {
3509 const PAIR: day_spec::Ink =
3510 day_spec::Ink::adaptive(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
3511 Case::new()
3512 .proves_modifier("background")
3513 .proves_cap(Cap::Appearance)
3514 .requires(Cap::Appearance)
3515 .page(|| {
3516 column((
3517 label("")
3518 .frame(80.0, 40.0)
3519 .background(PAIR)
3520 .id(day_core::id!(paired)),
3521 label("")
3522 .frame(80.0, 40.0)
3523 .background(day_spec::SystemColor::Background)
3524 .border(day_spec::SystemColor::Separator, 2.0)
3525 .id(day_core::id!(role)),
3526 appearance_switches(),
3527 ))
3528 .spacing(8.0)
3529 })
3530 .drive(|d: Drive| async move {
3531 let shown = |c: Color| day_core::conformance::DisplayedExpect {
3532 background: Some(c),
3533 ..Default::default()
3534 };
3535 d.tap("appearance::light").await?;
3536 d.sample_pixel("paired", 0.5, 0.5, "#ff0000").await?;
3537 d.assert_displayed("paired", shown(Color::rgb(1.0, 0.0, 0.0)))
3538 .await?;
3539 let light = day_core::resolve(day_spec::SystemColor::Background);
3540 d.assert_displayed("role", shown(light)).await?;
3541 d.tap("appearance::dark").await?;
3542 d.sample_pixel("paired", 0.5, 0.5, "#0000ff").await?;
3543 d.assert_displayed("paired", shown(Color::rgb(0.0, 0.0, 1.0)))
3544 .await?;
3545 let dark = day_core::resolve(day_spec::SystemColor::Background);
3546 d.assert_displayed("role", shown(dark)).await?;
3547 d.tap("appearance::system").await
3548 })
3549 }
3550
3551 #[day_macros::test(day_core)]
3554 fn canvas_ink_follows_the_appearance() -> Case {
3555 Case::new()
3556 .proves(day_spec::kinds::CANVAS)
3557 .requires(Cap::Appearance)
3558 .requires(Cap::Snapshot)
3559 .page(|| {
3560 column((
3561 canvas(|d, size| {
3562 d.fill(
3563 day_spec::Shape::Rect(day_spec::Rect::from_size(size)),
3564 day_spec::Ink::adaptive(
3565 Color::rgb(1.0, 0.0, 0.0),
3566 Color::rgb(0.0, 0.0, 1.0),
3567 ),
3568 );
3569 })
3570 .frame(80.0, 40.0)
3571 .id(day_core::id!(drawn)),
3572 appearance_switches(),
3573 ))
3574 .spacing(8.0)
3575 })
3576 .drive(|d: Drive| async move {
3577 d.tap("appearance::light").await?;
3578 d.sample_pixel("drawn", 0.5, 0.5, "#ff0000").await?;
3579 d.tap("appearance::dark").await?;
3580 d.sample_pixel("drawn", 0.5, 0.5, "#0000ff").await?;
3581 d.tap("appearance::system").await
3582 })
3583 }
3584
3585 #[day_macros::test(day_core)]
3588 fn surface_border_over_content() -> Case {
3589 Case::new()
3590 .proves_modifier("surface")
3591 .proves_modifier("border")
3592 .requires(Cap::Snapshot)
3593 .page(|| {
3594 rectangle()
3595 .fill(Color::rgb(0.0, 0.0, 1.0))
3596 .frame(80.0, 80.0)
3597 .surface(
3598 Surface::new()
3599 .corner_radius(12.0)
3600 .border(Color::rgb(1.0, 0.0, 0.0), 8.0),
3601 )
3602 .id(day_core::id!(framed))
3603 })
3604 .drive(|d: Drive| async move {
3605 d.sample_pixel("framed", 0.5, 0.5, "#0000ff").await?;
3606 d.sample_pixel("framed", 0.5, 0.04, "#ff0000").await?;
3607 d.sample_pixel("framed", 0.04, 0.5, "#ff0000").await?;
3608 d.sample_pixel("framed", 0.5, 0.96, "#ff0000").await
3609 })
3610 }
3611
3612 #[day_macros::test(day_core)]
3616 fn surface_radial_and_conic_fill() -> Case {
3617 Case::new()
3618 .proves_modifier("surface")
3619 .requires(Cap::Snapshot)
3620 .page(|| {
3621 let quarter = |at: f64, c: Color| [(at, c), (at + 0.25, c)];
3622 let conic = [
3623 quarter(0.0, Color::rgb(1.0, 0.0, 0.0)),
3624 quarter(0.25, Color::rgb(0.0, 1.0, 0.0)),
3625 quarter(0.5, Color::rgb(0.0, 0.0, 1.0)),
3626 quarter(0.75, Color::rgb(1.0, 1.0, 0.0)),
3627 ]
3628 .concat();
3629 row((
3630 label("")
3631 .frame(80.0, 80.0)
3632 .surface(Surface::new().fill(day_spec::RadialGradient::new(
3633 day_spec::UnitPoint::CENTER,
3634 0.5,
3635 [
3636 (0.0, Color::rgb(1.0, 0.0, 0.0)),
3637 (0.2, Color::rgb(1.0, 0.0, 0.0)),
3638 (0.8, Color::rgb(0.0, 0.0, 1.0)),
3639 (1.0, Color::rgb(0.0, 0.0, 1.0)),
3640 ],
3641 )))
3642 .id(day_core::id!(radial)),
3643 label("")
3644 .frame(80.0, 80.0)
3645 .background(day_spec::ConicGradient::centered(
3646 day_spec::Angle::ZERO,
3647 conic,
3648 ))
3649 .id(day_core::id!(conic)),
3650 ))
3651 .spacing(8.0)
3652 })
3653 .drive(|d: Drive| async move {
3654 d.sample_pixel("radial", 0.5, 0.5, "#ff0000").await?;
3655 d.sample_pixel("radial", 0.5, 0.97, "#0000ff").await?;
3656 d.sample_pixel("conic", 0.8, 0.6, "#ff0000").await?;
3659 d.sample_pixel("conic", 0.2, 0.6, "#00ff00").await?;
3660 d.sample_pixel("conic", 0.2, 0.4, "#0000ff").await?;
3661 d.sample_pixel("conic", 0.8, 0.4, "#ffff00").await
3662 })
3663 }
3664
3665 #[day_macros::test(day_core)]
3668 fn surface_follows_its_signals() -> Case {
3669 Case::new()
3670 .proves_modifier("corner_radius")
3671 .proves_modifier("border")
3672 .requires(Cap::Snapshot)
3673 .page(|| {
3674 let styled = Signal::new(false);
3675 let width = Signal::new(80.0);
3676 column((
3677 zstack((
3678 rectangle().fill(Color::WHITE),
3679 label("")
3680 .frame(80.0, 80.0)
3681 .background(Color::rgb(0.0, 0.0, 1.0))
3682 .border(Color::rgb(1.0, 0.0, 0.0), move || {
3683 if styled.get() { 8.0 } else { 0.0 }
3684 })
3685 .corner_radius(move || if styled.get() { 30.0 } else { 0.0 }),
3686 ))
3687 .frame(80.0, 80.0)
3688 .id(day_core::id!(styled)),
3689 zstack((
3690 rectangle().fill(Color::WHITE),
3691 label("")
3692 .frame(width, 40.0)
3693 .background(Color::rgb(0.0, 0.0, 1.0))
3694 .corner_radius(crate::Corner::CAPSULE),
3695 ))
3696 .frame(160.0, 40.0)
3697 .id(day_core::id!(pill)),
3698 button("Style")
3699 .action(move || {
3700 styled.set(true);
3701 width.set(160.0);
3702 })
3703 .id(day_core::id!(restyle)),
3704 ))
3705 .spacing(8.0)
3706 })
3707 .drive(|d: Drive| async move {
3708 d.sample_pixel("styled", 0.03, 0.03, "#0000ff").await?;
3709 d.sample_pixel("styled", 0.5, 0.04, "#0000ff").await?;
3710 d.sample_pixel("pill", 0.02, 0.06, "#ffffff").await?;
3711 d.tap("restyle").await?;
3712 d.sample_pixel("styled", 0.03, 0.03, "#ffffff").await?;
3713 d.sample_pixel("styled", 0.5, 0.04, "#ff0000").await?;
3714 d.sample_pixel("styled", 0.5, 0.5, "#0000ff").await?;
3715 d.sample_pixel("pill", 0.01, 0.06, "#ffffff").await?;
3717 d.sample_pixel("pill", 0.99, 0.94, "#ffffff").await?;
3718 d.sample_pixel("pill", 0.5, 0.5, "#0000ff").await
3719 })
3720 }
3721
3722 #[day_macros::test(day_core)]
3725 fn size_limits_follow_their_signals() -> Case {
3726 Case::new()
3727 .proves_modifier("max_width")
3728 .proves_modifier("min_height")
3729 .proves_modifier("aspect_ratio")
3730 .page(|| {
3731 let wide = Signal::new(false);
3732 column((
3733 rectangle()
3734 .fill(Color::rgb(0.2, 0.4, 0.9))
3735 .max_width(move || if wide.get() { 120.0 } else { 60.0 })
3736 .min_height(move || if wide.get() { 30.0 } else { 20.0 })
3737 .frame(200.0, 10.0)
3738 .id(day_core::id!(capped)),
3739 rectangle()
3740 .fill(Color::rgb(0.9, 0.4, 0.2))
3741 .aspect_ratio(move || if wide.get() { 4.0 } else { 2.0 })
3742 .width(80.0)
3743 .id(day_core::id!(ratio)),
3744 button("Widen")
3745 .action(move || wide.set(true))
3746 .id(day_core::id!(widen)),
3747 ))
3748 .spacing(8.0)
3749 })
3750 .drive(|d: Drive| async move {
3751 d.assert_size("capped", 60.0, 20.0).await?;
3752 d.assert_size("ratio", 80.0, 40.0).await?;
3753 d.tap("widen").await?;
3754 d.assert_size("capped", 120.0, 30.0).await?;
3755 d.assert_size("ratio", 80.0, 20.0).await
3756 })
3757 }
3758
3759 #[day_macros::test(day_core)]
3762 fn rotation_takes_an_angle_in_either_unit() -> Case {
3763 Case::new()
3764 .proves_modifier("rotation")
3765 .requires(Cap::Snapshot)
3766 .page(|| {
3767 zstack((
3768 rectangle().fill(Color::WHITE),
3769 shape_group([
3770 rectangle()
3771 .fill(Color::rgb(1.0, 0.0, 0.0))
3772 .at(0.0, 0.0, 0.5, 1.0),
3773 rectangle()
3774 .fill(Color::rgb(0.0, 0.0, 1.0))
3775 .at(0.5, 0.0, 0.5, 1.0),
3776 ])
3777 .frame(80.0, 40.0)
3778 .rotation(day_spec::Angle::rad(std::f64::consts::FRAC_PI_2)),
3779 ))
3780 .id(day_core::id!(ground))
3781 .frame(120.0, 120.0)
3782 })
3783 .drive(|d: Drive| async move {
3784 d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
3785 d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
3786 })
3787 }
3788
3789 #[day_macros::test(day_core)]
3791 fn opacity_hides() -> Case {
3792 Case::new()
3793 .proves_duty("set_opacity")
3794 .proves_modifier("opacity")
3795 .requires(Cap::Snapshot)
3796 .page(|| {
3797 zstack((
3798 rectangle().fill(Color::WHITE),
3799 rectangle().fill(Color::rgb(1.0, 0.0, 0.0)).opacity(0.0),
3800 ))
3801 .id(day_core::id!(ground))
3802 .frame(80.0, 40.0)
3803 })
3804 .drive(|d: Drive| async move { d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await })
3805 }
3806
3807 #[day_macros::test(day_core)]
3809 fn translation_moves_drawing() -> Case {
3810 Case::new()
3811 .proves_modifier("translation")
3812 .requires(Cap::Snapshot)
3813 .page(|| {
3814 zstack((
3815 rectangle().fill(Color::WHITE),
3816 rectangle()
3817 .fill(Color::rgb(0.0, 0.0, 1.0))
3818 .frame(40.0, 40.0)
3819 .translation(40.0, 0.0),
3820 ))
3821 .align(day_core::Alignment::Leading)
3822 .id(day_core::id!(ground))
3823 .frame(120.0, 40.0)
3824 })
3825 .drive(|d: Drive| async move {
3826 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3827 d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
3828 })
3829 }
3830
3831 #[day_macros::test(day_core)]
3833 fn translation_moves_view() -> Case {
3834 Case::new()
3835 .proves_modifier("translation")
3836 .requires(Cap::Snapshot)
3837 .page(|| {
3838 zstack((
3839 rectangle().fill(Color::WHITE),
3840 label("")
3841 .frame(40.0, 40.0)
3842 .background(Color::rgb(0.0, 0.0, 1.0))
3843 .translation(40.0, 0.0),
3844 ))
3845 .align(day_core::Alignment::Leading)
3846 .id(day_core::id!(ground))
3847 .frame(120.0, 40.0)
3848 })
3849 .drive(|d: Drive| async move {
3850 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3851 d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
3852 })
3853 }
3854
3855 #[day_macros::test(day_core)]
3857 fn scale_grows_drawing() -> Case {
3858 Case::new()
3859 .proves_modifier("scale")
3860 .requires(Cap::Snapshot)
3861 .page(|| {
3862 zstack((
3863 rectangle().fill(Color::WHITE),
3864 label("")
3865 .frame(40.0, 40.0)
3866 .background(Color::rgb(0.0, 0.0, 1.0))
3867 .scale(2.0),
3868 ))
3869 .id(day_core::id!(ground))
3870 .frame(120.0, 80.0)
3871 })
3872 .drive(|d: Drive| async move {
3873 d.sample_pixel("ground", 0.25, 0.5, "#0000ff").await?;
3875 d.sample_pixel("ground", 0.08, 0.5, "#ffffff").await
3876 })
3877 }
3878
3879 #[day_macros::test(day_core)]
3882 fn rotation_turns_clockwise() -> Case {
3883 Case::new()
3884 .proves_modifier("rotation")
3885 .requires(Cap::Snapshot)
3886 .page(|| {
3887 zstack((
3888 rectangle().fill(Color::WHITE),
3889 shape_group([
3890 rectangle()
3891 .fill(Color::rgb(1.0, 0.0, 0.0))
3892 .at(0.0, 0.0, 0.5, 1.0),
3893 rectangle()
3894 .fill(Color::rgb(0.0, 0.0, 1.0))
3895 .at(0.5, 0.0, 0.5, 1.0),
3896 ])
3897 .frame(80.0, 40.0)
3898 .rotation(day_spec::Angle::QUARTER),
3899 ))
3900 .id(day_core::id!(ground))
3901 .frame(120.0, 120.0)
3902 })
3903 .shot("default")
3904 .drive(|d: Drive| async move {
3905 d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
3906 d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
3907 })
3908 }
3909
3910 fn pad(id: day_core::ElementId) -> Decorated<ShapePiece> {
3916 rectangle()
3917 .fill(Color::rgb(0.2, 0.4, 0.9))
3918 .frame(120.0, 80.0)
3919 .id(id)
3920 }
3921
3922 #[day_macros::test(day_core)]
3924 fn on_tap_runs() -> Case {
3925 Case::new()
3926 .proves_modifier("on_tap")
3927 .page(|| {
3928 let taps = Signal::new(0i64);
3929 column((
3930 label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
3931 label("Tap me")
3932 .padding(12.0)
3933 .on_tap(move || taps.update(|n| *n += 1))
3934 .id(day_core::id!(target)),
3935 ))
3936 })
3937 .drive(|d: Drive| async move {
3938 d.tap("target").await?;
3939 d.tap("target").await?;
3940 d.assert_text("taps", "taps 2").await
3941 })
3942 }
3943
3944 #[day_macros::test(day_core)]
3946 fn on_tap_at_reports_point() -> Case {
3947 Case::new()
3948 .proves_modifier("on_tap_at")
3949 .page(|| {
3950 let at = Signal::new(String::from("none"));
3951 column((
3952 label(move || format!("at {}", at.get())).id(day_core::id!(at)),
3953 rectangle()
3954 .fill(Color::rgb(0.2, 0.4, 0.9))
3955 .frame(120.0, 80.0)
3956 .on_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y)))
3957 .id(day_core::id!(target)),
3958 ))
3959 })
3960 .drive(|d: Drive| async move {
3961 d.tap_at("target", 30.0, 20.0).await?;
3962 d.assert_text("at", "at 30,20").await
3963 })
3964 }
3965
3966 #[day_macros::test(day_core)]
3968 fn on_drag_reports_translation() -> Case {
3969 Case::new()
3970 .proves_duty("enable_gesture")
3971 .proves_modifier("on_drag")
3972 .page(|| {
3973 let state = Signal::new(String::from("idle"));
3974 column((
3975 label(move || state.get()).id(day_core::id!(state)),
3976 pad(day_core::id!(target)).on_drag(move |d: Drag| {
3977 state.set(match d.phase {
3978 DragPhase::Began => "began".into(),
3979 DragPhase::Changed => "moving".into(),
3980 DragPhase::Ended => {
3981 format!("moved {:.0},{:.0}", d.translation.x, d.translation.y)
3982 }
3983 });
3984 }),
3985 ))
3986 })
3987 .drive(|d: Drive| async move {
3988 d.drag("target", (10.0, 10.0), (50.0, 30.0)).await?;
3989 d.assert_text("state", "moved 40,20").await
3990 })
3991 }
3992
3993 #[day_macros::test(day_core)]
3995 fn on_hover_enters_and_leaves() -> Case {
3996 Case::new()
3997 .proves_modifier("on_hover")
3998 .page(|| {
3999 let state = Signal::new(String::from("out"));
4000 column((
4001 label(move || state.get()).id(day_core::id!(state)),
4002 pad(day_core::id!(target)).on_hover(move |p| {
4003 state.set(match p {
4004 Some(p) => format!("over {:.0},{:.0}", p.x, p.y),
4005 None => "out".into(),
4006 });
4007 }),
4008 ))
4009 })
4010 .drive(|d: Drive| async move {
4011 d.hover("target", Some((5.0, 6.0))).await?;
4012 d.assert_text("state", "over 5,6").await?;
4013 d.hover_leave("target").await?;
4014 d.assert_text("state", "out").await
4015 })
4016 }
4017
4018 #[day_macros::test(day_core)]
4020 fn on_pan_adds_deltas() -> Case {
4021 Case::new()
4022 .proves_modifier("on_pan")
4023 .page(|| {
4024 let total = Signal::new((0.0f64, 0.0f64));
4025 column((
4026 label(move || {
4027 let (x, y) = total.get();
4028 format!("pan {x:.0},{y:.0}")
4029 })
4030 .id(day_core::id!(total)),
4031 pad(day_core::id!(target)).on_pan(move |p: Pan| {
4032 total.update(|(x, y)| {
4033 *x += p.delta.x;
4034 *y += p.delta.y;
4035 });
4036 }),
4037 ))
4038 })
4039 .drive(|d: Drive| async move {
4040 d.pan("target", 40.0, -20.0).await?;
4041 d.assert_text("total", "pan 40,-20").await
4042 })
4043 }
4044
4045 #[day_macros::test(day_core)]
4047 fn on_pinch_reports_scale() -> Case {
4048 Case::new()
4049 .proves_modifier("on_pinch")
4050 .page(|| {
4051 let scale = Signal::new(String::from("none"));
4052 column((
4053 label(move || format!("scale {}", scale.get())).id(day_core::id!(scale)),
4054 pad(day_core::id!(target)).on_pinch(move |p: Pinch| {
4055 if p.phase == DragPhase::Ended {
4056 scale.set(format!("{:.1}", p.scale));
4057 }
4058 }),
4059 ))
4060 })
4061 .drive(|d: Drive| async move {
4062 d.pinch("target", 2.5).await?;
4063 d.assert_text("scale", "scale 2.5").await
4064 })
4065 }
4066
4067 #[day_macros::test(day_core)]
4070 fn on_rotate_reports_rotation() -> Case {
4071 Case::new()
4072 .proves_modifier("on_rotate")
4073 .page(|| {
4074 let angle = Signal::new(String::from("none"));
4075 column((
4076 label(move || format!("rotation {}", angle.get())).id(day_core::id!(angle)),
4077 pad(day_core::id!(target)).on_rotate(move |r: Rotate| {
4078 if r.phase == DragPhase::Ended {
4079 angle.set(format!("{:.2}", r.rotation.radians()));
4080 }
4081 }),
4082 ))
4083 })
4084 .drive(|d: Drive| async move {
4085 d.rotate("target", 0.75).await?;
4086 d.assert_text("angle", "rotation 0.75").await
4087 })
4088 }
4089
4090 #[day_macros::test(day_core)]
4092 fn on_key_reaches_focused() -> Case {
4093 Case::new()
4094 .proves_duty("focus")
4095 .proves_duty("set_focusable")
4096 .proves_modifier("on_key")
4097 .proves_modifier("focusable")
4098 .page(|| {
4099 let last = Signal::new(String::from("none"));
4100 column((
4101 label(move || format!("key {}", last.get())).id(day_core::id!(last)),
4102 pad(day_core::id!(target))
4103 .focusable()
4104 .on_key(move |k| last.set(k.key.name())),
4105 ))
4106 })
4107 .drive(|d: Drive| async move {
4108 d.focus("target").await?;
4110 d.assert_focused("target", true).await?;
4111 d.key(None, "ArrowRight").await?;
4112 d.assert_text("last", "key ArrowRight").await
4113 })
4114 }
4115
4116 #[day_macros::test(day_core)]
4119 fn on_drag_reports_release_velocity() -> Case {
4120 Case::new()
4121 .proves_modifier("on_drag")
4122 .page(|| {
4123 let state = Signal::new(String::from("idle"));
4124 column((
4125 label(move || state.get()).id(day_core::id!(state)),
4126 pad(day_core::id!(target)).on_drag(move |d: Drag| {
4127 if d.phase == DragPhase::Ended {
4128 state.set(format!(
4129 "from {:.0},{:.0} at {:.0},{:.0} speed {:.0}",
4130 d.start().x,
4131 d.start().y,
4132 d.velocity.x,
4133 d.velocity.y,
4134 d.speed()
4135 ));
4136 }
4137 }),
4138 ))
4139 })
4140 .drive(|d: Drive| async move {
4141 d.fling("target", (10.0, 20.0), (70.0, 20.0), (600.0, -800.0))
4142 .await?;
4143 d.assert_text("state", "from 10,20 at 600,-800 speed 1000")
4144 .await?;
4145 d.drag("target", (10.0, 20.0), (70.0, 20.0)).await?;
4147 d.assert_text("state", "from 10,20 at 0,0 speed 0").await
4148 })
4149 }
4150
4151 #[day_macros::test(day_core)]
4154 fn on_drag_along_withholds_cross_axis() -> Case {
4155 Case::new()
4156 .proves_modifier("on_drag_along")
4157 .proves_duty("set_drag_axis")
4158 .page(|| {
4159 let state = Signal::new(String::from("none"));
4160 let events = Signal::new(0i64);
4161 column((
4162 label(move || format!("{} after {}", state.get(), events.get()))
4163 .id(day_core::id!(state)),
4164 pad(day_core::id!(target)).on_drag_along(
4165 day_spec::DragAxis::Horizontal,
4166 move |d: Drag| {
4167 events.update(|n| *n += 1);
4168 if d.phase == DragPhase::Ended {
4169 state.set(format!("moved {:.0}", d.translation.x));
4170 }
4171 },
4172 ),
4173 ))
4174 })
4175 .drive(|d: Drive| async move {
4176 d.drag("target", (60.0, 10.0), (60.0, 70.0)).await?;
4177 d.assert_text("state", "none after 0").await?;
4178 d.drag("target", (10.0, 40.0), (90.0, 44.0)).await?;
4179 d.assert_text("state", "moved 80 after 6").await
4181 })
4182 }
4183
4184 #[day_macros::test(day_core)]
4187 fn on_long_press_fires() -> Case {
4188 Case::new()
4189 .proves_modifier("on_long_press")
4190 .proves_duty("gesture_support")
4191 .page(|| {
4192 let held = Signal::new(String::from("none"));
4193 let taps = Signal::new(0i64);
4194 column((
4195 label(move || format!("held {} taps {}", held.get(), taps.get()))
4196 .id(day_core::id!(state)),
4197 pad(day_core::id!(target))
4198 .on_tap(move || taps.update(|n| *n += 1))
4199 .on_long_press(move |at| held.set(format!("{:.0},{:.0}", at.x, at.y))),
4200 ))
4201 })
4202 .drive(|d: Drive| async move {
4203 d.long_press("target").await?;
4204 d.assert_text("state", "held 60,40 taps 0").await
4205 })
4206 }
4207
4208 #[day_macros::test(day_core)]
4210 fn on_double_tap_fires() -> Case {
4211 Case::new()
4212 .proves_modifier("on_double_tap")
4213 .page(|| {
4214 let doubles = Signal::new(0i64);
4215 let taps = Signal::new(0i64);
4216 column((
4217 label(move || format!("doubles {} taps {}", doubles.get(), taps.get()))
4218 .id(day_core::id!(state)),
4219 pad(day_core::id!(target))
4220 .on_tap(move || taps.update(|n| *n += 1))
4221 .on_double_tap(move || doubles.update(|n| *n += 1)),
4222 ))
4223 })
4224 .drive(|d: Drive| async move {
4225 d.double_tap("target").await?;
4226 d.assert_text("state", "doubles 1 taps 0").await
4227 })
4228 }
4229
4230 #[day_macros::test(day_core)]
4232 fn on_double_tap_at_reports_the_point() -> Case {
4233 Case::new()
4234 .proves_modifier("on_double_tap_at")
4235 .page(|| {
4236 let at = Signal::new(String::from("none"));
4237 column((
4238 label(move || format!("double at {}", at.get())).id(day_core::id!(state)),
4239 pad(day_core::id!(target))
4240 .on_double_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y))),
4241 ))
4242 })
4243 .drive(|d: Drive| async move {
4244 d.double_tap("target").await?;
4245 d.assert_text("state", "double at 60,40").await
4246 })
4247 }
4248
4249 #[day_macros::test(day_core)]
4251 fn on_pressed_follows_press() -> Case {
4252 Case::new()
4253 .proves_modifier("on_pressed")
4254 .page(|| {
4255 let down = Signal::new(false);
4256 let changes = Signal::new(0i64);
4257 column((
4258 label(move || {
4259 let state = if down.get() { "down" } else { "up" };
4260 format!("{state} after {}", changes.get())
4261 })
4262 .id(day_core::id!(state)),
4263 pad(day_core::id!(target)).on_pressed(move |pressed| {
4264 down.set(pressed);
4265 changes.update(|n| *n += 1);
4266 }),
4267 ))
4268 })
4269 .drive(|d: Drive| async move {
4270 d.press("target", true).await?;
4271 d.assert_text("state", "down after 1").await?;
4272 d.press("target", false).await?;
4273 d.assert_text("state", "up after 2").await
4274 })
4275 }
4276
4277 #[day_macros::test(day_core)]
4279 fn on_touches_reports_contacts() -> Case {
4280 Case::new()
4281 .proves_modifier("on_touches")
4282 .page(|| {
4283 let state = Signal::new(String::from("none"));
4284 column((
4285 label(move || state.get()).id(day_core::id!(state)),
4286 pad(day_core::id!(target)).on_touches(move |touches: &[day_spec::Touch]| {
4287 let down = touches.iter().filter(|t| t.is_down()).count();
4288 let ids: Vec<String> = touches.iter().map(|t| t.id.to_string()).collect();
4289 let last = touches.last().map_or(Point::ZERO, |t| t.location);
4290 state.set(format!(
4291 "{down} down ids {} last {:.0},{:.0}",
4292 ids.join("+"),
4293 last.x,
4294 last.y
4295 ));
4296 }),
4297 ))
4298 })
4299 .drive(|d: Drive| async move {
4300 let points = [(10.0, 10.0), (50.0, 30.0)];
4301 d.touches("target", &points, day_spec::TouchPhase::Began)
4302 .await?;
4303 d.assert_text("state", "2 down ids 0+1 last 50,30").await?;
4304 d.touches("target", &points, day_spec::TouchPhase::Ended)
4305 .await?;
4306 d.assert_text("state", "0 down ids 0+1 last 50,30").await
4307 })
4308 }
4309
4310 #[day_macros::test(day_core)]
4314 fn hit_slop_leaves_layout_alone() -> Case {
4315 Case::new()
4316 .proves_modifier("hit_slop")
4317 .proves_duty("set_hit_slop")
4318 .proves_cap(Cap::HitSlop)
4319 .page(|| {
4320 let taps = Signal::new(0i64);
4321 column((
4322 label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
4323 row((
4324 rectangle()
4325 .fill(Color::rgb(0.9, 0.2, 0.2))
4326 .frame(12.0, 12.0)
4327 .hit_slop(30.0)
4328 .on_tap(move || taps.update(|n| *n += 1))
4329 .id(day_core::id!(dot)),
4330 rectangle()
4331 .fill(Color::rgb(0.2, 0.4, 0.9))
4332 .frame(12.0, 12.0)
4333 .id(day_core::id!(next)),
4334 ))
4335 .spacing(4.0),
4336 ))
4337 .align(HAlign::Leading)
4338 })
4339 .drive(|d: Drive| async move {
4340 d.assert_frame("dot", size(12.0, 12.0)).await?;
4341 d.assert_frame(
4342 "next",
4343 FrameExpect {
4344 x: Some(16.0),
4345 y: Some(0.0),
4346 relative_to: Some("dot".into()),
4347 ..FrameExpect::default()
4348 },
4349 )
4350 .await?;
4351 d.tap("dot").await?;
4352 d.assert_text("taps", "taps 1").await
4353 })
4354 }
4355
4356 #[day_macros::test(day_core)]
4358 fn interaction_state_tracks_hover_press_focus() -> Case {
4359 Case::new()
4360 .proves_modifier("interaction")
4361 .page(|| {
4362 let state = InteractionState::new();
4363 column((
4364 label(move || {
4365 format!(
4366 "hovered {} pressed {} focused {}",
4367 state.hovered(),
4368 state.pressed(),
4369 state.focused()
4370 )
4371 })
4372 .id(day_core::id!(state)),
4373 pad(day_core::id!(target)).focusable().interaction(state),
4374 ))
4375 })
4376 .drive(|d: Drive| async move {
4377 d.assert_text("state", "hovered false pressed false focused false")
4378 .await?;
4379 d.hover("target", None).await?;
4380 d.assert_text("state", "hovered true pressed false focused false")
4381 .await?;
4382 d.press("target", true).await?;
4383 d.assert_text("state", "hovered true pressed true focused false")
4384 .await?;
4385 d.press("target", false).await?;
4386 d.hover_leave("target").await?;
4387 d.assert_text("state", "hovered false pressed false focused false")
4388 .await?;
4389 d.focus("target").await?;
4390 d.assert_text("state", "hovered false pressed false focused true")
4391 .await
4392 })
4393 }
4394
4395 #[day_macros::test(day_core)]
4397 fn interaction_state_drives_background() -> Case {
4398 Case::new()
4399 .proves_modifier("interaction")
4400 .requires(Cap::Snapshot)
4401 .page(|| {
4402 let state = InteractionState::new();
4403 label("")
4404 .frame(80.0, 40.0)
4405 .interaction(state)
4406 .background(move || {
4407 if state.pressed() {
4408 Color::rgb(1.0, 0.0, 0.0)
4409 } else {
4410 Color::rgb(0.0, 0.0, 1.0)
4411 }
4412 })
4413 .id(day_core::id!(card))
4414 })
4415 .drive(|d: Drive| async move {
4416 d.sample_pixel("card", 0.5, 0.5, "#0000ff").await?;
4417 d.press("card", true).await?;
4418 d.sample_pixel("card", 0.5, 0.5, "#ff0000").await?;
4419 d.press("card", false).await?;
4420 d.sample_pixel("card", 0.5, 0.5, "#0000ff").await
4421 })
4422 }
4423
4424 #[day_macros::test(day_core)]
4427 fn enabled_disables_subtree() -> Case {
4428 Case::new()
4429 .proves_modifier("enabled")
4430 .proves_duty("set_subtree_enabled")
4431 .page(|| {
4432 let on = Signal::new(true);
4433 let presses = Signal::new(0i64);
4434 let drags = Signal::new(0i64);
4435 let pressed = Signal::new(false);
4436 column((
4437 label(move || {
4438 format!(
4439 "presses {} drags {} pressed {}",
4440 presses.get(),
4441 drags.get(),
4442 pressed.get()
4443 )
4444 })
4445 .id(day_core::id!(state)),
4446 button("Flip")
4447 .action(move || on.update(|v| *v = !*v))
4448 .id(day_core::id!(flip)),
4449 column((
4450 button("Inner")
4451 .action(move || presses.update(|n| *n += 1))
4452 .id(day_core::id!(inner)),
4453 pad(day_core::id!(target))
4454 .on_pressed(move |down| pressed.set(down))
4455 .on_drag(move |d: Drag| {
4456 if d.phase == DragPhase::Ended {
4457 drags.update(|n| *n += 1);
4458 }
4459 }),
4460 ))
4461 .enabled(on),
4462 ))
4463 })
4464 .drive(|d: Drive| async move {
4465 let native = |enabled| NativeExpect {
4466 enabled: Some(enabled),
4467 ..NativeExpect::default()
4468 };
4469 d.assert_enabled("inner", true).await?;
4470 d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4471 d.assert_text("state", "presses 0 drags 1 pressed false")
4472 .await?;
4473 d.press("target", true).await?;
4475 d.assert_text("state", "presses 0 drags 1 pressed true")
4476 .await?;
4477 d.tap("flip").await?;
4478 d.assert_text("state", "presses 0 drags 1 pressed false")
4479 .await?;
4480 d.assert_enabled("inner", false).await?;
4481 d.assert_native("inner", native(false)).await?;
4482 d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4483 d.press("target", true).await?;
4484 d.assert_text("state", "presses 0 drags 1 pressed false")
4485 .await?;
4486 d.tap("flip").await?;
4487 d.assert_enabled("inner", true).await?;
4488 d.assert_native("inner", native(true)).await?;
4489 d.tap("inner").await?;
4490 d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4491 d.assert_text("state", "presses 1 drags 2 pressed false")
4492 .await
4493 })
4494 }
4495
4496 #[day_macros::test(day_core)]
4499 fn key_phases_reach_their_handlers() -> Case {
4500 Case::new()
4501 .proves_modifier("on_key_up")
4502 .proves_cap(Cap::KeyPhases)
4503 .page(|| {
4504 let counts = Signal::new((0i64, 0i64, 0i64));
4505 column((
4506 label(move || {
4507 let (down, repeat, up) = counts.get();
4508 format!("down {down} repeat {repeat} up {up}")
4509 })
4510 .id(day_core::id!(state)),
4511 pad(day_core::id!(target))
4512 .focusable()
4513 .on_key(move |k| {
4514 if k.key == day_spec::Key::ArrowRight {
4515 counts.update(|c| {
4516 if k.is_repeat() {
4517 c.1 += 1;
4518 } else {
4519 c.0 += 1;
4520 }
4521 });
4522 }
4523 })
4524 .on_key_up(move |k| {
4525 if k.key == day_spec::Key::ArrowRight && k.is_release() {
4526 counts.update(|c| c.2 += 1);
4527 }
4528 }),
4529 ))
4530 })
4531 .drive(|d: Drive| async move {
4532 d.focus("target").await?;
4533 d.key(None, "ArrowRight").await?;
4534 d.assert_text("state", "down 1 repeat 0 up 0").await?;
4535 d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Repeat)
4536 .await?;
4537 d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Repeat)
4538 .await?;
4539 d.assert_text("state", "down 1 repeat 2 up 0").await?;
4540 d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Up)
4541 .await?;
4542 d.assert_text("state", "down 1 repeat 2 up 1").await
4543 })
4544 }
4545
4546 #[day_macros::test(day_core)]
4549 fn focusable_piece_holds_and_yields_focus() -> Case {
4550 Case::new()
4551 .proves_cap(Cap::Focusable)
4552 .proves_duty("set_focusable")
4553 .requires(Cap::Focusable)
4554 .page(|| {
4555 let focused = Signal::new(false);
4556 let keys = Signal::new(0i64);
4557 let text = Signal::new(String::new());
4558 column((
4559 label(move || format!("focused {} keys {}", focused.get(), keys.get()))
4560 .id(day_core::id!(state)),
4561 pad(day_core::id!(target))
4562 .focusable()
4563 .focused(focused)
4564 .on_key(move |_| keys.update(|n| *n += 1)),
4565 text_field(text).id(day_core::id!(field)),
4566 ))
4567 })
4568 .drive(|d: Drive| async move {
4569 d.assert_text("state", "focused false keys 0").await?;
4570 d.focus("target").await?;
4571 d.assert_focused("target", true).await?;
4572 d.assert_text("state", "focused true keys 0").await?;
4573 d.key(None, "ArrowDown").await?;
4574 d.assert_text("state", "focused true keys 1").await?;
4575 d.focus("field").await?;
4577 d.assert_focused("field", true).await?;
4578 d.assert_focused("target", false).await?;
4579 d.assert_text("state", "focused false keys 1").await
4580 })
4581 }
4582
4583 #[day_macros::test(day_core)]
4585 fn primary_pointer_follows_input() -> Case {
4586 Case::new()
4587 .proves_duty("primary_pointer")
4588 .page(|| label(move || day_core::primary_pointer().name()).id(day_core::id!(kind)))
4589 .drive(|d: Drive| async move {
4590 let before = untrack(day_core::primary_pointer);
4591 d.pointer(day_spec::PointerKind::Touch).await?;
4592 d.assert_text("kind", "touch").await?;
4593 d.pointer(day_spec::PointerKind::Stylus).await?;
4594 d.assert_text("kind", "stylus").await?;
4595 d.pointer(day_spec::PointerKind::Mouse).await?;
4596 d.assert_text("kind", "mouse").await?;
4597 d.pointer(before).await
4599 })
4600 }
4601
4602 #[day_macros::test(day_core)]
4604 fn drop_target_reports_enter_leave_drop() -> Case {
4605 Case::new()
4606 .proves_modifier("drop_target")
4607 .proves_duty("set_drop_target")
4608 .page(|| {
4609 let hovering = Signal::new(0i64);
4610 let got = Signal::new(String::from("nothing"));
4611 column((
4612 label(move || format!("hovering {} got {}", hovering.get(), got.get()))
4613 .id(day_core::id!(state)),
4614 pad(day_core::id!(zone)).drop_target(
4615 DropTarget::new(["text/plain"])
4616 .on_enter(move |_| hovering.update(|n| *n += 1))
4617 .on_leave(move || hovering.update(|n| *n -= 1))
4618 .on_drop(move |drop| {
4619 let text = drop
4620 .items
4621 .first()
4622 .and_then(|item| item.get("text/plain"))
4623 .and_then(|bytes| std::str::from_utf8(bytes).ok());
4624 got.set(text.unwrap_or("?").to_owned());
4625 text.is_some()
4626 }),
4627 ),
4628 ))
4629 })
4630 .drive(|d: Drive| async move {
4631 d.drag_enter("zone", "hello").await?;
4632 d.drag_enter("zone", "hello").await?;
4634 d.assert_text("state", "hovering 1 got nothing").await?;
4635 d.drag_leave("zone").await?;
4636 d.assert_text("state", "hovering 0 got nothing").await?;
4637 d.drop_text("zone", "hello").await?;
4638 d.assert_text("state", "hovering 0 got hello").await
4639 })
4640 }
4641
4642 #[day_macros::test(day_core)]
4644 fn on_files_dropped_receives_paths() -> Case {
4645 Case::new()
4646 .proves_modifier("on_files_dropped")
4647 .page(|| {
4648 let got = Signal::new(String::from("none"));
4649 column((
4650 label(move || format!("files {}", got.get())).id(day_core::id!(state)),
4651 pad(day_core::id!(zone)).on_files_dropped(move |paths| {
4652 let names: Vec<String> = paths
4653 .iter()
4654 .filter_map(|p| p.file_name())
4655 .map(|n| n.to_string_lossy().into_owned())
4656 .collect();
4657 got.set(names.join("+"));
4658 }),
4659 ))
4660 })
4661 .drive(|d: Drive| async move {
4662 d.drop_files("zone", &["/work/first.txt", "/work/second%20draft.md"])
4663 .await?;
4664 d.assert_text("state", "files first.txt+second draft.md")
4665 .await
4666 })
4667 }
4668
4669 #[day_macros::test(day_core)]
4672 fn focused_binding_moves_focus() -> Case {
4673 Case::new()
4674 .proves_modifier("focused")
4675 .page(|| {
4676 let want = Signal::new(false);
4677 column((
4678 label(move || format!("focused {}", want.get())).id(day_core::id!(state)),
4679 button("Focus")
4680 .action(move || want.set(true))
4681 .id(day_core::id!(go)),
4682 text_field(Signal::new(String::new()))
4683 .focused(want)
4684 .id(day_core::id!(field)),
4685 ))
4686 })
4687 .drive(|d: Drive| async move {
4688 d.assert_focused("field", false).await?;
4689 d.tap("go").await?;
4690 d.assert_focused("field", true).await?;
4691 d.assert_text("state", "focused true").await
4692 })
4693 }
4694
4695 #[day_macros::test(day_core)]
4698 fn focused_inputs_survive_page_removal() -> Case {
4699 Case::new()
4700 .proves_duty("focus")
4701 .page(|| {
4702 let shown = Signal::new(true);
4703 column((
4704 button("Toggle page")
4705 .action(move || shown.set(!shown.get()))
4706 .id(day_core::id!(toggle)),
4707 text_field(Signal::new(String::new())).id(day_core::id!(survivor)),
4708 when(
4709 move || shown.get(),
4710 || {
4711 column((
4712 text_field(Signal::new(String::new())).id(day_core::id!(entry)),
4713 ))
4714 .background(Color::rgb(0.5, 0.5, 0.5))
4715 },
4716 ),
4717 ))
4718 })
4719 .drive(|d: Drive| async move {
4720 for _ in 0..4 {
4721 d.focus("entry").await?;
4722 d.assert_focused("entry", true).await?;
4723 d.tap("toggle").await?;
4725 d.assert_missing("entry").await?;
4726 d.wait_idle().await?;
4727 d.tap("toggle").await?;
4728 }
4729 d.focus("survivor").await?;
4730 d.tap("toggle").await?;
4731 d.assert_focused("survivor", true).await?;
4732 d.input("survivor", "still editable").await?;
4733 d.assert_text("survivor", "still editable").await
4734 })
4735 }
4736
4737 #[day_macros::test(day_core)]
4741 fn height_fixes_height() -> Case {
4742 Case::new()
4743 .proves_modifier("height")
4744 .page(|| {
4745 column((rectangle()
4746 .fill(Color::rgb(1.0, 0.0, 0.0))
4747 .id(day_core::id!(bar))
4748 .height(37.0),))
4749 .width(100.0)
4750 })
4751 .drive(|d: Drive| async move {
4752 d.assert_frame(
4753 "bar",
4754 FrameExpect {
4755 height: Some(37.0),
4756 ..Default::default()
4757 },
4758 )
4759 .await
4760 })
4761 }
4762
4763 #[day_macros::test(day_core)]
4765 fn grow_vertical_fills_column() -> Case {
4766 Case::new()
4767 .proves_modifier("grow")
4768 .page(|| {
4769 row((
4770 column((
4771 rectangle()
4772 .fill(Color::rgb(1.0, 0.0, 0.0))
4773 .id(day_core::id!(top))
4774 .frame(40.0, 20.0),
4775 rectangle()
4776 .fill(Color::rgb(0.0, 0.0, 1.0))
4777 .id(day_core::id!(rest))
4778 .width(40.0)
4779 .grow(Dimension::Height),
4780 ))
4781 .spacing(0.0)
4782 .height(120.0),
4783 rectangle()
4784 .fill(Color::rgb(0.0, 1.0, 0.0))
4785 .id(day_core::id!(both))
4786 .width(30.0)
4787 .grow(Dimension::Height),
4788 ))
4789 .spacing(0.0)
4790 .align(VAlign::Top)
4791 .height(120.0)
4792 })
4793 .drive(|d: Drive| async move {
4794 d.assert_frame(
4795 "rest",
4796 FrameExpect {
4797 height: Some(100.0),
4798 ..Default::default()
4799 },
4800 )
4801 .await?;
4802 d.assert_frame(
4803 "both",
4804 FrameExpect {
4805 height: Some(120.0),
4806 ..Default::default()
4807 },
4808 )
4809 .await
4810 })
4811 }
4812
4813 #[day_macros::test(day_core)]
4815 fn grid_span_and_align() -> Case {
4816 Case::new()
4817 .proves_modifier("grid_span")
4818 .proves_modifier("grid_align")
4819 .page(|| {
4820 let cell = |id: day_core::ElementId, w: f64| {
4821 rectangle()
4822 .fill(Color::rgb(0.2, 0.4, 0.9))
4823 .id(id)
4824 .frame(w, 20.0)
4825 };
4826 grid((
4827 grid_row((cell(day_core::id!(a), 40.0), cell(day_core::id!(b), 60.0))),
4828 grid_row((cell(day_core::id!(wide), 30.0)
4829 .grid_align(day_core::Alignment::TopTrailing)
4830 .grid_span(2),)),
4831 ))
4832 .spacing(0.0)
4833 .align(day_core::Alignment::TopLeading)
4834 })
4835 .drive(|d: Drive| async move {
4836 d.assert_frame(
4839 "wide",
4840 FrameExpect {
4841 x: Some(70.0),
4842 relative_to: Some("a".into()),
4843 ..Default::default()
4844 },
4845 )
4846 .await
4847 })
4848 }
4849
4850 #[day_macros::test(day_core)]
4852 fn overlay_centers() -> Case {
4853 Case::new()
4854 .proves_modifier("overlay")
4855 .requires(Cap::Snapshot)
4856 .page(|| {
4857 rectangle()
4858 .fill(Color::rgb(1.0, 0.0, 0.0))
4859 .frame(90.0, 90.0)
4860 .overlay(
4861 rectangle()
4862 .fill(Color::rgb(0.0, 0.0, 1.0))
4863 .frame(30.0, 30.0),
4864 )
4865 .id(day_core::id!(base))
4866 })
4867 .drive(|d: Drive| async move {
4868 d.sample_pixel("base", 0.5, 0.5, "#0000ff").await?;
4869 d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
4870 })
4871 }
4872
4873 #[day_macros::test(day_core)]
4875 fn transform_applies_whole() -> Case {
4876 Case::new()
4877 .proves_duty("set_transform")
4878 .proves_modifier("transform")
4879 .requires(Cap::Snapshot)
4880 .page(|| {
4881 zstack((
4882 rectangle().fill(Color::WHITE),
4883 label("")
4884 .frame(20.0, 20.0)
4885 .background(Color::rgb(0.0, 0.0, 1.0))
4886 .transform(Transform {
4887 tx: 30.0,
4888 sx: 2.0,
4889 sy: 2.0,
4890 ..Transform::default()
4891 }),
4892 ))
4893 .id(day_core::id!(ground))
4894 .frame(120.0, 60.0)
4895 })
4896 .drive(|d: Drive| async move {
4897 d.sample_pixel("ground", 0.75, 0.5, "#0000ff").await?;
4899 d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await
4900 })
4901 }
4902
4903 #[day_macros::test(day_core)]
4906 fn animation_lands_on_final() -> Case {
4907 Case::new()
4908 .proves_modifier("animation")
4909 .requires(Cap::Snapshot)
4910 .page(|| {
4911 let moved = Signal::new(false);
4912 column((
4913 button("Move")
4914 .action(move || moved.set(true))
4915 .id(day_core::id!(move_button)),
4916 zstack((
4917 rectangle().fill(Color::WHITE),
4918 label("")
4919 .frame(40.0, 40.0)
4920 .background(Color::rgb(0.0, 0.0, 1.0))
4921 .translation(move || if moved.get() { 80.0 } else { 0.0 }, 0.0)
4922 .animation(day_spec::AnimSpec::linear(150)),
4923 ))
4924 .align(day_core::Alignment::Leading)
4925 .id(day_core::id!(ground))
4926 .frame(120.0, 40.0),
4927 ))
4928 })
4929 .drive(|d: Drive| async move {
4930 d.sample_pixel("ground", 0.1, 0.5, "#0000ff").await?;
4931 d.tap("move_button").await?;
4932 d.wait_idle().await?;
4933 d.pause(0.4).await?;
4934 d.sample_pixel("ground", 0.85, 0.5, "#0000ff").await?;
4935 d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
4936 })
4937 }
4938
4939 #[day_macros::test(day_core)]
4941 fn ids_name_elements() -> Case {
4942 Case::new()
4943 .proves_modifier("id")
4944 .proves_modifier("id_of")
4945 .page(|| {
4946 let n = Signal::new(1i64);
4947 column((
4948 label("Fixed").id(day_core::id!(fixed)),
4949 label("Derived").id_of(move || day_core::id!(derived, n.get())),
4950 label("Keyed").id(day_core::id!(keyed, 7)),
4951 button("Next")
4952 .action(move || n.set(2))
4953 .id(day_core::id!(next)),
4954 ))
4955 })
4956 .drive(|d: Drive| async move {
4957 d.assert_text("fixed", "Fixed").await?;
4958 d.assert_text("keyed:7", "Keyed").await?;
4959 d.assert_text("derived:1", "Derived").await?;
4960 d.tap("next").await?;
4961 d.assert_missing("derived:1").await?;
4962 d.assert_text("derived:2", "Derived").await
4963 })
4964 }
4965
4966 #[day_macros::test(day_core)]
4968 fn tweak_and_native_ref_see_node() -> Case {
4969 Case::new()
4970 .proves_modifier("tweak")
4971 .proves_modifier("native_ref")
4972 .page(|| {
4973 let tweaked = Signal::new(false);
4974 let r = NativeRef::new();
4975 let held = r.clone();
4976 column((
4977 label(move || format!("tweaked {}", tweaked.get())).id(day_core::id!(tweaked)),
4978 label(move || format!("held {}", held.node().is_some()))
4979 .id(day_core::id!(held)),
4980 label("Target")
4981 .tweak(move |_node| tweaked.set(true))
4982 .native_ref(&r),
4983 ))
4984 })
4985 .drive(|d: Drive| async move {
4986 d.assert_text("tweaked", "tweaked true").await?;
4987 d.assert_text("held", "held true").await
4988 })
4989 }
4990
4991 #[day_macros::test(day_core)]
4993 fn modifier_applies() -> Case {
4994 Case::new()
4995 .proves_modifier("modifier")
4996 .page(|| {
4997 let padded = |content: AnyPiece| content.padding(10.0).any();
4998 column((label("Inner")
4999 .id(day_core::id!(inner))
5000 .modifier(padded)
5001 .id(day_core::id!(outer)),))
5002 .align(HAlign::Leading)
5003 })
5004 .drive(|d: Drive| async move {
5005 d.assert_frame(
5006 "inner",
5007 FrameExpect {
5008 x: Some(10.0),
5009 y: Some(10.0),
5010 relative_to: Some("outer".into()),
5011 ..Default::default()
5012 },
5013 )
5014 .await
5015 })
5016 }
5017
5018 #[day_macros::test(day_core)]
5020 fn announce_reaches_reader() -> Case {
5021 Case::new()
5022 .proves_duty("announce")
5023 .proves_cap(Cap::Announce)
5024 .page(|| {
5025 button("Save")
5026 .action(|| day_core::announce("Saved"))
5027 .id(day_core::id!(save))
5028 })
5029 .drive(|d: Drive| async move {
5030 d.tap("save").await?;
5031 d.assert_announced("Saved").await
5032 })
5033 }
5034}
5035
5036#[cfg(test)]
5037mod transfer_tests {
5038 use super::*;
5039 use day_spec::transfer::*;
5040
5041 #[test]
5042 fn transfer_callbacks_restore_owner_scope_and_reject_after_disposal() {
5043 let owner = Scope::child();
5044 let foreign = Scope::child();
5045 foreign.provide(22u32);
5046 let hovers = Rc::new(Cell::new(0i32));
5047 let leaves = Rc::new(Cell::new(0i32));
5048 let counts = (hovers.clone(), leaves.clone());
5049 let (source, target) = owner.enter(|| {
5050 owner.provide(11u32);
5051 let check = || assert_eq!(day_core::environment::<u32>(), Some(11));
5052 let (hovers, leaves) = counts;
5053 let entered = hovers.clone();
5054 (
5055 scoped_drag_source(Rc::new(move |_| {
5056 check();
5057 Some(Offer::default())
5058 })),
5059 scoped_drop_target(
5060 Target::new(Vec::<String>::new())
5061 .accept(move |_| {
5062 check();
5063 Operation::Copy
5064 })
5065 .on_enter(move |_| {
5066 check();
5067 entered.set(entered.get() + 1);
5068 })
5069 .on_leave(move || {
5070 check();
5071 hovers.set(hovers.get() - 1);
5072 leaves.set(leaves.get() + 1);
5073 })
5074 .on_drop(move |_| {
5075 check();
5076 true
5077 }),
5078 ),
5079 )
5080 });
5081 let location = || Location {
5082 position: day_spec::Point::new(40., 20.),
5083 types: vec![],
5084 allowed: vec![Operation::Copy],
5085 local: true,
5086 };
5087 foreign.enter(|| {
5088 assert!(source(day_spec::Point::new(0., 0.)).is_some());
5089 assert_eq!(target.proposal(&location()), Operation::Copy);
5092 assert_eq!(target.proposal(&location()), Operation::Copy);
5093 assert_eq!((hovers.get(), leaves.get()), (1, 0));
5094 assert!(target.is_hovering());
5095 target.leave();
5096 target.leave();
5097 assert_eq!((hovers.get(), leaves.get()), (0, 1));
5098 assert_eq!(target.proposal(&location()), Operation::Copy);
5099 assert!(target.deliver(location(), Offer::default()));
5100 assert_eq!((hovers.get(), leaves.get()), (0, 2));
5101 assert!(!target.is_hovering());
5102 assert_eq!(day_core::environment::<u32>(), Some(22));
5103 owner.dispose();
5104 assert!(source(day_spec::Point::new(0., 0.)).is_none());
5105 assert_eq!(target.proposal(&location()), Operation::None);
5106 assert!(!target.deliver(location(), Offer::default()));
5107 assert_eq!((hovers.get(), leaves.get()), (0, 2));
5108 });
5109 foreign.dispose();
5110 }
5111}