1use std::sync::Arc;
9
10use super::{
11 Accessible, AnyElement, Interactive, IntoReactive,
12 builder::{ElNode, Element, IntoElement, IntoListener, Listener, ParentElement},
13 events::{
14 self, CaretEvent, Composition, HintReason, NativeEvent, OverlayPosition, Selection,
15 VideoInfo, VideoProgress, WebNavigation,
16 },
17};
18use crate::{
19 AudioSession, AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, Hsla, JsonValue,
20 KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp,
21 OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType, Rgba,
22 ScreenAnimation, ScreenProp, ScrollProp, Size, StatusBarSetting, SubmitBehavior, Tag,
23 WebSource,
24 canvas::{
25 CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
26 Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
27 },
28 geometry::{Bounds, Corners, Percentage, Point, Radians, ScaledPixels},
29 js::host::HostProps,
30 overlay::{Align, OverlayAnchor, Placement},
31 style::SvgPaint,
32};
33
34pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
36 match (a, b) {
37 (Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
38 (Prop::ComponentPropBinding(a, _), Prop::ComponentPropBinding(b, _)) => a == b,
39 (Prop::RustProp(a, _), Prop::RustProp(b, _)) => a == b,
40 _ => HostProps::same_kind(a, b),
41 }
42}
43
44pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
47 match prop {
48 Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
49 Prop::ComponentPropBinding(name, _) => Some(Prop::ComponentPropBinding(name.clone(), None)),
50 Prop::RustProp(name, _) => Some(Prop::RustProp(name, None)),
51 _ => HostProps::reset(prop),
52 }
53}
54
55pub(crate) fn set(node: &mut ElNode, prop: Prop) {
57 set_in(&mut node.attrs.props, prop);
58}
59
60crate::static_reactive!(Color: Color);
61crate::static_reactive!(Hsla: Hsla, Rgba, Color);
62crate::static_reactive!(crate::AccessibilityRole: crate::AccessibilityRole);
63crate::static_reactive!(AutoCapitalize: AutoCapitalize);
64crate::static_reactive!(AutoFill: AutoFill);
65crate::static_reactive!(crate::HeaderSystemItem: crate::HeaderSystemItem);
66crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
67crate::static_reactive!(KeyboardType: KeyboardType);
68crate::static_reactive!(ModalAnimation: ModalAnimation);
69crate::static_reactive!(ModalPresentation: ModalPresentation);
70crate::static_reactive!(ResizeMode: ResizeMode);
71crate::static_reactive!(ReturnKeyType: ReturnKeyType);
72crate::static_reactive!(SubmitBehavior: SubmitBehavior);
73crate::static_reactive!(PasteBehavior: PasteBehavior);
74crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
75crate::static_reactive!(JsonValue: JsonValue);
76crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
77crate::static_reactive!(Placement: Placement);
78crate::static_reactive!(Align: Align);
79
80pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
82 match props.iter_mut().find(|p| same_kind(p, &prop)) {
83 Some(p) => *p = prop,
84 None => props.push(prop),
85 }
86}
87
88pub(crate) fn bind_prop<T: 'static>(
91 node: &mut ElNode,
92 value: impl IntoReactive<T>,
93 prop: impl Fn(T) -> Prop + 'static,
94) {
95 node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
96}
97
98fn listen<T: ?Sized + ToOwned + 'static>(
100 node: &mut ElNode,
101 kind: EventKind,
102 listener: Listener<T>,
103 decode: events::Decode<T>,
104) {
105 node.handlers.push((kind, events::typed(listener, decode)));
106}
107
108macro_rules! host_element {
109 ($(#[$doc:meta])* $name:ident) => {
110 $(#[$doc])*
111 #[derive(Clone)]
112 pub struct $name(ElNode);
113
114 impl Element for $name {
115 fn node(&mut self) -> &mut ElNode {
116 &mut self.0
117 }
118 }
119
120 impl IntoElement for $name {
121 fn into_element(self) -> AnyElement {
122 AnyElement(self.0)
123 }
124 }
125
126 impl Accessible for $name {}
127 impl Interactive for $name {}
128
129 impl super::builder::IntoTooltip for $name {
130 fn apply_tooltip(self, node: &mut ElNode) {
131 self.into_element().apply_tooltip(node);
132 }
133 }
134
135 #[allow(dead_code)]
137 impl $name {
138 fn set(mut self, prop: Prop) -> Self {
139 set(&mut self.0, prop);
140 self
141 }
142
143 fn bind_prop<T: 'static>(
144 mut self,
145 value: impl IntoReactive<T>,
146 prop: impl Fn(T) -> Prop + 'static,
147 ) -> Self {
148 bind_prop(&mut self.0, value, prop);
149 self
150 }
151
152 fn listen<T: ?Sized + ToOwned + 'static>(
153 mut self,
154 kind: EventKind,
155 listener: Listener<T>,
156 decode: events::Decode<T>,
157 ) -> Self {
158 listen(&mut self.0, kind, listener, decode);
159 self
160 }
161 }
162 };
163}
164
165host_element! {
166 Input
169}
170
171host_element! {
172 Scroll
175}
176
177host_element! {
178 Stack
184}
185
186host_element! {
187 Screen
191}
192
193host_element! {
194 Modal
198}
199
200host_element! {
201 InputAccessoryView
205}
206
207host_element! {
208 CanvasView
210}
211
212host_element! {
213 Svg
215}
216
217host_element! {
218 ShaderView
221}
222
223host_element! {
224 WebView
226}
227
228host_element! {
229 Video
231}
232
233host_element! {
234 NativeView
237}
238
239host_element! {
240 Overlay
245}
246
247impl ParentElement for Overlay {}
248impl ParentElement for ShaderView {}
249impl ParentElement for Scroll {}
250impl ParentElement for Stack {}
251impl ParentElement for Screen {}
252impl ParentElement for Modal {}
253
254impl ParentElement for InputAccessoryView {
256 fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
257 if !cfg!(target_os = "android") {
258 child.__push_into(&mut self.0.children);
259 }
260 self
261 }
262
263 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
264 if !cfg!(target_os = "android") {
265 self.0
266 .children
267 .extend(children.into_iter().map(|c| c.into_element().0));
268 }
269 self
270 }
271}
272
273pub fn overlay() -> Overlay {
281 Overlay(ElNode::new(Tag::Overlay))
282}
283
284pub fn input() -> Input {
286 Input(ElNode::new(Tag::Input))
287}
288
289pub fn scroll() -> Scroll {
291 Scroll(ElNode::new(Tag::Scroll))
292}
293
294#[doc(hidden)]
300pub fn stack() -> Stack {
301 Stack(ElNode::new(Tag::Stack))
302}
303
304#[doc(hidden)]
309pub fn screen() -> Screen {
310 let mut node = ElNode::new(Tag::Screen);
311 node.handlers.push((EventKind::Insets, Listener::noop()));
313 Screen(node)
314}
315
316#[doc(hidden)]
321pub fn modal() -> Modal {
322 let mut node = ElNode::new(Tag::Modal);
323 node.handlers.push((EventKind::Insets, Listener::noop()));
325 Modal(node)
326}
327
328pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
334 let tag = if cfg!(target_os = "android") {
335 Tag::View
336 } else {
337 Tag::InputAccessory
338 };
339 let mut node = ElNode::new(tag);
340 if cfg!(target_os = "android") {
341 node.style.value(
342 crate::StyleKey::Display,
343 crate::PropertyValue::Display(taffy::Display::None),
344 );
345 } else {
346 set(&mut node, Prop::NativeId(Some(native_id.into())));
347 }
348 InputAccessoryView(node)
349}
350
351pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
356 let mut node = ElNode::new(Tag::Canvas);
357 node.bind_attr(painter, |attrs, painter: Painter| {
358 attrs.drawing = Some(Arc::new(painter.drawing));
359 attrs.bound = painter.nodes;
360 });
361 CanvasView(node)
362}
363
364crate::static_reactive!(Painter: Painter, Drawing);
365
366pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
386 #[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
387 {
388 let mut node = ElNode::new(Tag::Canvas);
389 let shown = svg_drawing(src);
390 node.bind_attr(
391 move || shown.get(),
392 |attrs, drawing| attrs.drawing = drawing,
393 );
394 Svg(node)
395 }
396 #[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
397 {
398 let mut node = ElNode::new(Tag::Image);
399 node.style.value(
400 crate::StyleKey::ObjectFit,
401 crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
402 );
403 node.bind_attr(src, |attrs, src| attrs.src = Some(src));
404 set(
406 &mut node,
407 Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
408 );
409 Svg(node)
410 }
411}
412
413#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
418fn svg_drawing(
419 src: impl IntoReactive<super::ImageSrc>,
420) -> super::reactive::Signal<Option<Arc<Drawing>>> {
421 use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
422 let src = src.into_reactive();
423 let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
424 let lease = stored(crate::image::Lease::none());
425 let task = stored(None::<super::Spawned<()>>);
426 render_effect(move || {
427 let src = match &src {
428 super::Reactive::Static(src) => src.clone(),
429 super::Reactive::Bound(f) => f(),
430 };
431 untracked(|| {
432 drop(task.replace(None));
433 let context = crate::image::loader::context();
434 let source = crate::ImageSource {
435 uri: src.uri.as_str().into(),
436 size: None,
437 scales: crate::ImageScales::NONE,
438 data: None,
439 }
440 .inline();
441 let Some(location) = context.locate(&source) else {
442 log::warn!("svg: unsupported source `{}`", source.uri);
443 shown.set(None);
444 lease.replace(crate::image::Lease::none());
445 return;
446 };
447 if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
448 shown.set(Some(drawing));
449 lease.replace(held);
450 return;
451 }
452 let load = crate::svg::drawings::load(location, context);
453 task.replace(Some(super::spawn(async move {
454 let (drawing, held) = load.await;
455 shown.set(Some(drawing));
456 lease.replace(held);
457 })));
458 });
459 });
460 shown
461}
462
463pub fn shader() -> ShaderView {
467 ShaderView(ElNode::new(Tag::Shader))
468}
469
470pub fn shader_effect() -> ShaderView {
474 ShaderView(ElNode::new(Tag::ShaderEffect))
475}
476
477pub fn shader_transition() -> ShaderView {
482 ShaderView(ElNode::new(Tag::ShaderTransition))
483}
484
485pub fn screen_effect() -> ShaderView {
488 ShaderView(ElNode::new(Tag::ScreenEffect))
489}
490
491pub fn screen_transition() -> ShaderView {
495 ShaderView(ElNode::new(Tag::ScreenTransition))
496}
497
498crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);
499
500pub struct Uniform(UniformSource);
502
503enum UniformSource {
504 Value(super::Reactive<crate::shader::UniformValue>),
505 Animated(super::AnimatedNode),
506}
507
508pub trait IntoUniform {
511 fn into_uniform(self) -> Uniform;
513}
514
515impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
516 fn into_uniform(self) -> Uniform {
517 Uniform(UniformSource::Value(self.into_reactive()))
518 }
519}
520
521impl IntoUniform for &super::AnimatedValue {
522 fn into_uniform(self) -> Uniform {
523 Uniform(UniformSource::Animated(super::Animated::animated_node(
524 self,
525 )))
526 }
527}
528
529impl IntoUniform for &super::AnimatedNode {
530 fn into_uniform(self) -> Uniform {
531 Uniform(UniformSource::Animated(*self))
532 }
533}
534crate::static_reactive!(
535 crate::shader::UniformValue: crate::shader::UniformValue,
536 f32,
537 i32,
538 Color,
539 Hsla,
540 [f32; 2],
541 [f32; 3],
542 [f32; 4],
543 Vec<crate::shader::UniformValue>
544);
545
546impl ShaderView {
547 pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
551 self.bind_prop(shader, |s| Prop::Shader(Some(s)))
552 }
553
554 pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
561 let name: Arc<str> = name.into();
562 let value = match value.into_uniform().0 {
563 UniformSource::Value(value) => value,
564 UniformSource::Animated(node) => {
565 let value = match node.live() {
566 Some(node) => {
567 let id = node.id();
568 self.0.attrs.bound.push(node);
569 crate::shader::UniformValue::Animated(id)
570 }
571 None => crate::shader::UniformValue::Number(0.0),
572 };
573 super::Reactive::Static(value)
574 }
575 };
576 self.0.bind_attr(value, move |attrs, value| {
577 let mut uniforms = attrs
578 .props
579 .iter()
580 .find_map(|p| match p {
581 Prop::Uniforms(u) => Some(u.clone()),
582 _ => None,
583 })
584 .unwrap_or_default();
585 match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
586 Some(entry) => entry.1 = value,
587 None => uniforms.0.push((name.clone(), value)),
588 }
589 set_in(&mut attrs.props, Prop::Uniforms(uniforms));
590 });
591 self
592 }
593
594 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
596 self.bind_prop(paused, Prop::ShaderPaused)
597 }
598
599 pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
602 self.bind_prop(progress, |p| {
603 Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
604 })
605 }
606
607 pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
610 let progress = match value.animated_node().live() {
611 Some(node) => {
612 let id = node.id();
613 self.0.attrs.bound.push(node);
614 crate::shader::ShaderProgress::Animated(id)
615 }
616 None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
617 };
618 self.set(Prop::ShaderProgress(progress))
619 }
620
621 pub fn max_sample_offset(self, offset: Points) -> Self {
624 self.set(Prop::MaxSampleOffset(offset))
625 }
626
627 pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
630 self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
631 }
632
633 pub fn duration(self, duration: std::time::Duration) -> Self {
635 self.set(Prop::TransitionDuration(Some(
636 duration.as_secs_f32() * 1000.0,
637 )))
638 }
639
640 pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
643 self.set(Prop::TransitionFallback(fallback))
644 }
645}
646
647crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);
648
649pub fn web_view(url: impl IntoReactive<String>) -> WebView {
651 WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
652 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
653 })
654}
655
656pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
659 WebView(ElNode::new(Tag::WebView)).html(html, base_url)
660}
661
662pub fn video(url: impl IntoReactive<String>) -> Video {
665 Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
666 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
667 })
668}
669
670pub fn native(name: &str) -> NativeView {
672 NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
673}
674
675impl Input {
676 pub fn value(self, text: impl IntoReactive<String>) -> Self {
679 self.bind_prop(text, |text: String| Prop::Value(text))
680 }
681
682 pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
684 self.bind_prop(text, |text: String| Prop::DefaultValue(text))
685 }
686
687 pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
689 self.bind_prop(text, |text: String| Prop::Placeholder(text))
690 }
691
692 pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
694 self.bind_prop(color, |color: Hsla| {
695 Prop::PlaceholderColor(Some(color.into()))
696 })
697 }
698
699 pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
702 self.bind_prop(color, |color: Hsla| {
703 Prop::SelectionColor(Some(color.into()))
704 })
705 }
706
707 pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
709 self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
710 }
711
712 pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
714 self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
715 }
716
717 pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
719 self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
720 }
721
722 pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
725 self.bind_prop(appearance, |appearance: KeyboardAppearance| {
726 Prop::KeyboardAppearance(appearance)
727 })
728 }
729
730 pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
732 self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
733 }
734
735 pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
737 self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
738 }
739
740 pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
742 self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
743 }
744
745 pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
747 self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
748 }
749
750 pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
752 self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
753 }
754
755 pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
758 self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
759 }
760
761 pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
763 self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
764 }
765
766 pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
768 self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
769 }
770
771 pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
774 self.bind_prop(behavior, |behavior: SubmitBehavior| {
775 Prop::SubmitBehavior(Some(behavior))
776 })
777 }
778
779 pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
782 self.bind_prop(behavior, Prop::PasteBehavior)
783 }
784
785 pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
789 self.listen(EventKind::Paste, listener.into_listener(), events::paste)
790 }
791
792 pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
794 self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
795 }
796
797 pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
799 self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
800 }
801
802 pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
805 self.bind_prop(native_id, |id: String| {
806 Prop::InputAccessoryViewId(Some(id.into()))
807 })
808 }
809
810 pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
815 self.bind_prop(range, |(start, end): (u32, u32)| {
816 Prop::Selection(start, end)
817 })
818 }
819
820 pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
822 self.listen(
823 EventKind::ChangeText,
824 listener.into_listener(),
825 events::text,
826 )
827 }
828
829 pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
831 self.listen(
832 EventKind::SubmitEditing,
833 listener.into_listener(),
834 events::text,
835 )
836 }
837
838 pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
840 self.listen(
841 EventKind::SelectionChange,
842 listener.into_listener(),
843 events::selection,
844 )
845 }
846
847 pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
851 self.listen(
852 EventKind::CaretMove,
853 listener.into_listener(),
854 events::caret,
855 )
856 }
857
858 pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
860 self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
861 }
862
863 pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
867 self.listen(
868 EventKind::CompositionChange,
869 listener.into_listener(),
870 events::composition,
871 )
872 }
873
874 pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
876 self.listen(
877 EventKind::ContentSizeChange,
878 listener.into_listener(),
879 events::size,
880 )
881 }
882}
883
884impl Scroll {
885 pub fn horizontal(self) -> Self {
887 self.set(Prop::Horizontal(true))
888 }
889
890 pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
892 self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
893 }
894
895 pub fn zoom_range(self, min: f32, max: f32) -> Self {
897 self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
898 .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
899 }
900
901 pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
903 self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
904 }
905
906 pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
909 self.bind_prop(bounces, |bounces: bool| {
910 Prop::Scroll(ScrollProp::BouncesZoom(bounces))
911 })
912 }
913
914 pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
916 self.bind_prop(enabled, |enabled: bool| {
917 Prop::Scroll(ScrollProp::Pinch(enabled))
918 })
919 }
920
921 pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
923 self.bind_prop(center, |center: bool| {
924 Prop::Scroll(ScrollProp::CenterContent(center))
925 })
926 }
927}
928
929impl super::Scrollable for Scroll {}
930
931impl Screen {
932 fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
933 let mut node = ElNode::new(Tag::HeaderItem);
934 node.key = Some(key.into());
935 set(&mut node, Prop::HeaderSlot(slot));
936 node.children.push(item.into_element().0);
937 self.0.children.push(node);
938 self
939 }
940
941 pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
943 self.bind_prop(title, |t| {
944 Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
945 })
946 }
947
948 pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
950 self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
951 }
952
953 pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
956 self.bind_prop(hides, |v| {
957 Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
958 })
959 }
960
961 pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
963 self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
964 }
965
966 pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
968 self.bind_prop(transparent, |v| {
969 Prop::Screen(ScreenProp::HeaderTransparent(v))
970 })
971 }
972
973 pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
978 let style = match style.into_reactive() {
979 super::Reactive::Static(s) if s.1.is_bound() => {
981 super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
982 }
983 style => style,
984 };
985 self.0.bind_attr(style, |a, s: super::Style| {
986 set_in(&mut a.props, Prop::HeaderStyle(s.0));
987 if !s.1.is_empty() {
988 let typed = s.1.resolved();
989 let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
990 set_in(&mut a.props, Prop::HeaderClassList(list));
991 }
992 });
993 self
994 }
995
996 pub fn header_style_with(
1003 self,
1004 f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1005 ) -> Self {
1006 let list = move || {
1007 let style = f(super::StyleRefinement::default()).resolved();
1008 (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1009 };
1010 self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1011 Prop::HeaderClassList(list)
1012 })
1013 }
1014
1015 pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1017 self.bind_prop(title, |t| {
1018 Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1019 })
1020 }
1021
1022 pub fn header_right_system_item(
1026 self,
1027 item: impl IntoReactive<crate::HeaderSystemItem>,
1028 ) -> Self {
1029 self.bind_prop(item, |item| {
1030 Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1031 })
1032 }
1033
1034 pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1038 self.bind_prop(item, |item| {
1039 Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1040 })
1041 }
1042
1043 pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1047 self.bind_prop(name, |n| {
1048 Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1049 })
1050 }
1051
1052 pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1056 self.bind_prop(name, |n| {
1057 Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1058 })
1059 }
1060
1061 pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1063 self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1064 }
1065
1066 pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1069 self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1070 }
1071
1072 pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1076 self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1077 }
1078
1079 pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1081 self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1082 }
1083
1084 pub fn transition_shader(
1088 self,
1089 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1090 ) -> Self {
1091 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1092 Prop::TransitionShader(s.map(Into::into))
1093 })
1094 }
1095
1096 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1100 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1101 }
1102
1103 pub fn header_left(self, item: impl IntoElement) -> Self {
1105 self.header_item(HeaderSlot::Left, "header-left", item)
1106 }
1107
1108 pub fn header_right(self, item: impl IntoElement) -> Self {
1110 self.header_item(HeaderSlot::Right, "header-right", item)
1111 }
1112
1113 pub fn header_title(self, item: impl IntoElement) -> Self {
1115 self.header_item(HeaderSlot::Title, "header-title", item)
1116 }
1117
1118 pub fn header(self, item: impl IntoElement) -> Self {
1122 self.header_item(HeaderSlot::Header, "header", item)
1123 }
1124
1125 pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1128 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1129 }
1130
1131 pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1134 self.listen(
1135 EventKind::BackRequest,
1136 listener.into_listener(),
1137 events::unit,
1138 )
1139 }
1140}
1141
1142impl Overlay {
1143 pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1147 let anchor = *anchor;
1148 self.bind_prop(
1149 move || match anchor.node() {
1150 Some(id) => OverlayAnchor::Node(id),
1151 None => OverlayAnchor::None,
1152 },
1153 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1154 )
1155 }
1156
1157 pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1163 let cover = *cover;
1164 self.bind_prop(
1165 move || if shown() { cover.node() } else { None },
1166 |id| Prop::Overlay(OverlayProp::Cover(id)),
1167 )
1168 }
1169
1170 pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1174 let (anchor, edges) = (*anchor, *edges);
1175 self.bind_prop(
1176 move || match (anchor.node(), edges.node()) {
1177 (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1178 (Some(id), None) => OverlayAnchor::Node(id),
1179 _ => OverlayAnchor::None,
1180 },
1181 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1182 )
1183 }
1184
1185 pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1191 let anchor = *anchor;
1192 self.bind_prop(
1193 move || match anchor.node() {
1194 Some(id) => OverlayAnchor::Content(id),
1195 None => OverlayAnchor::None,
1196 },
1197 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1198 )
1199 }
1200
1201 pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1204 self.bind_prop(point, |p| {
1205 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1206 })
1207 }
1208
1209 pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1213 self.bind_prop(bounds, |b| {
1214 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1215 })
1216 }
1217
1218 pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1220 self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1221 }
1222
1223 pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1225 self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1226 }
1227
1228 pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1230 self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1231 }
1232
1233 pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1235 self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1236 }
1237
1238 pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1242 self.listen(
1243 EventKind::PressOutside,
1244 listener.into_listener(),
1245 events::page_point,
1246 )
1247 }
1248
1249 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1253 self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1254 }
1255
1256 pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1265 self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1266 }
1267
1268 pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1273 self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1274 }
1275
1276 pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1280 self.listen(
1281 EventKind::Show,
1282 listener.into_listener(),
1283 events::hint_reason,
1284 )
1285 }
1286
1287 pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1291 self.listen(
1292 EventKind::Dismiss,
1293 listener.into_listener(),
1294 events::hint_reason,
1295 )
1296 }
1297
1298 pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1301 self.listen(
1302 EventKind::Position,
1303 listener.into_listener(),
1304 events::overlay_position,
1305 )
1306 }
1307}
1308
1309impl Modal {
1310 pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1312 self.bind_prop(animation, |animation: ModalAnimation| {
1313 Prop::Modal(ModalProp::Animation(animation))
1314 })
1315 }
1316
1317 pub fn transition_shader(
1321 self,
1322 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1323 ) -> Self {
1324 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1325 Prop::TransitionShader(s.map(Into::into))
1326 })
1327 }
1328
1329 pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1331 self.bind_prop(presentation, |presentation: ModalPresentation| {
1332 Prop::Modal(ModalProp::Presentation(presentation))
1333 })
1334 }
1335
1336 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1339 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1340 }
1341
1342 pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1344 self.bind_prop(translucent, |translucent: bool| {
1345 Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1346 })
1347 }
1348
1349 pub fn supported_orientations(
1352 self,
1353 orientations: impl IntoIterator<Item = Orientation>,
1354 ) -> Self {
1355 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1356 self.set(Prop::Modal(ModalProp::Orientations(bits)))
1357 }
1358
1359 pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1362 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1363 }
1364
1365 pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1369 self.bind_prop(close, |v: bool| {
1370 Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1371 })
1372 }
1373
1374 pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1376 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1377 }
1378
1379 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1383 self.listen(
1384 EventKind::RequestClose,
1385 listener.into_listener(),
1386 events::unit,
1387 )
1388 }
1389
1390 pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1392 self.listen(EventKind::Show, listener.into_listener(), events::unit)
1393 }
1394
1395 pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1397 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1398 }
1399}
1400
1401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1403pub enum Orientation {
1404 Portrait,
1406 PortraitUpsideDown,
1408 Landscape,
1410 LandscapeLeft,
1412 LandscapeRight,
1414}
1415
1416impl Orientation {
1417 fn bits(self) -> u8 {
1418 use crate::ModalConfig as M;
1419 match self {
1420 Orientation::Portrait => M::PORTRAIT,
1421 Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1422 Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1423 Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1424 Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1425 }
1426 }
1427}
1428
1429impl WebView {
1430 pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1433 let base_url: Option<Arc<str>> = base_url.map(Into::into);
1434 self.bind_prop(html, move |html: String| {
1435 Prop::Native(NativeProp::Source(WebSource::Html {
1436 html: html.into(),
1437 base_url: base_url.clone(),
1438 }))
1439 })
1440 }
1441
1442 pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1444 self.bind_prop(script, |script: String| {
1445 Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1446 })
1447 }
1448
1449 pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1451 self.bind_prop(script, |script: String| {
1452 Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1453 })
1454 }
1455
1456 pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1458 self.bind_prop(agent, |agent: String| {
1459 Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1460 })
1461 }
1462
1463 pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1465 self.bind_prop(enabled, |enabled: bool| {
1466 Prop::Native(NativeProp::Scrollable(enabled))
1467 })
1468 }
1469
1470 pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1472 self.bind_prop(enabled, |enabled: bool| {
1473 Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1474 })
1475 }
1476
1477 pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1479 self.bind_prop(enabled, |enabled: bool| {
1480 Prop::Native(NativeProp::BackForwardGestures(enabled))
1481 })
1482 }
1483
1484 pub fn incognito(self, incognito: bool) -> Self {
1489 self.set(Prop::Native(NativeProp::Incognito(incognito)))
1490 }
1491
1492 pub fn url_scheme(
1507 self,
1508 scheme: &str,
1509 handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1510 ) -> Self {
1511 let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1512 Ok(scheme) => scheme,
1513 Err(e) => {
1514 log::warn!(target: "js", "web view: {e}");
1515 return self;
1516 }
1517 };
1518 let mut schemes = self
1519 .0
1520 .attrs
1521 .props
1522 .iter()
1523 .find_map(|p| match p {
1524 Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1525 _ => None,
1526 })
1527 .unwrap_or_default();
1528 schemes.retain(|s| s.scheme() != scheme.scheme());
1529 schemes.push(scheme);
1530 self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1531 }
1532
1533 pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1535 self.listen(
1536 EventKind::LoadStart,
1537 listener.into_listener(),
1538 events::navigation,
1539 )
1540 }
1541
1542 pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1544 self.listen(
1545 EventKind::Load,
1546 listener.into_listener(),
1547 events::navigation,
1548 )
1549 }
1550
1551 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1553 self.listen(EventKind::Error, listener.into_listener(), events::message)
1554 }
1555
1556 pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1562 self.listen(
1563 EventKind::Error,
1564 listener.into_listener(),
1565 events::unavailable,
1566 )
1567 }
1568
1569 pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1571 self.listen(EventKind::Message, listener.into_listener(), events::data)
1572 }
1573
1574 pub fn on_navigation_state_change<M>(
1576 self,
1577 listener: impl IntoListener<WebNavigation, M>,
1578 ) -> Self {
1579 self.listen(
1580 EventKind::NavigationStateChange,
1581 listener.into_listener(),
1582 events::navigation,
1583 )
1584 }
1585}
1586
1587impl Video {
1588 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1590 self.bind_prop(paused, |paused: bool| {
1591 Prop::Native(NativeProp::Paused(paused))
1592 })
1593 }
1594
1595 pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1597 self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1598 }
1599
1600 pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1602 self.bind_prop(volume, |volume: f32| {
1603 Prop::Native(NativeProp::Volume(volume))
1604 })
1605 }
1606
1607 pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1609 self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1610 }
1611
1612 pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1614 self.bind_prop(repeat, |repeat: bool| {
1615 Prop::Native(NativeProp::Repeat(repeat))
1616 })
1617 }
1618
1619 pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1621 self.bind_prop(controls, |controls: bool| {
1622 Prop::Native(NativeProp::Controls(controls))
1623 })
1624 }
1625
1626 pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1628 self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1629 }
1630
1631 pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1634 self.bind_prop(session, |session: AudioSession| {
1635 Prop::Native(NativeProp::AudioSession(session))
1636 })
1637 }
1638
1639 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1641 self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1642 }
1643
1644 pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1646 self.listen(EventKind::Load, listener.into_listener(), events::video)
1647 }
1648
1649 pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1651 self.listen(
1652 EventKind::Progress,
1653 listener.into_listener(),
1654 events::progress,
1655 )
1656 }
1657
1658 pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1660 self.listen(EventKind::End, listener.into_listener(), events::unit)
1661 }
1662
1663 pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1665 self.listen(
1666 EventKind::Buffer,
1667 listener.into_listener(),
1668 events::buffering,
1669 )
1670 }
1671
1672 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1674 self.listen(EventKind::Error, listener.into_listener(), events::message)
1675 }
1676}
1677
1678impl NativeView {
1679 pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1682 let name: Arc<str> = name.into();
1683 self.bind_prop(value, move |value| {
1684 Prop::ComponentProp(name.clone(), Some(value))
1685 })
1686 }
1687
1688 pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1694 if let Some(node) = value.animated_node().live() {
1695 set(
1696 &mut self.0,
1697 Prop::ComponentPropBinding(name.into(), Some(node.id())),
1698 );
1699 self.0.attrs.bound.push(node);
1700 }
1701 self
1702 }
1703
1704 pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1706 self.listen(
1707 EventKind::NativeEvent,
1708 listener.into_listener(),
1709 events::native,
1710 )
1711 }
1712}
1713
1714#[derive(Debug, Clone, PartialEq)]
1717pub struct CanvasArg(pub(crate) CanvasArgKind);
1718
1719#[derive(Debug, Clone, PartialEq)]
1720pub(crate) enum CanvasArgKind {
1721 Const(f32),
1722 Node(super::LiveNode),
1723}
1724
1725impl From<f32> for CanvasArg {
1726 fn from(n: f32) -> Self {
1727 Self(CanvasArgKind::Const(n))
1728 }
1729}
1730
1731impl From<Points> for CanvasArg {
1733 fn from(n: Points) -> Self {
1734 Self(CanvasArgKind::Const(n.0))
1735 }
1736}
1737
1738impl From<Radians> for CanvasArg {
1740 fn from(n: Radians) -> Self {
1741 Self(CanvasArgKind::Const(n.0))
1742 }
1743}
1744
1745impl<A: super::Animated> From<&A> for CanvasArg {
1747 fn from(a: &A) -> Self {
1748 Self(match a.animated_node().live() {
1749 Some(node) => CanvasArgKind::Node(node),
1750 None => CanvasArgKind::Const(0.0),
1751 })
1752 }
1753}
1754
1755#[derive(Debug, Clone, PartialEq)]
1760pub struct CanvasPaint(CanvasPaintKind);
1761
1762#[derive(Debug, Clone, PartialEq)]
1763enum CanvasPaintKind {
1764 Color(Color),
1765 Gradient(Arc<CanvasGradient>),
1766 Node(super::LiveNode),
1767}
1768
1769impl From<Color> for CanvasPaint {
1770 fn from(color: Color) -> Self {
1771 Self(CanvasPaintKind::Color(color))
1772 }
1773}
1774
1775impl From<Hsla> for CanvasPaint {
1776 fn from(color: Hsla) -> Self {
1777 Color::from(color).into()
1778 }
1779}
1780
1781impl From<Rgba> for CanvasPaint {
1782 fn from(color: Rgba) -> Self {
1783 Color::from(color).into()
1784 }
1785}
1786
1787impl From<CanvasGradient> for CanvasPaint {
1788 fn from(gradient: CanvasGradient) -> Self {
1789 Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
1790 }
1791}
1792
1793impl From<Arc<CanvasGradient>> for CanvasPaint {
1794 fn from(gradient: Arc<CanvasGradient>) -> Self {
1795 Self(CanvasPaintKind::Gradient(gradient))
1796 }
1797}
1798
1799impl<A: super::Animated> From<&A> for CanvasPaint {
1801 fn from(a: &A) -> Self {
1802 Self(match a.animated_node().live() {
1803 Some(node) => CanvasPaintKind::Node(node),
1804 None => CanvasPaintKind::Color(Color::TRANSPARENT),
1805 })
1806 }
1807}
1808
1809#[derive(Debug, Clone, Default)]
1817pub struct Painter {
1818 drawing: Drawing,
1819 nodes: Vec<super::LiveNode>,
1821}
1822
1823impl Painter {
1824 pub fn new() -> Self {
1826 Self::default()
1827 }
1828
1829 pub fn finish(self) -> Drawing {
1831 self.drawing
1832 }
1833
1834 pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
1838 match value.into().0 {
1839 CanvasArgKind::Const(n) => Num::Const(n),
1840 CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
1841 }
1842 }
1843
1844 pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
1847 match paint.into().0 {
1848 CanvasPaintKind::Color(color) => Paint::Color(color),
1849 CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
1850 CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
1851 }
1852 }
1853
1854 fn slot(&mut self, node: super::LiveNode) -> u16 {
1855 let slot = self.drawing.slot(node.id());
1856 self.nodes.push(node);
1857 slot
1858 }
1859
1860 pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
1863 self.drawing.nodes.push(node);
1864 self
1865 }
1866
1867 pub fn op(mut self, op: CanvasOp) -> Self {
1870 self.drawing.ops.push(op);
1871 self
1872 }
1873
1874 fn path(self, op: PathOp) -> Self {
1875 self.op(CanvasOp::Path(op))
1876 }
1877
1878 pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
1885 crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
1886 }
1887
1888 pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
1892 crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
1893 }
1894
1895 pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
1900 crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
1901 }
1902
1903 pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
1907 crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
1908 }
1909
1910 pub fn save(self) -> Self {
1912 self.op(CanvasOp::Save)
1913 }
1914
1915 pub fn restore(self) -> Self {
1917 self.op(CanvasOp::Restore)
1918 }
1919
1920 pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1922 let (x, y) = (self.num(x), self.num(y));
1923 self.op(CanvasOp::Translate(x, y))
1924 }
1925
1926 pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1928 let (x, y) = (self.num(x), self.num(y));
1929 self.op(CanvasOp::Scale(x, y))
1930 }
1931
1932 pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
1935 let a = self.num(angle);
1936 self.op(CanvasOp::Rotate(a))
1937 }
1938
1939 pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1942 let m = m.map(|n| self.num(n));
1943 self.op(CanvasOp::Transform(m))
1944 }
1945
1946 pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1949 let m = m.map(|n| self.num(n));
1950 self.op(CanvasOp::SetTransform(m))
1951 }
1952
1953 pub fn reset_transform(self) -> Self {
1955 self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
1956 }
1957
1958 pub fn begin_path(self) -> Self {
1960 self.op(CanvasOp::BeginPath)
1961 }
1962
1963 pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1965 let (x, y) = (self.num(x), self.num(y));
1966 self.path(PathOp::MoveTo(x, y))
1967 }
1968
1969 pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1971 let (x, y) = (self.num(x), self.num(y));
1972 self.path(PathOp::LineTo(x, y))
1973 }
1974
1975 pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
1977 let c = |v: Points| Num::Const(v.0);
1978 self.path(PathOp::QuadTo([
1979 c(control.x),
1980 c(control.y),
1981 c(to.x),
1982 c(to.y),
1983 ]))
1984 }
1985
1986 pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
1988 let c = |v: Points| Num::Const(v.0);
1989 self.path(PathOp::CubicTo([
1990 c(c1.x),
1991 c(c1.y),
1992 c(c2.x),
1993 c(c2.y),
1994 c(to.x),
1995 c(to.y),
1996 ]))
1997 }
1998
1999 pub fn arc(
2002 self,
2003 x: impl Into<CanvasArg>,
2004 y: impl Into<CanvasArg>,
2005 radius: impl Into<CanvasArg>,
2006 start: impl Into<CanvasArg>,
2007 end: impl Into<CanvasArg>,
2008 ) -> Self {
2009 self.arc_in(x, y, radius, start, end, false)
2010 }
2011
2012 pub fn arc_counterclockwise(
2014 self,
2015 x: impl Into<CanvasArg>,
2016 y: impl Into<CanvasArg>,
2017 radius: impl Into<CanvasArg>,
2018 start: impl Into<CanvasArg>,
2019 end: impl Into<CanvasArg>,
2020 ) -> Self {
2021 self.arc_in(x, y, radius, start, end, true)
2022 }
2023
2024 fn arc_in(
2025 mut self,
2026 x: impl Into<CanvasArg>,
2027 y: impl Into<CanvasArg>,
2028 radius: impl Into<CanvasArg>,
2029 start: impl Into<CanvasArg>,
2030 end: impl Into<CanvasArg>,
2031 ccw: bool,
2032 ) -> Self {
2033 let (x, y, radius, start, end) = (
2034 self.num(x),
2035 self.num(y),
2036 self.num(radius),
2037 self.num(start),
2038 self.num(end),
2039 );
2040 self.path(PathOp::Arc {
2041 x,
2042 y,
2043 radius,
2044 start,
2045 end,
2046 ccw,
2047 })
2048 }
2049
2050 pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2053 let c = |v: Points| Num::Const(v.0);
2054 self.path(PathOp::ArcTo([
2055 c(p1.x),
2056 c(p1.y),
2057 c(p2.x),
2058 c(p2.y),
2059 c(radius),
2060 ]))
2061 }
2062
2063 pub fn ellipse(
2067 self,
2068 center: Point<Points>,
2069 radii: Size<Points>,
2070 rotation: Radians,
2071 start: Radians,
2072 end: Radians,
2073 counterclockwise: bool,
2074 ) -> Self {
2075 let c = Num::Const;
2076 self.path(PathOp::Ellipse {
2077 geometry: [
2078 c(center.x.0),
2079 c(center.y.0),
2080 c(radii.width.0),
2081 c(radii.height.0),
2082 c(rotation.0),
2083 ],
2084 start: c(start.0),
2085 end: c(end.0),
2086 ccw: counterclockwise,
2087 })
2088 }
2089
2090 pub fn rect(self, rect: Bounds<Points>) -> Self {
2092 self.path(PathOp::Rect(nums(rect)))
2093 }
2094
2095 pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2097 self.round_rect_corners(rect, Corners::all(radius))
2098 }
2099
2100 pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2102 let c = |v: Points| Num::Const(v.0);
2103 self.path(PathOp::RoundRect(
2104 nums(rect),
2105 [
2106 c(radii.top_left),
2107 c(radii.top_right),
2108 c(radii.bottom_right),
2109 c(radii.bottom_left),
2110 ],
2111 ))
2112 }
2113
2114 pub fn close_path(self) -> Self {
2116 self.path(PathOp::Close)
2117 }
2118
2119 pub fn fill(self) -> Self {
2121 self.fill_with(FillRule::NonZero)
2122 }
2123
2124 pub fn fill_with(self, rule: FillRule) -> Self {
2126 self.op(CanvasOp::Fill(None, rule))
2127 }
2128
2129 pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2132 self.op(CanvasOp::Fill(Some(path.clone()), rule))
2133 }
2134
2135 pub fn fill_svg(self, data: &str) -> Self {
2138 self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2139 }
2140
2141 pub fn stroke(self) -> Self {
2143 self.op(CanvasOp::Stroke(None))
2144 }
2145
2146 pub fn stroke_path(self, path: &Path) -> Self {
2148 self.op(CanvasOp::Stroke(Some(path.clone())))
2149 }
2150
2151 pub fn stroke_svg(self, data: &str) -> Self {
2153 self.stroke_path(&crate::canvas::svg_path(data))
2154 }
2155
2156 pub fn clip(self) -> Self {
2158 self.clip_with(FillRule::NonZero)
2159 }
2160
2161 pub fn clip_with(self, rule: FillRule) -> Self {
2163 self.op(CanvasOp::Clip(None, rule))
2164 }
2165
2166 pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2168 self.op(CanvasOp::Clip(Some(path.clone()), rule))
2169 }
2170
2171 pub fn fill_rect(
2173 mut self,
2174 x: impl Into<CanvasArg>,
2175 y: impl Into<CanvasArg>,
2176 w: impl Into<CanvasArg>,
2177 h: impl Into<CanvasArg>,
2178 ) -> Self {
2179 let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2180 self.op(CanvasOp::FillRect([x, y, w, h]))
2181 }
2182
2183 pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2185 self.op(CanvasOp::StrokeRect(nums(rect)))
2186 }
2187
2188 pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2190 self.op(CanvasOp::ClearRect(nums(rect)))
2191 }
2192
2193 pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2195 self.fill_style(color.into())
2196 }
2197
2198 pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2200 self.stroke_style(color.into())
2201 }
2202
2203 pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2206 let paint = self.paint(paint);
2207 self.op(CanvasOp::FillStyle(paint))
2208 }
2209
2210 pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2216 self.view_paint(
2217 ViewPaint::Fill(initial),
2218 CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2219 )
2220 }
2221
2222 pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2225 self.view_paint(
2226 ViewPaint::Stroke(initial),
2227 CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2228 )
2229 }
2230
2231 pub fn line_width_from_view(self) -> Self {
2234 self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2235 }
2236
2237 pub fn line_dash_from_view(self) -> Self {
2240 self.view_paint(
2241 ViewPaint::StrokeDasharray,
2242 CanvasOp::LineDash(Arc::from([])),
2243 )
2244 }
2245
2246 pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2255 self.view_paint(
2256 ViewPaint::Background {
2257 area,
2258 rule: FillRule::NonZero,
2259 },
2260 CanvasOp::Fill(None, FillRule::NonZero),
2261 )
2262 }
2263
2264 fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2265 let at = self.drawing.ops.len() as u32;
2266 self.drawing.view_paints.push((at, view));
2267 self.op(placeholder)
2268 }
2269
2270 pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2272 let paint = self.paint(paint);
2273 self.op(CanvasOp::StrokeStyle(paint))
2274 }
2275
2276 pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2278 let w = self.num(width);
2279 self.op(CanvasOp::LineWidth(w))
2280 }
2281
2282 pub fn line_cap(self, cap: LineCap) -> Self {
2284 self.op(CanvasOp::LineCap(cap))
2285 }
2286
2287 pub fn line_join(self, join: LineJoin) -> Self {
2289 self.op(CanvasOp::LineJoin(join))
2290 }
2291
2292 pub fn miter_limit(self, limit: f32) -> Self {
2295 self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2296 }
2297
2298 pub fn line_dash(self, segments: &[Points]) -> Self {
2300 self.op(CanvasOp::LineDash(segments.into()))
2301 }
2302
2303 pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2306 let o = self.num(offset);
2307 self.op(CanvasOp::LineDashOffset(o))
2308 }
2309
2310 pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2312 let a = self.num(alpha);
2313 self.op(CanvasOp::GlobalAlpha(a))
2314 }
2315
2316 pub fn composite(self, composite: Composite) -> Self {
2318 self.op(CanvasOp::Composite(composite))
2319 }
2320
2321 pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2323 self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2324 .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2325 .op(CanvasOp::ShadowOffset(offset))
2326 }
2327
2328 pub fn font(self, font: &str) -> Self {
2331 match CanvasFont::parse(font) {
2332 Some(font) => self.op(CanvasOp::Font(font)),
2333 None => self,
2334 }
2335 }
2336
2337 pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2341 self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2342 numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2343 )))
2344 }
2345
2346 pub fn text_align(self, align: CanvasTextAlign) -> Self {
2348 self.op(CanvasOp::TextAlign(align))
2349 }
2350
2351 pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2353 self.op(CanvasOp::TextBaseline(baseline))
2354 }
2355
2356 pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2358 self.text(text, x, y, None, false)
2359 }
2360
2361 pub fn fill_text_max_width(
2363 self,
2364 text: &str,
2365 x: impl Into<CanvasArg>,
2366 y: impl Into<CanvasArg>,
2367 max_width: Points,
2368 ) -> Self {
2369 self.text(text, x, y, Some(max_width), false)
2370 }
2371
2372 pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2374 self.text(text, x, y, None, true)
2375 }
2376
2377 pub fn stroke_text_max_width(
2380 self,
2381 text: &str,
2382 x: impl Into<CanvasArg>,
2383 y: impl Into<CanvasArg>,
2384 max_width: Points,
2385 ) -> Self {
2386 self.text(text, x, y, Some(max_width), true)
2387 }
2388
2389 fn text(
2390 mut self,
2391 text: &str,
2392 x: impl Into<CanvasArg>,
2393 y: impl Into<CanvasArg>,
2394 max_width: Option<Points>,
2395 stroke: bool,
2396 ) -> Self {
2397 let (text, x, y) = (text.into(), self.num(x), self.num(y));
2398 self.op(if stroke {
2399 CanvasOp::StrokeText {
2400 text,
2401 x,
2402 y,
2403 max_width,
2404 }
2405 } else {
2406 CanvasOp::FillText {
2407 text,
2408 x,
2409 y,
2410 max_width,
2411 }
2412 })
2413 }
2414
2415 pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2417 self.draw_image_part(uri, None, dest)
2418 }
2419
2420 pub fn draw_image_part(
2423 self,
2424 uri: &str,
2425 source: Option<Bounds<ScaledPixels>>,
2426 dest: Bounds<Points>,
2427 ) -> Self {
2428 self.op(CanvasOp::DrawImage {
2429 image: CanvasImage { uri: uri.into() },
2430 source,
2431 dest: nums(dest),
2432 })
2433 }
2434}
2435
2436fn nums(rect: Bounds<Points>) -> [Num; 4] {
2438 [
2439 rect.origin.x,
2440 rect.origin.y,
2441 rect.size.width,
2442 rect.size.height,
2443 ]
2444 .map(|v| Num::Const(v.0))
2445}
2446
2447impl From<Drawing> for Painter {
2448 fn from(drawing: Drawing) -> Self {
2449 Self {
2450 drawing,
2451 nodes: Vec::new(),
2452 }
2453 }
2454}
2455
2456crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2457
2458impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2460 fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2461 super::Reactive::Static(Some(self))
2462 }
2463}
2464
2465impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2467 fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2468 super::Reactive::Static(Some(self))
2469 }
2470}
2471
2472#[cfg(test)]
2473mod tests {
2474 use super::*;
2475 use crate::{
2476 element::{
2477 AnimatedValue,
2478 reactive::{Runtime, create_root, signal},
2479 },
2480 shader::{ShaderUniforms, UniformValue},
2481 };
2482
2483 fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2484 attrs
2485 .props
2486 .iter()
2487 .find_map(|p| match p {
2488 Prop::Uniforms(u) => Some(u.clone()),
2489 _ => None,
2490 })
2491 .unwrap_or_default()
2492 }
2493
2494 fn released(executor: &super::super::task::Executor) -> usize {
2496 executor
2497 .take_actions()
2498 .into_iter()
2499 .filter(|a| {
2500 matches!(
2501 a,
2502 super::super::task::Action::Animation(
2503 crate::animation::AnimationOp::Release { .. }
2504 )
2505 )
2506 })
2507 .count()
2508 }
2509
2510 fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2511 u.0.iter()
2512 .find(|(n, _)| &**n == name)
2513 .map(|(_, v)| v.clone())
2514 }
2515
2516 #[test]
2517 fn screens_and_modals_take_a_transition_shader() {
2518 let runtime = Runtime::default();
2519 let _entered = runtime.enter();
2520 let source = "struct Uniforms { edge: f32 }\n\
2521 fn shade(uv: vec2f) -> vec4f {\n \
2522 return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2523 let shader = crate::shader::Shader::compile(source).expect("compiles");
2524 let wipe = crate::shader::TransitionShader::new(shader)
2525 .uniform("edge", 1.0_f32)
2526 .duration(std::time::Duration::from_millis(400));
2527 let expected = crate::shader::NavShaderSpec {
2528 source: source.into(),
2529 uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2530 duration: Some(400.0),
2531 };
2532 let spec = |attrs: &super::super::builder::Attrs| {
2533 attrs.props.iter().find_map(|p| match p {
2534 Prop::TransitionShader(s) => Some(s.clone()),
2535 _ => None,
2536 })
2537 };
2538 let page = screen().transition_shader(wipe.clone()).0;
2539 assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2540 let dialog = modal().transition_shader(wipe.clone()).0;
2541 assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2542 let on = signal(true);
2544 let bound = screen()
2545 .transition_shader(move || on.get().then(|| wipe.clone()))
2546 .0;
2547 assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
2548 on.set(false);
2549 assert_eq!(spec(&bound.resolved_attrs()), Some(None));
2550 }
2551
2552 #[test]
2553 fn uniform_takes_static_bound_and_animated_values() {
2554 let runtime = Runtime::default();
2555 let _entered = runtime.enter();
2556 let executor = std::rc::Rc::new(super::super::task::Executor::default());
2557 let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
2558 let speed = signal(1.0_f32);
2559 let view = shader()
2560 .uniform("center", [0.5_f32, 0.5])
2561 .uniform("wave", &wave)
2562 .uniform("speed", move || speed.get());
2563 let node = view.0;
2564
2565 let set = uniforms(&node.attrs);
2568 assert_eq!(
2569 value(&set, "center"),
2570 Some(UniformValue::List(vec![
2571 UniformValue::Number(0.5),
2572 UniformValue::Number(0.5)
2573 ]))
2574 );
2575 let id = wave.node().live().expect("live").id();
2576 assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
2577 assert_eq!(
2578 node.attrs.bound.len(),
2579 1,
2580 "the element holds the animated node"
2581 );
2582 assert_eq!(
2583 value(&set, "speed"),
2584 None,
2585 "a bound one is applied when resolved"
2586 );
2587
2588 assert_eq!(
2590 value(&uniforms(&node.resolved_attrs()), "speed"),
2591 Some(UniformValue::Number(1.0))
2592 );
2593 speed.set(2.0);
2594 assert_eq!(
2595 value(&uniforms(&node.resolved_attrs()), "speed"),
2596 Some(UniformValue::Number(2.0))
2597 );
2598
2599 value_owner.dispose();
2601 assert_eq!(released(&executor), 0, "the view keeps the animated node");
2602 drop(node);
2603 assert_eq!(released(&executor), 1, "and lets it go with the view");
2604 }
2605
2606 #[test]
2607 fn a_later_uniform_replaces_one_of_the_same_name() {
2608 let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
2609 let set = uniforms(&view.0.attrs);
2610 assert_eq!(set.0.len(), 1);
2611 assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
2612 }
2613
2614 #[test]
2615 fn web_view_url_scheme_builder_collects_schemes() {
2616 let web = web_view_html("<img src=\"a:1\">", None)
2617 .url_scheme("a", |request| request.fail())
2618 .url_scheme("b", |request| request.fail())
2619 .url_scheme("A", |request| request.fail())
2621 .url_scheme("https", |request| request.fail());
2623 let schemes: Vec<String> = web
2624 .0
2625 .attrs
2626 .props
2627 .iter()
2628 .find_map(|p| match p {
2629 Prop::Native(NativeProp::UrlSchemes(list)) => {
2630 Some(list.iter().map(|s| s.scheme().to_owned()).collect())
2631 }
2632 _ => None,
2633 })
2634 .unwrap();
2635 assert_eq!(schemes, ["b", "a"]);
2636 }
2637}