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, SheetDetent, Size, StatusBarSetting, SubmitBehavior,
23 Tag, 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!(crate::HeaderItem: crate::HeaderItem);
67crate::static_reactive!(Vec<crate::HeaderItem>: Vec<crate::HeaderItem>);
68crate::static_reactive!(super::header::HeaderItem: super::header::HeaderItem);
69crate::static_reactive!(Vec<super::header::HeaderItem>: Vec<super::header::HeaderItem>);
70crate::static_reactive!(Vec<super::desktop::MenuItem>: Vec<super::desktop::MenuItem>);
71crate::static_reactive!(SheetDetent: SheetDetent);
72crate::static_reactive!(Vec<SheetDetent>: Vec<SheetDetent>);
73crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
74crate::static_reactive!(KeyboardType: KeyboardType);
75crate::static_reactive!(ModalAnimation: ModalAnimation);
76crate::static_reactive!(ModalPresentation: ModalPresentation);
77crate::static_reactive!(ResizeMode: ResizeMode);
78crate::static_reactive!(ReturnKeyType: ReturnKeyType);
79crate::static_reactive!(SubmitBehavior: SubmitBehavior);
80crate::static_reactive!(PasteBehavior: PasteBehavior);
81crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
82crate::static_reactive!(JsonValue: JsonValue);
83crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
84crate::static_reactive!(Placement: Placement);
85crate::static_reactive!(Align: Align);
86
87pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
89 match props.iter_mut().find(|p| same_kind(p, &prop)) {
90 Some(p) => *p = prop,
91 None => props.push(prop),
92 }
93}
94
95pub(crate) fn bind_prop<T: 'static>(
98 node: &mut ElNode,
99 value: impl IntoReactive<T>,
100 prop: impl Fn(T) -> Prop + 'static,
101) {
102 node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
103}
104
105fn listen<T: ?Sized + ToOwned + 'static>(
107 node: &mut ElNode,
108 kind: EventKind,
109 listener: Listener<T>,
110 decode: events::Decode<T>,
111) {
112 node.handlers.push((kind, events::typed(listener, decode)));
113}
114
115macro_rules! host_element {
116 ($(#[$doc:meta])* $name:ident) => {
117 $(#[$doc])*
118 #[derive(Clone)]
119 pub struct $name(ElNode);
120
121 impl Element for $name {
122 fn node(&mut self) -> &mut ElNode {
123 &mut self.0
124 }
125 }
126
127 impl IntoElement for $name {
128 fn into_element(self) -> AnyElement {
129 AnyElement(self.0)
130 }
131 }
132
133 impl Accessible for $name {}
134 impl Interactive for $name {}
135
136 impl super::builder::IntoTooltip for $name {
137 fn apply_tooltip(self, node: &mut ElNode) {
138 self.into_element().apply_tooltip(node);
139 }
140 }
141
142 #[allow(dead_code)]
144 impl $name {
145 fn set(mut self, prop: Prop) -> Self {
146 set(&mut self.0, prop);
147 self
148 }
149
150 fn bind_prop<T: 'static>(
151 mut self,
152 value: impl IntoReactive<T>,
153 prop: impl Fn(T) -> Prop + 'static,
154 ) -> Self {
155 bind_prop(&mut self.0, value, prop);
156 self
157 }
158
159 fn listen<T: ?Sized + ToOwned + 'static>(
160 mut self,
161 kind: EventKind,
162 listener: Listener<T>,
163 decode: events::Decode<T>,
164 ) -> Self {
165 listen(&mut self.0, kind, listener, decode);
166 self
167 }
168 }
169 };
170}
171
172host_element! {
173 Input
176}
177
178host_element! {
179 Scroll
182}
183
184host_element! {
185 Stack
191}
192
193host_element! {
194 Screen
198}
199
200host_element! {
201 Modal
205}
206
207host_element! {
208 InputAccessoryView
212}
213
214host_element! {
215 CanvasView
217}
218
219host_element! {
220 Svg
222}
223
224host_element! {
225 ShaderView
228}
229
230host_element! {
231 WebView
233}
234
235host_element! {
236 Video
238}
239
240host_element! {
241 NativeView
244}
245
246host_element! {
247 Overlay
252}
253
254impl ParentElement for Overlay {}
255impl ParentElement for ShaderView {}
256impl ParentElement for Scroll {}
257impl ParentElement for Stack {}
258impl ParentElement for Screen {}
259impl ParentElement for Modal {}
260
261fn has_input_accessory() -> bool {
264 super::ambient::try_os().unwrap_or_default() == crate::platform::Os::Ios
265}
266
267impl ParentElement for InputAccessoryView {
268 fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
269 if has_input_accessory() {
270 child.__push_into(&mut self.0.children);
271 }
272 self
273 }
274
275 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
276 if has_input_accessory() {
277 self.0
278 .children
279 .extend(children.into_iter().map(|c| c.into_element().0));
280 }
281 self
282 }
283}
284
285pub fn overlay() -> Overlay {
293 Overlay(ElNode::new(Tag::Overlay))
294}
295
296pub fn input() -> Input {
298 Input(ElNode::new(Tag::Input))
299}
300
301pub fn scroll() -> Scroll {
303 Scroll(ElNode::new(Tag::Scroll))
304}
305
306#[doc(hidden)]
312pub fn stack() -> Stack {
313 Stack(ElNode::new(Tag::Stack))
314}
315
316#[doc(hidden)]
321pub fn screen() -> Screen {
322 let mut node = ElNode::new(Tag::Screen);
323 node.handlers.push((EventKind::Insets, Listener::noop()));
325 Screen(node)
326}
327
328#[doc(hidden)]
333pub fn modal() -> Modal {
334 let mut node = ElNode::new(Tag::Modal);
335 node.handlers.push((EventKind::Insets, Listener::noop()));
337 Modal(node)
338}
339
340pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
346 let supported = has_input_accessory();
347 let tag = if supported {
348 Tag::InputAccessory
349 } else {
350 Tag::View
351 };
352 let mut node = ElNode::new(tag);
353 if supported {
354 set(&mut node, Prop::NativeId(Some(native_id.into())));
355 } else {
356 node.style.value(
357 crate::StyleKey::Display,
358 crate::PropertyValue::Display(taffy::Display::None),
359 );
360 }
361 InputAccessoryView(node)
362}
363
364pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
369 let mut node = ElNode::new(Tag::Canvas);
370 node.bind_attr(painter, |attrs, painter: Painter| {
371 let r = attrs.rare_mut();
372 r.drawing = Some(Arc::new(painter.drawing));
373 r.bound = painter.nodes;
374 });
375 CanvasView(node)
376}
377
378crate::static_reactive!(Painter: Painter, Drawing);
379
380pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
400 #[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
401 {
402 let mut node = ElNode::new(Tag::Canvas);
403 let shown = svg_drawing(src);
404 node.bind_attr(
405 move || shown.get(),
406 |attrs, drawing: Option<Arc<crate::canvas::Drawing>>| {
407 if drawing.is_some() || attrs.rare.is_some() {
408 attrs.rare_mut().drawing = drawing;
409 }
410 },
411 );
412 Svg(node)
413 }
414 #[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
415 {
416 let mut node = ElNode::new(Tag::Image);
417 node.style.value(
418 crate::StyleKey::ObjectFit,
419 crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
420 );
421 node.bind_attr(src, |attrs, src| attrs.rare_mut().src = Some(src));
422 set(
424 &mut node,
425 Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
426 );
427 Svg(node)
428 }
429}
430
431#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
436fn svg_drawing(
437 src: impl IntoReactive<super::ImageSrc>,
438) -> super::reactive::Signal<Option<Arc<Drawing>>> {
439 use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
440 let src = src.into_reactive();
441 let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
442 let lease = stored(crate::image::Lease::none());
443 let task = stored(None::<super::Spawned<()>>);
444 render_effect(move || {
445 let src = match &src {
446 super::Reactive::Static(src) => src.clone(),
447 super::Reactive::Bound(f) => f(),
448 };
449 untracked(|| {
450 drop(task.replace(None));
451 let context = crate::image::loader::context();
452 let source = crate::ImageSource {
453 uri: src.uri.as_str().into(),
454 size: None,
455 scales: crate::ImageScales::NONE,
456 data: None,
457 }
458 .inline();
459 let Some(location) = context.locate(&source) else {
460 log::warn!("svg: unsupported source `{}`", source.uri);
461 shown.set(None);
462 lease.replace(crate::image::Lease::none());
463 return;
464 };
465 if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
466 shown.set(Some(drawing));
467 lease.replace(held);
468 return;
469 }
470 let load = crate::svg::drawings::load(location, context);
471 task.replace(Some(super::spawn(async move {
472 let (drawing, held) = load.await;
473 shown.set(Some(drawing));
474 lease.replace(held);
475 })));
476 });
477 });
478 shown
479}
480
481pub fn shader() -> ShaderView {
485 ShaderView(ElNode::new(Tag::Shader))
486}
487
488pub fn shader_effect() -> ShaderView {
492 ShaderView(ElNode::new(Tag::ShaderEffect))
493}
494
495pub fn shader_transition() -> ShaderView {
500 ShaderView(ElNode::new(Tag::ShaderTransition))
501}
502
503pub fn screen_effect() -> ShaderView {
506 ShaderView(ElNode::new(Tag::ScreenEffect))
507}
508
509pub fn screen_transition() -> ShaderView {
513 ShaderView(ElNode::new(Tag::ScreenTransition))
514}
515
516crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);
517
518pub struct Uniform(UniformSource);
520
521enum UniformSource {
522 Value(super::Reactive<crate::shader::UniformValue>),
523 Animated(super::AnimatedNode),
524}
525
526pub trait IntoUniform {
529 fn into_uniform(self) -> Uniform;
531}
532
533impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
534 fn into_uniform(self) -> Uniform {
535 Uniform(UniformSource::Value(self.into_reactive()))
536 }
537}
538
539impl IntoUniform for &super::AnimatedValue {
540 fn into_uniform(self) -> Uniform {
541 Uniform(UniformSource::Animated(super::Animated::animated_node(
542 self,
543 )))
544 }
545}
546
547impl IntoUniform for &super::AnimatedNode {
548 fn into_uniform(self) -> Uniform {
549 Uniform(UniformSource::Animated(*self))
550 }
551}
552crate::static_reactive!(
553 crate::shader::UniformValue: crate::shader::UniformValue,
554 f32,
555 i32,
556 Color,
557 Hsla,
558 [f32; 2],
559 [f32; 3],
560 [f32; 4],
561 Vec<crate::shader::UniformValue>
562);
563
564impl ShaderView {
565 pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
569 self.bind_prop(shader, |s| Prop::Shader(Some(s)))
570 }
571
572 pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
579 let name: Arc<str> = name.into();
580 let value = match value.into_uniform().0 {
581 UniformSource::Value(value) => value,
582 UniformSource::Animated(node) => {
583 let value = match node.live() {
584 Some(node) => {
585 let id = node.id();
586 self.0.attrs.rare_mut().bound.push(node);
587 crate::shader::UniformValue::Animated(id)
588 }
589 None => crate::shader::UniformValue::Number(0.0),
590 };
591 super::Reactive::Static(value)
592 }
593 };
594 self.0.bind_attr(value, move |attrs, value| {
595 let mut uniforms = attrs
596 .props
597 .iter()
598 .find_map(|p| match p {
599 Prop::Uniforms(u) => Some(u.clone()),
600 _ => None,
601 })
602 .unwrap_or_default();
603 match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
604 Some(entry) => entry.1 = value,
605 None => uniforms.0.push((name.clone(), value)),
606 }
607 set_in(&mut attrs.props, Prop::Uniforms(uniforms));
608 });
609 self
610 }
611
612 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
614 self.bind_prop(paused, Prop::ShaderPaused)
615 }
616
617 pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
620 self.bind_prop(progress, |p| {
621 Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
622 })
623 }
624
625 pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
628 let progress = match value.animated_node().live() {
629 Some(node) => {
630 let id = node.id();
631 self.0.attrs.rare_mut().bound.push(node);
632 crate::shader::ShaderProgress::Animated(id)
633 }
634 None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
635 };
636 self.set(Prop::ShaderProgress(progress))
637 }
638
639 pub fn max_sample_offset(self, offset: Points) -> Self {
642 self.set(Prop::MaxSampleOffset(offset))
643 }
644
645 pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
648 self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
649 }
650
651 pub fn duration(self, duration: std::time::Duration) -> Self {
653 self.set(Prop::TransitionDuration(Some(
654 duration.as_secs_f32() * 1000.0,
655 )))
656 }
657
658 pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
661 self.set(Prop::TransitionFallback(fallback))
662 }
663}
664
665crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);
666
667pub fn web_view(url: impl IntoReactive<String>) -> WebView {
669 WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
670 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
671 })
672}
673
674pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
677 WebView(ElNode::new(Tag::WebView)).html(html, base_url)
678}
679
680pub fn video(url: impl IntoReactive<String>) -> Video {
683 Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
684 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
685 })
686}
687
688pub fn native(name: &str) -> NativeView {
690 NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
691}
692
693impl Input {
694 pub fn value(self, text: impl IntoReactive<String>) -> Self {
697 self.bind_prop(text, |text: String| Prop::Value(text))
698 }
699
700 pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
702 self.bind_prop(text, |text: String| Prop::DefaultValue(text))
703 }
704
705 pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
707 self.bind_prop(text, |text: String| Prop::Placeholder(text))
708 }
709
710 pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
712 self.bind_prop(color, |color: Hsla| {
713 Prop::PlaceholderColor(Some(color.into()))
714 })
715 }
716
717 pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
720 self.bind_prop(color, |color: Hsla| {
721 Prop::SelectionColor(Some(color.into()))
722 })
723 }
724
725 pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
727 self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
728 }
729
730 pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
732 self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
733 }
734
735 pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
737 self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
738 }
739
740 pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
743 self.bind_prop(appearance, |appearance: KeyboardAppearance| {
744 Prop::KeyboardAppearance(appearance)
745 })
746 }
747
748 pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
750 self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
751 }
752
753 pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
755 self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
756 }
757
758 pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
761 self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
762 }
763
764 pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
766 self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
767 }
768
769 pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
771 self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
772 }
773
774 pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
777 self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
778 }
779
780 pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
785 self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
786 }
787
788 pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
790 self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
791 }
792
793 pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
796 self.bind_prop(behavior, |behavior: SubmitBehavior| {
797 Prop::SubmitBehavior(Some(behavior))
798 })
799 }
800
801 pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
804 self.bind_prop(behavior, Prop::PasteBehavior)
805 }
806
807 pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
811 self.listen(EventKind::Paste, listener.into_listener(), events::paste)
812 }
813
814 pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
816 self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
817 }
818
819 pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
821 self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
822 }
823
824 pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
827 self.bind_prop(native_id, |id: String| {
828 Prop::InputAccessoryViewId(Some(id.into()))
829 })
830 }
831
832 pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
837 self.bind_prop(range, |(start, end): (u32, u32)| {
838 Prop::Selection(start, end)
839 })
840 }
841
842 pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
844 self.listen(
845 EventKind::ChangeText,
846 listener.into_listener(),
847 events::text,
848 )
849 }
850
851 pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
853 self.listen(
854 EventKind::SubmitEditing,
855 listener.into_listener(),
856 events::text,
857 )
858 }
859
860 pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
862 self.listen(
863 EventKind::SelectionChange,
864 listener.into_listener(),
865 events::selection,
866 )
867 }
868
869 pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
873 self.listen(
874 EventKind::CaretMove,
875 listener.into_listener(),
876 events::caret,
877 )
878 }
879
880 pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
882 self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
883 }
884
885 pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
889 self.listen(
890 EventKind::CompositionChange,
891 listener.into_listener(),
892 events::composition,
893 )
894 }
895
896 pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
898 self.listen(
899 EventKind::ContentSizeChange,
900 listener.into_listener(),
901 events::size,
902 )
903 }
904}
905
906impl Scroll {
907 pub fn horizontal(self) -> Self {
909 self.set(Prop::Horizontal(true))
910 }
911
912 pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
914 self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
915 }
916
917 pub fn zoom_range(self, min: f32, max: f32) -> Self {
919 self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
920 .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
921 }
922
923 pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
925 self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
926 }
927
928 pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
931 self.bind_prop(bounces, |bounces: bool| {
932 Prop::Scroll(ScrollProp::BouncesZoom(bounces))
933 })
934 }
935
936 pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
938 self.bind_prop(enabled, |enabled: bool| {
939 Prop::Scroll(ScrollProp::Pinch(enabled))
940 })
941 }
942
943 pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
945 self.bind_prop(center, |center: bool| {
946 Prop::Scroll(ScrollProp::CenterContent(center))
947 })
948 }
949}
950
951impl super::Scrollable for Scroll {}
952
953impl Screen {
954 fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
955 let mut node = ElNode::new(Tag::HeaderItem);
956 node.key = Some(key.into());
957 set(&mut node, Prop::HeaderSlot(slot));
958 node.children.push(item.into_element().0);
959 self.0.children.push(node);
960 self
961 }
962
963 pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
965 self.bind_prop(title, |t| {
966 Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
967 })
968 }
969
970 pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
972 self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
973 }
974
975 pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
978 self.bind_prop(hides, |v| {
979 Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
980 })
981 }
982
983 pub fn supported_orientations(
987 self,
988 orientations: impl IntoIterator<Item = Orientation>,
989 ) -> Self {
990 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
991 self.set(Prop::Screen(ScreenProp::Orientations(bits)))
992 }
993
994 pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
996 self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
997 }
998
999 pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
1001 self.bind_prop(transparent, |v| {
1002 Prop::Screen(ScreenProp::HeaderTransparent(v))
1003 })
1004 }
1005
1006 pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
1011 let style = match style.into_reactive() {
1012 super::Reactive::Static(s) if s.1.is_bound() => {
1014 super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
1015 }
1016 style => style,
1017 };
1018 self.0.bind_attr(style, |a, s: super::Style| {
1019 set_in(&mut a.props, Prop::HeaderStyle(s.0));
1020 if !s.1.is_empty() {
1021 let typed = s.1.resolved();
1022 let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
1023 set_in(&mut a.props, Prop::HeaderClassList(list));
1024 }
1025 });
1026 self
1027 }
1028
1029 pub fn header_style_with(
1036 self,
1037 f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1038 ) -> Self {
1039 let list = move || {
1040 let style = f(super::StyleRefinement::default()).resolved();
1041 (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1042 };
1043 self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1044 Prop::HeaderClassList(list)
1045 })
1046 }
1047
1048 pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1050 self.bind_prop(title, |t| {
1051 Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1052 })
1053 }
1054
1055 pub fn header_right_system_item(
1059 self,
1060 item: impl IntoReactive<crate::HeaderSystemItem>,
1061 ) -> Self {
1062 self.bind_prop(item, |item| {
1063 Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1064 })
1065 }
1066
1067 pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1071 self.bind_prop(item, |item| {
1072 Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1073 })
1074 }
1075
1076 pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1080 self.bind_prop(name, |n| {
1081 Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1082 })
1083 }
1084
1085 pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1089 self.bind_prop(name, |n| {
1090 Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1091 })
1092 }
1093
1094 pub fn header_right_items(
1102 self,
1103 items: impl IntoReactive<Vec<super::header::HeaderItem>>,
1104 ) -> Self {
1105 self.bind_prop(items, |items| {
1106 Prop::Screen(ScreenProp::HeaderRightItems(super::header::register(items)))
1107 })
1108 }
1109
1110 pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1112 self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1113 }
1114
1115 pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1118 self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1119 }
1120
1121 pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1125 self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1126 }
1127
1128 pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1130 self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1131 }
1132
1133 pub fn transition_shader(
1137 self,
1138 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1139 ) -> Self {
1140 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1141 Prop::TransitionShader(s.map(Into::into))
1142 })
1143 }
1144
1145 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1149 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1150 }
1151
1152 pub fn header_left(self, item: impl IntoElement) -> Self {
1154 self.header_item(HeaderSlot::Left, "header-left", item)
1155 }
1156
1157 pub fn header_right(self, item: impl IntoElement) -> Self {
1159 self.header_item(HeaderSlot::Right, "header-right", item)
1160 }
1161
1162 pub fn header_title(self, item: impl IntoElement) -> Self {
1164 self.header_item(HeaderSlot::Title, "header-title", item)
1165 }
1166
1167 pub fn header(self, item: impl IntoElement) -> Self {
1171 self.header_item(HeaderSlot::Header, "header", item)
1172 }
1173
1174 pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1177 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1178 }
1179
1180 pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1183 self.listen(
1184 EventKind::BackRequest,
1185 listener.into_listener(),
1186 events::unit,
1187 )
1188 }
1189}
1190
1191impl Overlay {
1192 pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1196 let anchor = *anchor;
1197 self.bind_prop(
1198 move || match anchor.node() {
1199 Some(id) => OverlayAnchor::Node(id),
1200 None => OverlayAnchor::None,
1201 },
1202 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1203 )
1204 }
1205
1206 pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1212 let cover = *cover;
1213 self.bind_prop(
1214 move || if shown() { cover.node() } else { None },
1215 |id| Prop::Overlay(OverlayProp::Cover(id)),
1216 )
1217 }
1218
1219 pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1223 let (anchor, edges) = (*anchor, *edges);
1224 self.bind_prop(
1225 move || match (anchor.node(), edges.node()) {
1226 (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1227 (Some(id), None) => OverlayAnchor::Node(id),
1228 _ => OverlayAnchor::None,
1229 },
1230 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1231 )
1232 }
1233
1234 pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1240 let anchor = *anchor;
1241 self.bind_prop(
1242 move || match anchor.node() {
1243 Some(id) => OverlayAnchor::Content(id),
1244 None => OverlayAnchor::None,
1245 },
1246 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1247 )
1248 }
1249
1250 pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1253 self.bind_prop(point, |p| {
1254 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1255 })
1256 }
1257
1258 pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1262 self.bind_prop(bounds, |b| {
1263 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1264 })
1265 }
1266
1267 pub fn anchor_to(self, anchor: impl IntoReactive<OverlayAnchor>) -> Self {
1271 self.bind_prop(anchor, |a| Prop::Overlay(OverlayProp::Anchor(a)))
1272 }
1273
1274 pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1276 self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1277 }
1278
1279 pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1281 self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1282 }
1283
1284 pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1286 self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1287 }
1288
1289 pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1291 self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1292 }
1293
1294 pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1298 self.listen(
1299 EventKind::PressOutside,
1300 listener.into_listener(),
1301 events::page_point,
1302 )
1303 }
1304
1305 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1309 self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1310 }
1311
1312 pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1321 self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1322 }
1323
1324 pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1329 self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1330 }
1331
1332 pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1336 self.listen(
1337 EventKind::Show,
1338 listener.into_listener(),
1339 events::hint_reason,
1340 )
1341 }
1342
1343 pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1347 self.listen(
1348 EventKind::Dismiss,
1349 listener.into_listener(),
1350 events::hint_reason,
1351 )
1352 }
1353
1354 pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1357 self.listen(
1358 EventKind::Position,
1359 listener.into_listener(),
1360 events::overlay_position,
1361 )
1362 }
1363}
1364
1365impl Modal {
1366 pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1368 self.bind_prop(animation, |animation: ModalAnimation| {
1369 Prop::Modal(ModalProp::Animation(animation))
1370 })
1371 }
1372
1373 pub fn transition_shader(
1377 self,
1378 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1379 ) -> Self {
1380 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1381 Prop::TransitionShader(s.map(Into::into))
1382 })
1383 }
1384
1385 pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1387 self.bind_prop(presentation, |presentation: ModalPresentation| {
1388 Prop::Modal(ModalProp::Presentation(presentation))
1389 })
1390 }
1391
1392 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1395 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1396 }
1397
1398 pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1400 self.bind_prop(translucent, |translucent: bool| {
1401 Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1402 })
1403 }
1404
1405 pub fn supported_orientations(
1408 self,
1409 orientations: impl IntoIterator<Item = Orientation>,
1410 ) -> Self {
1411 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1412 self.set(Prop::Modal(ModalProp::Orientations(bits)))
1413 }
1414
1415 pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1418 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1419 }
1420
1421 pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1425 self.bind_prop(close, |v: bool| {
1426 Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1427 })
1428 }
1429
1430 pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1432 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1433 }
1434
1435 pub fn detents(self, detents: impl IntoReactive<Vec<SheetDetent>>) -> Self {
1442 self.bind_prop(detents, |v: Vec<SheetDetent>| {
1443 Prop::Modal(ModalProp::Detents(v))
1444 })
1445 }
1446
1447 pub fn detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1452 self.bind_prop(detent, |v: Option<SheetDetent>| {
1453 Prop::Modal(ModalProp::Detent(v))
1454 })
1455 }
1456
1457 pub fn default_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1460 self.bind_prop(detent, |v: Option<SheetDetent>| {
1461 Prop::Modal(ModalProp::DefaultDetent(v))
1462 })
1463 }
1464
1465 pub fn grabber(self, grabber: impl IntoReactive<bool>) -> Self {
1467 self.bind_prop(grabber, |v: bool| Prop::Modal(ModalProp::Grabber(v)))
1468 }
1469
1470 pub fn largest_undimmed_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1473 self.bind_prop(detent, |v: Option<SheetDetent>| {
1474 Prop::Modal(ModalProp::LargestUndimmedDetent(v))
1475 })
1476 }
1477
1478 pub fn on_detent_change<M>(self, listener: impl IntoListener<SheetDetent, M>) -> Self {
1481 self.listen(
1482 EventKind::DetentChange,
1483 listener.into_listener(),
1484 events::sheet_detent,
1485 )
1486 }
1487
1488 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1492 self.listen(
1493 EventKind::RequestClose,
1494 listener.into_listener(),
1495 events::unit,
1496 )
1497 }
1498
1499 pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1501 self.listen(EventKind::Show, listener.into_listener(), events::unit)
1502 }
1503
1504 pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1506 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1507 }
1508}
1509
1510#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1512pub enum Orientation {
1513 Portrait,
1515 PortraitUpsideDown,
1517 Landscape,
1519 LandscapeLeft,
1523 LandscapeRight,
1527}
1528
1529impl Orientation {
1530 fn bits(self) -> u8 {
1531 use crate::ModalConfig as M;
1532 match self {
1533 Orientation::Portrait => M::PORTRAIT,
1534 Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1535 Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1536 Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1537 Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1538 }
1539 }
1540}
1541
1542impl WebView {
1543 pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1546 let base_url: Option<Arc<str>> = base_url.map(Into::into);
1547 self.bind_prop(html, move |html: String| {
1548 Prop::Native(NativeProp::Source(WebSource::Html {
1549 html: html.into(),
1550 base_url: base_url.clone(),
1551 }))
1552 })
1553 }
1554
1555 pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1557 self.bind_prop(script, |script: String| {
1558 Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1559 })
1560 }
1561
1562 pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1564 self.bind_prop(script, |script: String| {
1565 Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1566 })
1567 }
1568
1569 pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1571 self.bind_prop(agent, |agent: String| {
1572 Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1573 })
1574 }
1575
1576 pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1578 self.bind_prop(enabled, |enabled: bool| {
1579 Prop::Native(NativeProp::Scrollable(enabled))
1580 })
1581 }
1582
1583 pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1585 self.bind_prop(enabled, |enabled: bool| {
1586 Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1587 })
1588 }
1589
1590 pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1592 self.bind_prop(enabled, |enabled: bool| {
1593 Prop::Native(NativeProp::BackForwardGestures(enabled))
1594 })
1595 }
1596
1597 pub fn incognito(self, incognito: bool) -> Self {
1602 self.set(Prop::Native(NativeProp::Incognito(incognito)))
1603 }
1604
1605 pub fn url_scheme(
1620 self,
1621 scheme: &str,
1622 handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1623 ) -> Self {
1624 let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1625 Ok(scheme) => scheme,
1626 Err(e) => {
1627 log::warn!(target: "js", "web view: {e}");
1628 return self;
1629 }
1630 };
1631 let mut schemes = self
1632 .0
1633 .attrs
1634 .props
1635 .iter()
1636 .find_map(|p| match p {
1637 Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1638 _ => None,
1639 })
1640 .unwrap_or_default();
1641 schemes.retain(|s| s.scheme() != scheme.scheme());
1642 schemes.push(scheme);
1643 self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1644 }
1645
1646 pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1648 self.listen(
1649 EventKind::LoadStart,
1650 listener.into_listener(),
1651 events::navigation,
1652 )
1653 }
1654
1655 pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1657 self.listen(
1658 EventKind::Load,
1659 listener.into_listener(),
1660 events::navigation,
1661 )
1662 }
1663
1664 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1666 self.listen(EventKind::Error, listener.into_listener(), events::message)
1667 }
1668
1669 pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1675 self.listen(
1676 EventKind::Error,
1677 listener.into_listener(),
1678 events::unavailable,
1679 )
1680 }
1681
1682 pub fn on_process_terminated<M>(self, listener: impl IntoListener<str, M>) -> Self {
1688 self.listen(
1689 EventKind::Error,
1690 listener.into_listener(),
1691 events::terminated,
1692 )
1693 }
1694
1695 pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1697 self.listen(EventKind::Message, listener.into_listener(), events::data)
1698 }
1699
1700 pub fn on_navigation_state_change<M>(
1702 self,
1703 listener: impl IntoListener<WebNavigation, M>,
1704 ) -> Self {
1705 self.listen(
1706 EventKind::NavigationStateChange,
1707 listener.into_listener(),
1708 events::navigation,
1709 )
1710 }
1711
1712 pub fn on_download<M>(
1719 self,
1720 listener: impl IntoListener<crate::webview::WebDownload, M>,
1721 ) -> Self {
1722 self.listen(
1723 EventKind::Download,
1724 listener.into_listener(),
1725 events::web_download,
1726 )
1727 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1728 }
1729
1730 pub fn on_download_pending<M>(
1738 self,
1739 listener: impl IntoListener<crate::webview::WebDownloadPending, M>,
1740 ) -> Self {
1741 self.listen(
1742 EventKind::DownloadPending,
1743 listener.into_listener(),
1744 events::web_download_pending,
1745 )
1746 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1747 }
1748}
1749
1750impl Video {
1751 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1753 self.bind_prop(paused, |paused: bool| {
1754 Prop::Native(NativeProp::Paused(paused))
1755 })
1756 }
1757
1758 pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1760 self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1761 }
1762
1763 pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1765 self.bind_prop(volume, |volume: f32| {
1766 Prop::Native(NativeProp::Volume(volume))
1767 })
1768 }
1769
1770 pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1772 self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1773 }
1774
1775 pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1777 self.bind_prop(repeat, |repeat: bool| {
1778 Prop::Native(NativeProp::Repeat(repeat))
1779 })
1780 }
1781
1782 pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1784 self.bind_prop(controls, |controls: bool| {
1785 Prop::Native(NativeProp::Controls(controls))
1786 })
1787 }
1788
1789 pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1791 self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1792 }
1793
1794 pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1797 self.bind_prop(session, |session: AudioSession| {
1798 Prop::Native(NativeProp::AudioSession(session))
1799 })
1800 }
1801
1802 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1804 self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1805 }
1806
1807 pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1809 self.listen(EventKind::Load, listener.into_listener(), events::video)
1810 }
1811
1812 pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1814 self.listen(
1815 EventKind::Progress,
1816 listener.into_listener(),
1817 events::progress,
1818 )
1819 }
1820
1821 pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1823 self.listen(EventKind::End, listener.into_listener(), events::unit)
1824 }
1825
1826 pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1828 self.listen(
1829 EventKind::Buffer,
1830 listener.into_listener(),
1831 events::buffering,
1832 )
1833 }
1834
1835 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1837 self.listen(EventKind::Error, listener.into_listener(), events::message)
1838 }
1839}
1840
1841impl NativeView {
1842 pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1845 let name: Arc<str> = name.into();
1846 self.bind_prop(value, move |value| {
1847 Prop::ComponentProp(name.clone(), Some(value))
1848 })
1849 }
1850
1851 pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1857 if let Some(node) = value.animated_node().live() {
1858 set(
1859 &mut self.0,
1860 Prop::ComponentPropBinding(name.into(), Some(node.id())),
1861 );
1862 self.0.attrs.rare_mut().bound.push(node);
1863 }
1864 self
1865 }
1866
1867 pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1869 self.listen(
1870 EventKind::NativeEvent,
1871 listener.into_listener(),
1872 events::native,
1873 )
1874 }
1875}
1876
1877#[derive(Debug, Clone, PartialEq)]
1880pub struct CanvasArg(pub(crate) CanvasArgKind);
1881
1882#[derive(Debug, Clone, PartialEq)]
1883pub(crate) enum CanvasArgKind {
1884 Const(f32),
1885 Node(super::LiveNode),
1886}
1887
1888impl From<f32> for CanvasArg {
1889 fn from(n: f32) -> Self {
1890 Self(CanvasArgKind::Const(n))
1891 }
1892}
1893
1894impl From<Points> for CanvasArg {
1896 fn from(n: Points) -> Self {
1897 Self(CanvasArgKind::Const(n.0))
1898 }
1899}
1900
1901impl From<Radians> for CanvasArg {
1903 fn from(n: Radians) -> Self {
1904 Self(CanvasArgKind::Const(n.0))
1905 }
1906}
1907
1908impl<A: super::Animated> From<&A> for CanvasArg {
1910 fn from(a: &A) -> Self {
1911 Self(match a.animated_node().live() {
1912 Some(node) => CanvasArgKind::Node(node),
1913 None => CanvasArgKind::Const(0.0),
1914 })
1915 }
1916}
1917
1918#[derive(Debug, Clone, PartialEq)]
1923pub struct CanvasPaint(CanvasPaintKind);
1924
1925#[derive(Debug, Clone, PartialEq)]
1926enum CanvasPaintKind {
1927 Color(Color),
1928 Gradient(Arc<CanvasGradient>),
1929 Node(super::LiveNode),
1930}
1931
1932impl From<Color> for CanvasPaint {
1933 fn from(color: Color) -> Self {
1934 Self(CanvasPaintKind::Color(color))
1935 }
1936}
1937
1938impl From<Hsla> for CanvasPaint {
1939 fn from(color: Hsla) -> Self {
1940 Color::from(color).into()
1941 }
1942}
1943
1944impl From<Rgba> for CanvasPaint {
1945 fn from(color: Rgba) -> Self {
1946 Color::from(color).into()
1947 }
1948}
1949
1950impl From<CanvasGradient> for CanvasPaint {
1951 fn from(gradient: CanvasGradient) -> Self {
1952 Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
1953 }
1954}
1955
1956impl From<Arc<CanvasGradient>> for CanvasPaint {
1957 fn from(gradient: Arc<CanvasGradient>) -> Self {
1958 Self(CanvasPaintKind::Gradient(gradient))
1959 }
1960}
1961
1962impl<A: super::Animated> From<&A> for CanvasPaint {
1964 fn from(a: &A) -> Self {
1965 Self(match a.animated_node().live() {
1966 Some(node) => CanvasPaintKind::Node(node),
1967 None => CanvasPaintKind::Color(Color::TRANSPARENT),
1968 })
1969 }
1970}
1971
1972#[derive(Debug, Clone, Default)]
1980pub struct Painter {
1981 drawing: Drawing,
1982 nodes: Vec<super::LiveNode>,
1984}
1985
1986impl Painter {
1987 pub fn new() -> Self {
1989 Self::default()
1990 }
1991
1992 pub fn finish(self) -> Drawing {
1994 self.drawing
1995 }
1996
1997 pub fn render(
2008 self,
2009 size: Size<Points>,
2010 options: crate::canvas::render::RenderOptions,
2011 ) -> crate::element::Answer<Result<Vec<u8>, crate::element::JsError>> {
2012 crate::element::ambient::render_canvas(crate::canvas::render::RenderRequest {
2013 drawing: self.drawing,
2014 size,
2015 scale: options.scale,
2016 format: options.format,
2017 })
2018 }
2019
2020 pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
2024 match value.into().0 {
2025 CanvasArgKind::Const(n) => Num::Const(n),
2026 CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
2027 }
2028 }
2029
2030 pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
2033 match paint.into().0 {
2034 CanvasPaintKind::Color(color) => Paint::Color(color),
2035 CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
2036 CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
2037 }
2038 }
2039
2040 fn slot(&mut self, node: super::LiveNode) -> u16 {
2041 let slot = self.drawing.slot(node.id());
2042 self.nodes.push(node);
2043 slot
2044 }
2045
2046 pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
2049 self.drawing.nodes.push(node);
2050 self
2051 }
2052
2053 pub fn op(mut self, op: CanvasOp) -> Self {
2056 self.drawing.ops.push(op);
2057 self
2058 }
2059
2060 fn path(self, op: PathOp) -> Self {
2061 self.op(CanvasOp::Path(op))
2062 }
2063
2064 pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
2071 crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
2072 }
2073
2074 pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
2078 crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
2079 }
2080
2081 pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
2086 crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
2087 }
2088
2089 pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
2093 crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
2094 }
2095
2096 pub fn save(self) -> Self {
2098 self.op(CanvasOp::Save)
2099 }
2100
2101 pub fn restore(self) -> Self {
2103 self.op(CanvasOp::Restore)
2104 }
2105
2106 pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2108 let (x, y) = (self.num(x), self.num(y));
2109 self.op(CanvasOp::Translate(x, y))
2110 }
2111
2112 pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2114 let (x, y) = (self.num(x), self.num(y));
2115 self.op(CanvasOp::Scale(x, y))
2116 }
2117
2118 pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
2121 let a = self.num(angle);
2122 self.op(CanvasOp::Rotate(a))
2123 }
2124
2125 pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2128 let m = m.map(|n| self.num(n));
2129 self.op(CanvasOp::Transform(m))
2130 }
2131
2132 pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2135 let m = m.map(|n| self.num(n));
2136 self.op(CanvasOp::SetTransform(m))
2137 }
2138
2139 pub fn reset_transform(self) -> Self {
2141 self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
2142 }
2143
2144 pub fn begin_path(self) -> Self {
2146 self.op(CanvasOp::BeginPath)
2147 }
2148
2149 pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2151 let (x, y) = (self.num(x), self.num(y));
2152 self.path(PathOp::MoveTo(x, y))
2153 }
2154
2155 pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2157 let (x, y) = (self.num(x), self.num(y));
2158 self.path(PathOp::LineTo(x, y))
2159 }
2160
2161 pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
2163 let c = |v: Points| Num::Const(v.0);
2164 self.path(PathOp::QuadTo([
2165 c(control.x),
2166 c(control.y),
2167 c(to.x),
2168 c(to.y),
2169 ]))
2170 }
2171
2172 pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
2174 let c = |v: Points| Num::Const(v.0);
2175 self.path(PathOp::CubicTo([
2176 c(c1.x),
2177 c(c1.y),
2178 c(c2.x),
2179 c(c2.y),
2180 c(to.x),
2181 c(to.y),
2182 ]))
2183 }
2184
2185 pub fn arc(
2188 self,
2189 x: impl Into<CanvasArg>,
2190 y: impl Into<CanvasArg>,
2191 radius: impl Into<CanvasArg>,
2192 start: impl Into<CanvasArg>,
2193 end: impl Into<CanvasArg>,
2194 ) -> Self {
2195 self.arc_in(x, y, radius, start, end, false)
2196 }
2197
2198 pub fn arc_counterclockwise(
2200 self,
2201 x: impl Into<CanvasArg>,
2202 y: impl Into<CanvasArg>,
2203 radius: impl Into<CanvasArg>,
2204 start: impl Into<CanvasArg>,
2205 end: impl Into<CanvasArg>,
2206 ) -> Self {
2207 self.arc_in(x, y, radius, start, end, true)
2208 }
2209
2210 fn arc_in(
2211 mut self,
2212 x: impl Into<CanvasArg>,
2213 y: impl Into<CanvasArg>,
2214 radius: impl Into<CanvasArg>,
2215 start: impl Into<CanvasArg>,
2216 end: impl Into<CanvasArg>,
2217 ccw: bool,
2218 ) -> Self {
2219 let (x, y, radius, start, end) = (
2220 self.num(x),
2221 self.num(y),
2222 self.num(radius),
2223 self.num(start),
2224 self.num(end),
2225 );
2226 self.path(PathOp::Arc {
2227 x,
2228 y,
2229 radius,
2230 start,
2231 end,
2232 ccw,
2233 })
2234 }
2235
2236 pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2239 let c = |v: Points| Num::Const(v.0);
2240 self.path(PathOp::ArcTo([
2241 c(p1.x),
2242 c(p1.y),
2243 c(p2.x),
2244 c(p2.y),
2245 c(radius),
2246 ]))
2247 }
2248
2249 pub fn ellipse(
2253 self,
2254 center: Point<Points>,
2255 radii: Size<Points>,
2256 rotation: Radians,
2257 start: Radians,
2258 end: Radians,
2259 counterclockwise: bool,
2260 ) -> Self {
2261 let c = Num::Const;
2262 self.path(PathOp::Ellipse {
2263 geometry: [
2264 c(center.x.0),
2265 c(center.y.0),
2266 c(radii.width.0),
2267 c(radii.height.0),
2268 c(rotation.0),
2269 ],
2270 start: c(start.0),
2271 end: c(end.0),
2272 ccw: counterclockwise,
2273 })
2274 }
2275
2276 pub fn rect(self, rect: Bounds<Points>) -> Self {
2278 self.path(PathOp::Rect(nums(rect)))
2279 }
2280
2281 pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2283 self.round_rect_corners(rect, Corners::all(radius))
2284 }
2285
2286 pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2288 let c = |v: Points| Num::Const(v.0);
2289 self.path(PathOp::RoundRect(
2290 nums(rect),
2291 [
2292 c(radii.top_left),
2293 c(radii.top_right),
2294 c(radii.bottom_right),
2295 c(radii.bottom_left),
2296 ],
2297 ))
2298 }
2299
2300 pub fn close_path(self) -> Self {
2302 self.path(PathOp::Close)
2303 }
2304
2305 pub fn fill(self) -> Self {
2307 self.fill_with(FillRule::NonZero)
2308 }
2309
2310 pub fn fill_with(self, rule: FillRule) -> Self {
2312 self.op(CanvasOp::Fill(None, rule))
2313 }
2314
2315 pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2318 self.op(CanvasOp::Fill(Some(path.clone()), rule))
2319 }
2320
2321 pub fn fill_svg(self, data: &str) -> Self {
2324 self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2325 }
2326
2327 pub fn stroke(self) -> Self {
2329 self.op(CanvasOp::Stroke(None))
2330 }
2331
2332 pub fn stroke_path(self, path: &Path) -> Self {
2334 self.op(CanvasOp::Stroke(Some(path.clone())))
2335 }
2336
2337 pub fn stroke_svg(self, data: &str) -> Self {
2339 self.stroke_path(&crate::canvas::svg_path(data))
2340 }
2341
2342 pub fn clip(self) -> Self {
2344 self.clip_with(FillRule::NonZero)
2345 }
2346
2347 pub fn clip_with(self, rule: FillRule) -> Self {
2349 self.op(CanvasOp::Clip(None, rule))
2350 }
2351
2352 pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2354 self.op(CanvasOp::Clip(Some(path.clone()), rule))
2355 }
2356
2357 pub fn fill_rect(
2359 mut self,
2360 x: impl Into<CanvasArg>,
2361 y: impl Into<CanvasArg>,
2362 w: impl Into<CanvasArg>,
2363 h: impl Into<CanvasArg>,
2364 ) -> Self {
2365 let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2366 self.op(CanvasOp::FillRect([x, y, w, h]))
2367 }
2368
2369 pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2371 self.op(CanvasOp::StrokeRect(nums(rect)))
2372 }
2373
2374 pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2376 self.op(CanvasOp::ClearRect(nums(rect)))
2377 }
2378
2379 pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2381 self.fill_style(color.into())
2382 }
2383
2384 pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2386 self.stroke_style(color.into())
2387 }
2388
2389 pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2392 let paint = self.paint(paint);
2393 self.op(CanvasOp::FillStyle(paint))
2394 }
2395
2396 pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2402 self.view_paint(
2403 ViewPaint::Fill(initial),
2404 CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2405 )
2406 }
2407
2408 pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2411 self.view_paint(
2412 ViewPaint::Stroke(initial),
2413 CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2414 )
2415 }
2416
2417 pub fn line_width_from_view(self) -> Self {
2420 self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2421 }
2422
2423 pub fn line_dash_from_view(self) -> Self {
2426 self.view_paint(
2427 ViewPaint::StrokeDasharray,
2428 CanvasOp::LineDash(Arc::from([])),
2429 )
2430 }
2431
2432 pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2441 self.view_paint(
2442 ViewPaint::Background {
2443 area,
2444 rule: FillRule::NonZero,
2445 },
2446 CanvasOp::Fill(None, FillRule::NonZero),
2447 )
2448 }
2449
2450 fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2451 let at = self.drawing.ops.len() as u32;
2452 self.drawing.view_paints.push((at, view));
2453 self.op(placeholder)
2454 }
2455
2456 pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2458 let paint = self.paint(paint);
2459 self.op(CanvasOp::StrokeStyle(paint))
2460 }
2461
2462 pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2464 let w = self.num(width);
2465 self.op(CanvasOp::LineWidth(w))
2466 }
2467
2468 pub fn line_cap(self, cap: LineCap) -> Self {
2470 self.op(CanvasOp::LineCap(cap))
2471 }
2472
2473 pub fn line_join(self, join: LineJoin) -> Self {
2475 self.op(CanvasOp::LineJoin(join))
2476 }
2477
2478 pub fn miter_limit(self, limit: f32) -> Self {
2481 self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2482 }
2483
2484 pub fn line_dash(self, segments: &[Points]) -> Self {
2486 self.op(CanvasOp::LineDash(segments.into()))
2487 }
2488
2489 pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2492 let o = self.num(offset);
2493 self.op(CanvasOp::LineDashOffset(o))
2494 }
2495
2496 pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2498 let a = self.num(alpha);
2499 self.op(CanvasOp::GlobalAlpha(a))
2500 }
2501
2502 pub fn composite(self, composite: Composite) -> Self {
2504 self.op(CanvasOp::Composite(composite))
2505 }
2506
2507 pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2509 self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2510 .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2511 .op(CanvasOp::ShadowOffset(offset))
2512 }
2513
2514 pub fn font(self, font: &str) -> Self {
2517 match CanvasFont::parse(font) {
2518 Some(font) => self.op(CanvasOp::Font(font)),
2519 None => self,
2520 }
2521 }
2522
2523 pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2527 self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2528 numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2529 )))
2530 }
2531
2532 pub fn text_align(self, align: CanvasTextAlign) -> Self {
2534 self.op(CanvasOp::TextAlign(align))
2535 }
2536
2537 pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2539 self.op(CanvasOp::TextBaseline(baseline))
2540 }
2541
2542 pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2544 self.text(text, x, y, None, false)
2545 }
2546
2547 pub fn fill_text_max_width(
2549 self,
2550 text: &str,
2551 x: impl Into<CanvasArg>,
2552 y: impl Into<CanvasArg>,
2553 max_width: Points,
2554 ) -> Self {
2555 self.text(text, x, y, Some(max_width), false)
2556 }
2557
2558 pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2560 self.text(text, x, y, None, true)
2561 }
2562
2563 pub fn stroke_text_max_width(
2566 self,
2567 text: &str,
2568 x: impl Into<CanvasArg>,
2569 y: impl Into<CanvasArg>,
2570 max_width: Points,
2571 ) -> Self {
2572 self.text(text, x, y, Some(max_width), true)
2573 }
2574
2575 fn text(
2576 mut self,
2577 text: &str,
2578 x: impl Into<CanvasArg>,
2579 y: impl Into<CanvasArg>,
2580 max_width: Option<Points>,
2581 stroke: bool,
2582 ) -> Self {
2583 let (text, x, y) = (text.into(), self.num(x), self.num(y));
2584 self.op(if stroke {
2585 CanvasOp::StrokeText {
2586 text,
2587 x,
2588 y,
2589 max_width,
2590 }
2591 } else {
2592 CanvasOp::FillText {
2593 text,
2594 x,
2595 y,
2596 max_width,
2597 }
2598 })
2599 }
2600
2601 pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2603 self.draw_image_part(uri, None, dest)
2604 }
2605
2606 pub fn draw_image_part(
2609 self,
2610 uri: &str,
2611 source: Option<Bounds<ScaledPixels>>,
2612 dest: Bounds<Points>,
2613 ) -> Self {
2614 self.op(CanvasOp::DrawImage {
2615 image: CanvasImage { uri: uri.into() },
2616 source,
2617 dest: nums(dest),
2618 })
2619 }
2620}
2621
2622fn nums(rect: Bounds<Points>) -> [Num; 4] {
2624 [
2625 rect.origin.x,
2626 rect.origin.y,
2627 rect.size.width,
2628 rect.size.height,
2629 ]
2630 .map(|v| Num::Const(v.0))
2631}
2632
2633impl From<Drawing> for Painter {
2634 fn from(drawing: Drawing) -> Self {
2635 Self {
2636 drawing,
2637 nodes: Vec::new(),
2638 }
2639 }
2640}
2641
2642crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2643
2644impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2646 fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2647 super::Reactive::Static(Some(self))
2648 }
2649}
2650
2651impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2653 fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2654 super::Reactive::Static(Some(self))
2655 }
2656}
2657
2658impl IntoReactive<Option<crate::WindowsBackdrop>> for crate::WindowsBackdrop {
2660 fn into_reactive(self) -> super::Reactive<Option<crate::WindowsBackdrop>> {
2661 super::Reactive::Static(Some(self))
2662 }
2663}
2664
2665#[cfg(test)]
2666mod tests {
2667 use super::*;
2668 use crate::{
2669 element::{
2670 AnimatedValue,
2671 reactive::{Runtime, create_root, signal},
2672 },
2673 shader::{ShaderUniforms, UniformValue},
2674 };
2675
2676 fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2677 attrs
2678 .props
2679 .iter()
2680 .find_map(|p| match p {
2681 Prop::Uniforms(u) => Some(u.clone()),
2682 _ => None,
2683 })
2684 .unwrap_or_default()
2685 }
2686
2687 fn released(executor: &super::super::task::Executor) -> usize {
2689 executor
2690 .take_actions()
2691 .into_iter()
2692 .filter(|a| {
2693 matches!(
2694 a,
2695 super::super::task::Action::Animation(
2696 crate::animation::AnimationOp::Release { .. }
2697 )
2698 )
2699 })
2700 .count()
2701 }
2702
2703 fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2704 u.0.iter()
2705 .find(|(n, _)| &**n == name)
2706 .map(|(_, v)| v.clone())
2707 }
2708
2709 #[test]
2710 fn screens_and_modals_take_a_transition_shader() {
2711 let runtime = Runtime::default();
2712 let _entered = runtime.enter();
2713 let source = "struct Uniforms { edge: f32 }\n\
2714 fn shade(uv: vec2f) -> vec4f {\n \
2715 return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2716 let shader = crate::shader::Shader::compile(source).expect("compiles");
2717 let wipe = crate::shader::TransitionShader::new(shader)
2718 .uniform("edge", 1.0_f32)
2719 .duration(std::time::Duration::from_millis(400));
2720 let expected = crate::shader::NavShaderSpec {
2721 source: source.into(),
2722 uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2723 duration: Some(400.0),
2724 };
2725 let spec = |attrs: &super::super::builder::Attrs| {
2726 attrs.props.iter().find_map(|p| match p {
2727 Prop::TransitionShader(s) => Some(s.clone()),
2728 _ => None,
2729 })
2730 };
2731 let page = screen().transition_shader(wipe.clone()).0;
2732 assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2733 let dialog = modal().transition_shader(wipe.clone()).0;
2734 assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2735 let on = signal(true);
2737 let bound = screen()
2738 .transition_shader(move || on.get().then(|| wipe.clone()))
2739 .0;
2740 assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
2741 on.set(false);
2742 assert_eq!(spec(&bound.resolved_attrs()), Some(None));
2743 }
2744
2745 #[test]
2746 fn uniform_takes_static_bound_and_animated_values() {
2747 let runtime = Runtime::default();
2748 let _entered = runtime.enter();
2749 let executor = std::rc::Rc::new(super::super::task::Executor::default());
2750 let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
2751 let speed = signal(1.0_f32);
2752 let view = shader()
2753 .uniform("center", [0.5_f32, 0.5])
2754 .uniform("wave", &wave)
2755 .uniform("speed", move || speed.get());
2756 let node = view.0;
2757
2758 let set = uniforms(&node.attrs);
2761 assert_eq!(
2762 value(&set, "center"),
2763 Some(UniformValue::List(vec![
2764 UniformValue::Number(0.5),
2765 UniformValue::Number(0.5)
2766 ]))
2767 );
2768 let id = wave.node().live().expect("live").id();
2769 assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
2770 assert_eq!(
2771 node.attrs.bound().len(),
2772 1,
2773 "the element holds the animated node"
2774 );
2775 assert_eq!(
2776 value(&set, "speed"),
2777 None,
2778 "a bound one is applied when resolved"
2779 );
2780
2781 assert_eq!(
2783 value(&uniforms(&node.resolved_attrs()), "speed"),
2784 Some(UniformValue::Number(1.0))
2785 );
2786 speed.set(2.0);
2787 assert_eq!(
2788 value(&uniforms(&node.resolved_attrs()), "speed"),
2789 Some(UniformValue::Number(2.0))
2790 );
2791
2792 value_owner.dispose();
2794 assert_eq!(released(&executor), 0, "the view keeps the animated node");
2795 drop(node);
2796 assert_eq!(released(&executor), 1, "and lets it go with the view");
2797 }
2798
2799 #[test]
2800 fn a_later_uniform_replaces_one_of_the_same_name() {
2801 let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
2802 let set = uniforms(&view.0.attrs);
2803 assert_eq!(set.0.len(), 1);
2804 assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
2805 }
2806
2807 #[test]
2808 fn web_view_url_scheme_builder_collects_schemes() {
2809 let web = web_view_html("<img src=\"a:1\">", None)
2810 .url_scheme("a", |request| request.fail())
2811 .url_scheme("b", |request| request.fail())
2812 .url_scheme("A", |request| request.fail())
2814 .url_scheme("https", |request| request.fail());
2816 let schemes: Vec<String> = web
2817 .0
2818 .attrs
2819 .props
2820 .iter()
2821 .find_map(|p| match p {
2822 Prop::Native(NativeProp::UrlSchemes(list)) => {
2823 Some(list.iter().map(|s| s.scheme().to_owned()).collect())
2824 }
2825 _ => None,
2826 })
2827 .unwrap();
2828 assert_eq!(schemes, ["b", "a"]);
2829 }
2830}