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, HeaderTitleAlign, Hsla,
20 JsonValue, KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp,
21 NativeProp, OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType,
22 Rgba, ScreenAnimation, ScreenProp, ScrollProp, SheetDetent, Size, StatusBarSetting,
23 SubmitBehavior, 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 NavStack
191}
192
193host_element! {
194 NavPage
198}
199
200host_element! {
201 Dialog
205}
206
207#[deprecated(since = "0.9.0", note = "renamed to `NavStack`")]
209pub type Stack = NavStack;
210
211#[deprecated(since = "0.9.0", note = "renamed to `NavPage`")]
213pub type Screen = NavPage;
214
215#[deprecated(since = "0.9.0", note = "renamed to `Dialog`")]
217pub type Modal = Dialog;
218
219host_element! {
220 InputAccessoryView
224}
225
226host_element! {
227 CanvasView
229}
230
231host_element! {
232 Svg
234}
235
236host_element! {
237 ShaderView
240}
241
242host_element! {
243 WebView
245}
246
247host_element! {
248 Video
250}
251
252host_element! {
253 NativeView
256}
257
258host_element! {
259 GpuView
263}
264
265host_element! {
266 Overlay
271}
272
273impl ParentElement for Overlay {}
274impl ParentElement for ShaderView {}
275impl ParentElement for GpuView {}
276impl ParentElement for Scroll {}
277impl ParentElement for NavStack {}
278impl ParentElement for NavPage {}
279impl ParentElement for Dialog {}
280
281fn has_input_accessory() -> bool {
284 super::ambient::try_os().unwrap_or_default() == crate::platform::Os::Ios
285}
286
287impl ParentElement for InputAccessoryView {
288 fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
289 if has_input_accessory() {
290 child.__push_into(&mut self.0.children);
291 }
292 self
293 }
294
295 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
296 if has_input_accessory() {
297 self.0
298 .children
299 .extend(children.into_iter().map(|c| c.into_element().0));
300 }
301 self
302 }
303}
304
305pub fn overlay() -> Overlay {
313 Overlay(ElNode::new(Tag::Overlay))
314}
315
316pub fn input() -> Input {
318 Input(ElNode::new(Tag::Input))
319}
320
321pub fn scroll() -> Scroll {
323 Scroll(ElNode::new(Tag::Scroll))
324}
325
326#[doc(hidden)]
332pub fn stack() -> NavStack {
333 NavStack(ElNode::new(Tag::Stack))
334}
335
336#[doc(hidden)]
341pub fn screen() -> NavPage {
342 let mut node = ElNode::new(Tag::Screen);
343 node.handlers.push((EventKind::Insets, Listener::noop()));
345 NavPage(node)
346}
347
348#[doc(hidden)]
353pub fn modal() -> Dialog {
354 let mut node = ElNode::new(Tag::Modal);
355 node.handlers.push((EventKind::Insets, Listener::noop()));
357 Dialog(node)
358}
359
360pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
366 let supported = has_input_accessory();
367 let tag = if supported {
368 Tag::InputAccessory
369 } else {
370 Tag::View
371 };
372 let mut node = ElNode::new(tag);
373 if supported {
374 set(&mut node, Prop::NativeId(Some(native_id.into())));
375 } else {
376 node.style.value(
377 crate::StyleKey::Display,
378 crate::PropertyValue::Display(taffy::Display::None),
379 );
380 }
381 InputAccessoryView(node)
382}
383
384pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
389 let mut node = ElNode::new(Tag::Canvas);
390 node.bind_attr(painter, |attrs, painter: Painter| {
391 let r = attrs.rare_mut();
392 r.drawing = Some(Arc::new(painter.drawing));
393 r.bound = painter.nodes;
394 });
395 CanvasView(node)
396}
397
398crate::static_reactive!(Painter: Painter, Drawing);
399
400pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
420 #[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
421 {
422 let mut node = ElNode::new(Tag::Canvas);
423 let shown = svg_drawing(src);
424 node.bind_attr(
425 move || shown.get(),
426 |attrs, drawing: Option<Arc<crate::canvas::Drawing>>| {
427 if drawing.is_some() || attrs.rare.is_some() {
428 attrs.rare_mut().drawing = drawing;
429 }
430 },
431 );
432 Svg(node)
433 }
434 #[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
435 {
436 let mut node = ElNode::new(Tag::Image);
437 node.style.value(
438 crate::StyleKey::ObjectFit,
439 crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
440 );
441 node.bind_attr(src, |attrs, src| attrs.rare_mut().src = Some(src));
442 set(
444 &mut node,
445 Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
446 );
447 Svg(node)
448 }
449}
450
451#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
456fn svg_drawing(
457 src: impl IntoReactive<super::ImageSrc>,
458) -> super::reactive::Signal<Option<Arc<Drawing>>> {
459 use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
460 let src = src.into_reactive();
461 let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
462 let lease = stored(crate::image::Lease::none());
463 let task = stored(None::<super::Spawned<()>>);
464 render_effect(move || {
465 let src = match &src {
466 super::Reactive::Static(src) => src.clone(),
467 super::Reactive::Bound(f) => f(),
468 };
469 untracked(|| {
470 drop(task.replace(None));
471 let context = crate::image::loader::context();
472 let source = crate::ImageSource {
473 uri: src.uri.as_str().into(),
474 size: None,
475 scales: crate::ImageScales::NONE,
476 data: src.data,
477 }
478 .inline();
479 let Some(location) = context.locate(&source) else {
480 log::warn!("svg: unsupported source `{}`", source.uri);
481 shown.set(None);
482 lease.replace(crate::image::Lease::none());
483 return;
484 };
485 if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
486 shown.set(Some(drawing));
487 lease.replace(held);
488 return;
489 }
490 let load = crate::svg::drawings::load(location, context);
491 task.replace(Some(super::spawn(async move {
492 let (drawing, held) = load.await;
493 shown.set(Some(drawing));
494 lease.replace(held);
495 })));
496 });
497 });
498 shown
499}
500
501fn shader_view(tag: Tag) -> ShaderView {
504 crate::shader::note_use();
505 ShaderView(ElNode::new(tag))
506}
507
508pub fn shader() -> ShaderView {
512 shader_view(Tag::Shader)
513}
514
515pub fn shader_effect() -> ShaderView {
519 shader_view(Tag::ShaderEffect)
520}
521
522pub fn shader_transition() -> ShaderView {
527 shader_view(Tag::ShaderTransition)
528}
529
530pub fn screen_effect() -> ShaderView {
533 shader_view(Tag::ScreenEffect)
534}
535
536pub fn screen_transition() -> ShaderView {
540 shader_view(Tag::ScreenTransition)
541}
542
543crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);
544
545pub struct Uniform(UniformSource);
547
548enum UniformSource {
549 Value(super::Reactive<crate::shader::UniformValue>),
550 Animated(super::AnimatedNode),
551}
552
553pub trait IntoUniform {
556 fn into_uniform(self) -> Uniform;
558}
559
560impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
561 fn into_uniform(self) -> Uniform {
562 Uniform(UniformSource::Value(self.into_reactive()))
563 }
564}
565
566impl IntoUniform for &super::AnimatedValue {
567 fn into_uniform(self) -> Uniform {
568 Uniform(UniformSource::Animated(super::Animated::animated_node(
569 self,
570 )))
571 }
572}
573
574impl IntoUniform for &super::AnimatedNode {
575 fn into_uniform(self) -> Uniform {
576 Uniform(UniformSource::Animated(*self))
577 }
578}
579crate::static_reactive!(
580 crate::shader::UniformValue: crate::shader::UniformValue,
581 f32,
582 i32,
583 Color,
584 Hsla,
585 [f32; 2],
586 [f32; 3],
587 [f32; 4],
588 Vec<crate::shader::UniformValue>
589);
590
591impl ShaderView {
592 pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
596 self.bind_prop(shader, |s| Prop::Shader(Some(s)))
597 }
598
599 pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
606 let name: Arc<str> = name.into();
607 let value = match value.into_uniform().0 {
608 UniformSource::Value(value) => value,
609 UniformSource::Animated(node) => {
610 let value = match node.live() {
611 Some(node) => {
612 let id = node.id();
613 self.0.attrs.rare_mut().bound.push(node);
614 crate::shader::UniformValue::Animated(id)
615 }
616 None => crate::shader::UniformValue::Number(0.0),
617 };
618 super::Reactive::Static(value)
619 }
620 };
621 self.0.bind_attr(value, move |attrs, value| {
622 let mut uniforms = attrs
623 .props
624 .iter()
625 .find_map(|p| match p {
626 Prop::Uniforms(u) => Some(u.clone()),
627 _ => None,
628 })
629 .unwrap_or_default();
630 match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
631 Some(entry) => entry.1 = value,
632 None => uniforms.0.push((name.clone(), value)),
633 }
634 set_in(&mut attrs.props, Prop::Uniforms(uniforms));
635 });
636 self
637 }
638
639 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
641 self.bind_prop(paused, Prop::ShaderPaused)
642 }
643
644 pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
647 self.bind_prop(progress, |p| {
648 Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
649 })
650 }
651
652 pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
655 let progress = match value.animated_node().live() {
656 Some(node) => {
657 let id = node.id();
658 self.0.attrs.rare_mut().bound.push(node);
659 crate::shader::ShaderProgress::Animated(id)
660 }
661 None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
662 };
663 self.set(Prop::ShaderProgress(progress))
664 }
665
666 pub fn max_sample_offset(self, offset: Points) -> Self {
669 self.set(Prop::MaxSampleOffset(offset))
670 }
671
672 pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
675 self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
676 }
677
678 pub fn duration(self, duration: std::time::Duration) -> Self {
680 self.set(Prop::TransitionDuration(Some(
681 duration.as_secs_f32() * 1000.0,
682 )))
683 }
684
685 pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
688 self.set(Prop::TransitionFallback(fallback))
689 }
690}
691
692crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);
693
694pub fn web_view(url: impl IntoReactive<String>) -> WebView {
696 WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
697 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
698 })
699}
700
701pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
704 WebView(ElNode::new(Tag::WebView)).html(html, base_url)
705}
706
707pub fn video(url: impl IntoReactive<String>) -> Video {
710 Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
711 Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
712 })
713}
714
715pub fn gpu_view() -> GpuView {
720 GpuView(ElNode::new(Tag::GpuView))
721}
722
723pub fn native(name: &str) -> NativeView {
725 NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
726}
727
728impl Input {
729 pub fn value(self, text: impl IntoReactive<String>) -> Self {
732 self.bind_prop(text, |text: String| Prop::Value(text))
733 }
734
735 pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
737 self.bind_prop(text, |text: String| Prop::DefaultValue(text))
738 }
739
740 pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
742 self.bind_prop(text, |text: String| Prop::Placeholder(text))
743 }
744
745 pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
747 self.bind_prop(color, |color: Hsla| {
748 Prop::PlaceholderColor(Some(color.into()))
749 })
750 }
751
752 pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
755 self.bind_prop(color, |color: Hsla| {
756 Prop::SelectionColor(Some(color.into()))
757 })
758 }
759
760 pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
762 self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
763 }
764
765 pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
767 self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
768 }
769
770 pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
772 self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
773 }
774
775 pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
778 self.bind_prop(appearance, |appearance: KeyboardAppearance| {
779 Prop::KeyboardAppearance(appearance)
780 })
781 }
782
783 pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
785 self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
786 }
787
788 pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
790 self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
791 }
792
793 pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
796 self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
797 }
798
799 pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
801 self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
802 }
803
804 pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
806 self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
807 }
808
809 pub fn scrollbar(self, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
816 self.bind_prop(setting, Prop::Scrollbar)
817 }
818
819 pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
824 self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
825 }
826
827 pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
829 self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
830 }
831
832 pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
835 self.bind_prop(behavior, |behavior: SubmitBehavior| {
836 Prop::SubmitBehavior(Some(behavior))
837 })
838 }
839
840 pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
843 self.bind_prop(behavior, Prop::PasteBehavior)
844 }
845
846 pub fn paste_max_size(self, bytes: impl IntoReactive<u64>) -> Self {
851 self.bind_prop(bytes, |bytes: u64| Prop::PasteMaxSize(Some(bytes)))
852 }
853
854 pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
858 self.listen(EventKind::Paste, listener.into_listener(), events::paste)
859 }
860
861 pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
863 self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
864 }
865
866 pub fn select_text_on_focus(self, select: impl IntoReactive<bool>) -> Self {
870 self.bind_prop(select, |select: bool| Prop::SelectTextOnFocus(select))
871 }
872
873 pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
875 self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
876 }
877
878 pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
881 self.bind_prop(native_id, |id: String| {
882 Prop::InputAccessoryViewId(Some(id.into()))
883 })
884 }
885
886 pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
891 self.bind_prop(range, |(start, end): (u32, u32)| {
892 Prop::Selection(start, end)
893 })
894 }
895
896 pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
898 self.listen(
899 EventKind::ChangeText,
900 listener.into_listener(),
901 events::text,
902 )
903 }
904
905 pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
907 self.listen(
908 EventKind::SubmitEditing,
909 listener.into_listener(),
910 events::text,
911 )
912 }
913
914 pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
916 self.listen(
917 EventKind::SelectionChange,
918 listener.into_listener(),
919 events::selection,
920 )
921 }
922
923 pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
927 self.listen(
928 EventKind::CaretMove,
929 listener.into_listener(),
930 events::caret,
931 )
932 }
933
934 pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
937 self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
938 }
939
940 pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
944 self.listen(
945 EventKind::CompositionChange,
946 listener.into_listener(),
947 events::composition,
948 )
949 }
950
951 pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
953 self.listen(
954 EventKind::ContentSizeChange,
955 listener.into_listener(),
956 events::size,
957 )
958 }
959}
960
961impl Scroll {
962 pub fn horizontal(self) -> Self {
964 self.set(Prop::Horizontal(true))
965 }
966
967 pub fn scrollbar(self, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
971 self.bind_prop(setting, Prop::Scrollbar)
972 }
973
974 pub fn zoom_range(self, min: f32, max: f32) -> Self {
976 self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
977 .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
978 }
979
980 pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
982 self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
983 }
984
985 pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
988 self.bind_prop(bounces, |bounces: bool| {
989 Prop::Scroll(ScrollProp::BouncesZoom(bounces))
990 })
991 }
992
993 pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
995 self.bind_prop(enabled, |enabled: bool| {
996 Prop::Scroll(ScrollProp::Pinch(enabled))
997 })
998 }
999
1000 pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
1002 self.bind_prop(center, |center: bool| {
1003 Prop::Scroll(ScrollProp::CenterContent(center))
1004 })
1005 }
1006}
1007
1008impl super::Scrollable for Scroll {}
1009
1010impl NavPage {
1011 fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
1012 let mut node = ElNode::new(Tag::HeaderItem);
1013 node.key = Some(key.into());
1014 set(&mut node, Prop::HeaderSlot(slot));
1015 node.children.push(item.into_element().0);
1016 self.0.children.push(node);
1017 self
1018 }
1019
1020 pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1022 self.bind_prop(title, |t| {
1023 Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
1024 })
1025 }
1026
1027 pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
1029 self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
1030 }
1031
1032 pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
1035 self.bind_prop(hides, |v| {
1036 Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
1037 })
1038 }
1039
1040 pub fn supported_orientations(
1044 self,
1045 orientations: impl IntoIterator<Item = Orientation>,
1046 ) -> Self {
1047 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1048 self.set(Prop::Screen(ScreenProp::Orientations(bits)))
1049 }
1050
1051 pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
1053 self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
1054 }
1055
1056 pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
1058 self.bind_prop(transparent, |v| {
1059 Prop::Screen(ScreenProp::HeaderTransparent(v))
1060 })
1061 }
1062
1063 pub fn header_shadow_visible(self, visible: impl IntoReactive<bool>) -> Self {
1067 self.bind_prop(visible, |v| {
1068 Prop::Screen(ScreenProp::HeaderShadowVisible(v))
1069 })
1070 }
1071
1072 pub fn header_title_align(self, align: impl IntoReactive<HeaderTitleAlign>) -> Self {
1076 self.bind_prop(align, |a| Prop::Screen(ScreenProp::HeaderTitleAlign(a)))
1077 }
1078
1079 pub fn header_background_on_scroll(self, on: impl IntoReactive<bool>) -> Self {
1085 self.bind_prop(on, |v| {
1086 Prop::Screen(ScreenProp::HeaderBackgroundOnScroll(v))
1087 })
1088 }
1089
1090 pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
1095 let style = match style.into_reactive() {
1096 super::Reactive::Static(s) if s.1.is_bound() => {
1098 super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
1099 }
1100 style => style,
1101 };
1102 self.0.bind_attr(style, |a, s: super::Style| {
1103 set_in(&mut a.props, Prop::HeaderStyle(s.0));
1104 if !s.1.is_empty() {
1105 let typed = s.1.resolved();
1106 let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
1107 set_in(&mut a.props, Prop::HeaderClassList(list));
1108 }
1109 });
1110 self
1111 }
1112
1113 pub fn header_style_with(
1120 self,
1121 f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1122 ) -> Self {
1123 let list = move || {
1124 let style = f(super::StyleRefinement::default()).resolved();
1125 (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1126 };
1127 self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1128 Prop::HeaderClassList(list)
1129 })
1130 }
1131
1132 pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1134 self.bind_prop(title, |t| {
1135 Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1136 })
1137 }
1138
1139 pub fn header_right_system_item(
1143 self,
1144 item: impl IntoReactive<crate::HeaderSystemItem>,
1145 ) -> Self {
1146 self.bind_prop(item, |item| {
1147 Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1148 })
1149 }
1150
1151 pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1155 self.bind_prop(item, |item| {
1156 Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1157 })
1158 }
1159
1160 pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1164 self.bind_prop(name, |n| {
1165 Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1166 })
1167 }
1168
1169 pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1173 self.bind_prop(name, |n| {
1174 Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1175 })
1176 }
1177
1178 pub fn header_right_items(
1186 self,
1187 items: impl IntoReactive<Vec<super::header::HeaderItem>>,
1188 ) -> Self {
1189 self.bind_prop(items, |items| {
1190 Prop::Screen(ScreenProp::HeaderRightItems(super::header::register(items)))
1191 })
1192 }
1193
1194 pub fn header_left_items(
1200 self,
1201 items: impl IntoReactive<Vec<super::header::HeaderItem>>,
1202 ) -> Self {
1203 self.bind_prop(items, |items| {
1204 Prop::Screen(ScreenProp::HeaderLeftItems(super::header::register(items)))
1205 })
1206 }
1207
1208 pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1210 self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1211 }
1212
1213 pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1216 self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1217 }
1218
1219 pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1223 self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1224 }
1225
1226 pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1228 self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1229 }
1230
1231 pub fn transition_shader(
1235 self,
1236 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1237 ) -> Self {
1238 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1239 crate::shader::note_use();
1240 Prop::TransitionShader(s.map(Into::into))
1241 })
1242 }
1243
1244 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1248 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1249 }
1250
1251 pub fn header_left(self, item: impl IntoElement) -> Self {
1253 self.header_item(HeaderSlot::Left, "header-left", item)
1254 }
1255
1256 pub fn header_right(self, item: impl IntoElement) -> Self {
1258 self.header_item(HeaderSlot::Right, "header-right", item)
1259 }
1260
1261 pub fn header_title(self, item: impl IntoElement) -> Self {
1263 self.header_item(HeaderSlot::Title, "header-title", item)
1264 }
1265
1266 pub fn header(self, item: impl IntoElement) -> Self {
1270 self.header_item(HeaderSlot::Header, "header", item)
1271 }
1272
1273 pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1276 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1277 }
1278
1279 pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1282 self.listen(
1283 EventKind::BackRequest,
1284 listener.into_listener(),
1285 events::unit,
1286 )
1287 }
1288}
1289
1290impl Overlay {
1291 pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1295 let anchor = *anchor;
1296 self.bind_prop(
1297 move || match anchor.node() {
1298 Some(id) => OverlayAnchor::Node(id),
1299 None => OverlayAnchor::None,
1300 },
1301 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1302 )
1303 }
1304
1305 pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1311 let cover = *cover;
1312 self.bind_prop(
1313 move || if shown() { cover.node() } else { None },
1314 |id| Prop::Overlay(OverlayProp::Cover(id)),
1315 )
1316 }
1317
1318 pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1322 let (anchor, edges) = (*anchor, *edges);
1323 self.bind_prop(
1324 move || match (anchor.node(), edges.node()) {
1325 (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1326 (Some(id), None) => OverlayAnchor::Node(id),
1327 _ => OverlayAnchor::None,
1328 },
1329 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1330 )
1331 }
1332
1333 pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1339 let anchor = *anchor;
1340 self.bind_prop(
1341 move || match anchor.node() {
1342 Some(id) => OverlayAnchor::Content(id),
1343 None => OverlayAnchor::None,
1344 },
1345 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1346 )
1347 }
1348
1349 pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1352 self.bind_prop(point, |p| {
1353 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1354 })
1355 }
1356
1357 pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1361 self.bind_prop(bounds, |b| {
1362 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1363 })
1364 }
1365
1366 pub fn anchor_to(self, anchor: impl IntoReactive<OverlayAnchor>) -> Self {
1370 self.bind_prop(anchor, |a| Prop::Overlay(OverlayProp::Anchor(a)))
1371 }
1372
1373 pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1375 self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1376 }
1377
1378 pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1380 self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1381 }
1382
1383 pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1385 self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1386 }
1387
1388 pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1390 self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1391 }
1392
1393 pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1397 self.listen(
1398 EventKind::PressOutside,
1399 listener.into_listener(),
1400 events::page_point,
1401 )
1402 }
1403
1404 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1408 self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1409 }
1410
1411 pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1420 self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1421 }
1422
1423 pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1428 self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1429 }
1430
1431 pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1435 self.listen(
1436 EventKind::Show,
1437 listener.into_listener(),
1438 events::hint_reason,
1439 )
1440 }
1441
1442 pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1446 self.listen(
1447 EventKind::Dismiss,
1448 listener.into_listener(),
1449 events::hint_reason,
1450 )
1451 }
1452
1453 pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1456 self.listen(
1457 EventKind::Position,
1458 listener.into_listener(),
1459 events::overlay_position,
1460 )
1461 }
1462}
1463
1464impl Dialog {
1465 pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1467 self.bind_prop(animation, |animation: ModalAnimation| {
1468 Prop::Modal(ModalProp::Animation(animation))
1469 })
1470 }
1471
1472 pub fn transition_shader(
1476 self,
1477 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1478 ) -> Self {
1479 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1480 crate::shader::note_use();
1481 Prop::TransitionShader(s.map(Into::into))
1482 })
1483 }
1484
1485 pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1487 self.bind_prop(presentation, |presentation: ModalPresentation| {
1488 Prop::Modal(ModalProp::Presentation(presentation))
1489 })
1490 }
1491
1492 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1495 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1496 }
1497
1498 pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1500 self.bind_prop(translucent, |translucent: bool| {
1501 Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1502 })
1503 }
1504
1505 pub fn supported_orientations(
1508 self,
1509 orientations: impl IntoIterator<Item = Orientation>,
1510 ) -> Self {
1511 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1512 self.set(Prop::Modal(ModalProp::Orientations(bits)))
1513 }
1514
1515 pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1518 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1519 }
1520
1521 pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1525 self.bind_prop(close, |v: bool| {
1526 Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1527 })
1528 }
1529
1530 pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1532 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1533 }
1534
1535 pub fn detents(self, detents: impl IntoReactive<Vec<SheetDetent>>) -> Self {
1542 self.bind_prop(detents, |v: Vec<SheetDetent>| {
1543 Prop::Modal(ModalProp::Detents(v))
1544 })
1545 }
1546
1547 pub fn detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1552 self.bind_prop(detent, |v: Option<SheetDetent>| {
1553 Prop::Modal(ModalProp::Detent(v))
1554 })
1555 }
1556
1557 pub fn default_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1560 self.bind_prop(detent, |v: Option<SheetDetent>| {
1561 Prop::Modal(ModalProp::DefaultDetent(v))
1562 })
1563 }
1564
1565 pub fn grabber(self, grabber: impl IntoReactive<bool>) -> Self {
1567 self.bind_prop(grabber, |v: bool| Prop::Modal(ModalProp::Grabber(v)))
1568 }
1569
1570 pub fn largest_undimmed_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1573 self.bind_prop(detent, |v: Option<SheetDetent>| {
1574 Prop::Modal(ModalProp::LargestUndimmedDetent(v))
1575 })
1576 }
1577
1578 pub fn on_detent_change<M>(self, listener: impl IntoListener<SheetDetent, M>) -> Self {
1581 self.listen(
1582 EventKind::DetentChange,
1583 listener.into_listener(),
1584 events::sheet_detent,
1585 )
1586 }
1587
1588 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1592 self.listen(
1593 EventKind::RequestClose,
1594 listener.into_listener(),
1595 events::unit,
1596 )
1597 }
1598
1599 pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1601 self.listen(EventKind::Show, listener.into_listener(), events::unit)
1602 }
1603
1604 pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1606 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1607 }
1608}
1609
1610#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1612pub enum Orientation {
1613 Portrait,
1615 PortraitUpsideDown,
1617 Landscape,
1619 LandscapeLeft,
1623 LandscapeRight,
1627}
1628
1629impl Orientation {
1630 fn bits(self) -> u8 {
1631 use crate::ModalConfig as M;
1632 match self {
1633 Orientation::Portrait => M::PORTRAIT,
1634 Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1635 Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1636 Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1637 Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1638 }
1639 }
1640}
1641
1642impl WebView {
1643 pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1646 let base_url: Option<Arc<str>> = base_url.map(Into::into);
1647 self.bind_prop(html, move |html: String| {
1648 Prop::Native(NativeProp::Source(WebSource::Html {
1649 html: html.into(),
1650 base_url: base_url.clone(),
1651 }))
1652 })
1653 }
1654
1655 pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1657 self.bind_prop(script, |script: String| {
1658 Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1659 })
1660 }
1661
1662 pub fn allow_origin(self, origin: impl IntoReactive<String>) -> Self {
1669 self.bind_prop(origin, |origin: String| {
1670 Prop::Native(NativeProp::AllowOrigin(Some(origin.into())))
1671 })
1672 }
1673
1674 pub fn allow_navigation<S: Into<Arc<str>>>(self, hosts: impl IntoIterator<Item = S>) -> Self {
1681 let hosts = hosts.into_iter().map(Into::into).collect();
1682 self.set(Prop::Native(NativeProp::AllowNavigation(Some(hosts))))
1683 }
1684
1685 pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1687 self.bind_prop(script, |script: String| {
1688 Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1689 })
1690 }
1691
1692 pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1694 self.bind_prop(agent, |agent: String| {
1695 Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1696 })
1697 }
1698
1699 pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1701 self.bind_prop(enabled, |enabled: bool| {
1702 Prop::Native(NativeProp::Scrollable(enabled))
1703 })
1704 }
1705
1706 pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1708 self.bind_prop(enabled, |enabled: bool| {
1709 Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1710 })
1711 }
1712
1713 pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1715 self.bind_prop(enabled, |enabled: bool| {
1716 Prop::Native(NativeProp::BackForwardGestures(enabled))
1717 })
1718 }
1719
1720 pub fn incognito(self, incognito: bool) -> Self {
1725 self.set(Prop::Native(NativeProp::Incognito(incognito)))
1726 }
1727
1728 pub fn zoomable(self, zoomable: bool) -> Self {
1733 self.set(Prop::Native(NativeProp::Zoomable(zoomable)))
1734 }
1735
1736 pub fn url_scheme(
1752 self,
1753 scheme: &str,
1754 handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1755 ) -> Self {
1756 let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1757 Ok(scheme) => scheme,
1758 Err(e) => {
1759 log::warn!(target: "js", "web view: {e}");
1760 return self;
1761 }
1762 };
1763 let mut schemes = self
1764 .0
1765 .attrs
1766 .props
1767 .iter()
1768 .find_map(|p| match p {
1769 Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1770 _ => None,
1771 })
1772 .unwrap_or_default();
1773 schemes.retain(|s| s.scheme() != scheme.scheme());
1774 schemes.push(scheme);
1775 self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1776 }
1777
1778 pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1780 self.listen(
1781 EventKind::LoadStart,
1782 listener.into_listener(),
1783 events::navigation,
1784 )
1785 }
1786
1787 pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1789 self.listen(
1790 EventKind::Load,
1791 listener.into_listener(),
1792 events::navigation,
1793 )
1794 }
1795
1796 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1798 self.listen(EventKind::Error, listener.into_listener(), events::message)
1799 }
1800
1801 pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1807 self.listen(
1808 EventKind::Error,
1809 listener.into_listener(),
1810 events::unavailable,
1811 )
1812 }
1813
1814 pub fn on_process_terminated<M>(self, listener: impl IntoListener<str, M>) -> Self {
1820 self.listen(
1821 EventKind::Error,
1822 listener.into_listener(),
1823 events::terminated,
1824 )
1825 }
1826
1827 pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1829 self.listen(EventKind::Message, listener.into_listener(), events::data)
1830 }
1831
1832 pub fn on_navigation_state_change<M>(
1834 self,
1835 listener: impl IntoListener<WebNavigation, M>,
1836 ) -> Self {
1837 self.listen(
1838 EventKind::NavigationStateChange,
1839 listener.into_listener(),
1840 events::navigation,
1841 )
1842 }
1843
1844 pub fn on_download<M>(
1851 self,
1852 listener: impl IntoListener<crate::webview::WebDownload, M>,
1853 ) -> Self {
1854 self.listen(
1855 EventKind::Download,
1856 listener.into_listener(),
1857 events::web_download,
1858 )
1859 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1860 }
1861
1862 pub fn on_download_pending<M>(
1870 self,
1871 listener: impl IntoListener<crate::webview::WebDownloadPending, M>,
1872 ) -> Self {
1873 self.listen(
1874 EventKind::DownloadPending,
1875 listener.into_listener(),
1876 events::web_download_pending,
1877 )
1878 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1879 }
1880}
1881
1882impl Video {
1883 pub fn poster(self, url: impl IntoReactive<String>) -> Self {
1886 self.bind_prop(url, |url: String| {
1887 Prop::Native(NativeProp::Poster(Some(url.into())))
1888 })
1889 }
1890
1891 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1893 self.bind_prop(paused, |paused: bool| {
1894 Prop::Native(NativeProp::Paused(paused))
1895 })
1896 }
1897
1898 pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1900 self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1901 }
1902
1903 pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1905 self.bind_prop(volume, |volume: f32| {
1906 Prop::Native(NativeProp::Volume(volume))
1907 })
1908 }
1909
1910 pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1912 self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1913 }
1914
1915 pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1917 self.bind_prop(repeat, |repeat: bool| {
1918 Prop::Native(NativeProp::Repeat(repeat))
1919 })
1920 }
1921
1922 pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1924 self.bind_prop(controls, |controls: bool| {
1925 Prop::Native(NativeProp::Controls(controls))
1926 })
1927 }
1928
1929 pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1931 self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1932 }
1933
1934 pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1937 self.bind_prop(session, |session: AudioSession| {
1938 Prop::Native(NativeProp::AudioSession(session))
1939 })
1940 }
1941
1942 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1944 self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1945 }
1946
1947 pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1949 self.listen(EventKind::Load, listener.into_listener(), events::video)
1950 }
1951
1952 pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1954 self.listen(
1955 EventKind::Progress,
1956 listener.into_listener(),
1957 events::progress,
1958 )
1959 }
1960
1961 pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1963 self.listen(EventKind::End, listener.into_listener(), events::unit)
1964 }
1965
1966 pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1968 self.listen(
1969 EventKind::Buffer,
1970 listener.into_listener(),
1971 events::buffering,
1972 )
1973 }
1974
1975 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1977 self.listen(EventKind::Error, listener.into_listener(), events::message)
1978 }
1979}
1980
1981impl NativeView {
1982 pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1985 let name: Arc<str> = name.into();
1986 self.bind_prop(value, move |value| {
1987 Prop::ComponentProp(name.clone(), Some(value))
1988 })
1989 }
1990
1991 pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1997 if let Some(node) = value.animated_node().live() {
1998 set(
1999 &mut self.0,
2000 Prop::ComponentPropBinding(name.into(), Some(node.id())),
2001 );
2002 self.0.attrs.rare_mut().bound.push(node);
2003 }
2004 self
2005 }
2006
2007 pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
2009 self.listen(
2010 EventKind::NativeEvent,
2011 listener.into_listener(),
2012 events::native,
2013 )
2014 }
2015}
2016
2017impl GpuView {
2018 pub fn source(self, source: crate::gpu::GpuSource) -> Self {
2020 self.set(Prop::GpuRenderer(Some(source)))
2021 }
2022
2023 pub fn renderer_named(self, name: &str) -> Self {
2027 self.set(Prop::Component(name.into()))
2028 }
2029
2030 pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
2033 let name: Arc<str> = name.into();
2034 self.bind_prop(value, move |value| {
2035 Prop::ComponentProp(name.clone(), Some(value))
2036 })
2037 }
2038
2039 pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
2044 if let Some(node) = value.animated_node().live() {
2045 set(
2046 &mut self.0,
2047 Prop::ComponentPropBinding(name.into(), Some(node.id())),
2048 );
2049 self.0.attrs.rare_mut().bound.push(node);
2050 }
2051 self
2052 }
2053
2054 pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
2056 self.listen(
2057 EventKind::NativeEvent,
2058 listener.into_listener(),
2059 events::native,
2060 )
2061 }
2062}
2063
2064#[derive(Debug, Clone, PartialEq)]
2067pub struct CanvasArg(pub(crate) CanvasArgKind);
2068
2069#[derive(Debug, Clone, PartialEq)]
2070pub(crate) enum CanvasArgKind {
2071 Const(f32),
2072 Node(super::LiveNode),
2073}
2074
2075impl From<f32> for CanvasArg {
2076 fn from(n: f32) -> Self {
2077 Self(CanvasArgKind::Const(n))
2078 }
2079}
2080
2081impl From<Points> for CanvasArg {
2083 fn from(n: Points) -> Self {
2084 Self(CanvasArgKind::Const(n.0))
2085 }
2086}
2087
2088impl From<Point<Points>> for Point<CanvasArg> {
2089 fn from(point: Point<Points>) -> Self {
2090 point.map(Into::into)
2091 }
2092}
2093
2094impl From<Radians> for CanvasArg {
2096 fn from(n: Radians) -> Self {
2097 Self(CanvasArgKind::Const(n.0))
2098 }
2099}
2100
2101impl<A: super::Animated> From<&A> for CanvasArg {
2103 fn from(a: &A) -> Self {
2104 Self(match a.animated_node().live() {
2105 Some(node) => CanvasArgKind::Node(node),
2106 None => CanvasArgKind::Const(0.0),
2107 })
2108 }
2109}
2110
2111#[derive(Debug, Clone, PartialEq)]
2116pub struct CanvasPaint(CanvasPaintKind);
2117
2118#[derive(Debug, Clone, PartialEq)]
2119enum CanvasPaintKind {
2120 Color(Color),
2121 Gradient(Arc<CanvasGradient>),
2122 Node(super::LiveNode),
2123}
2124
2125impl From<Color> for CanvasPaint {
2126 fn from(color: Color) -> Self {
2127 Self(CanvasPaintKind::Color(color))
2128 }
2129}
2130
2131impl From<Hsla> for CanvasPaint {
2132 fn from(color: Hsla) -> Self {
2133 Color::from(color).into()
2134 }
2135}
2136
2137impl From<Rgba> for CanvasPaint {
2138 fn from(color: Rgba) -> Self {
2139 Color::from(color).into()
2140 }
2141}
2142
2143impl From<CanvasGradient> for CanvasPaint {
2144 fn from(gradient: CanvasGradient) -> Self {
2145 Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
2146 }
2147}
2148
2149impl From<Arc<CanvasGradient>> for CanvasPaint {
2150 fn from(gradient: Arc<CanvasGradient>) -> Self {
2151 Self(CanvasPaintKind::Gradient(gradient))
2152 }
2153}
2154
2155impl<A: super::Animated> From<&A> for CanvasPaint {
2157 fn from(a: &A) -> Self {
2158 Self(match a.animated_node().live() {
2159 Some(node) => CanvasPaintKind::Node(node),
2160 None => CanvasPaintKind::Color(Color::TRANSPARENT),
2161 })
2162 }
2163}
2164
2165#[derive(Debug, Clone, Default)]
2173pub struct Painter {
2174 drawing: Drawing,
2175 nodes: Vec<super::LiveNode>,
2177}
2178
2179impl Painter {
2180 pub fn new() -> Self {
2182 Self::default()
2183 }
2184
2185 pub fn finish(self) -> Drawing {
2187 self.drawing
2188 }
2189
2190 pub fn render(
2201 self,
2202 size: Size<Points>,
2203 options: crate::canvas::render::RenderOptions,
2204 ) -> crate::element::Answer<Result<Vec<u8>, crate::element::JsError>> {
2205 crate::element::ambient::render_canvas(crate::canvas::render::RenderRequest {
2206 drawing: self.drawing,
2207 size,
2208 scale: options.scale,
2209 format: options.format,
2210 })
2211 }
2212
2213 pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
2217 match value.into().0 {
2218 CanvasArgKind::Const(n) => Num::Const(n),
2219 CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
2220 }
2221 }
2222
2223 pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
2226 match paint.into().0 {
2227 CanvasPaintKind::Color(color) => Paint::Color(color),
2228 CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
2229 CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
2230 }
2231 }
2232
2233 fn slot(&mut self, node: super::LiveNode) -> u16 {
2234 let slot = self.drawing.slot(node.id());
2235 self.nodes.push(node);
2236 slot
2237 }
2238
2239 pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
2242 self.drawing.nodes.push(node);
2243 self
2244 }
2245
2246 pub fn op(mut self, op: CanvasOp) -> Self {
2249 self.drawing.ops.push(op);
2250 self
2251 }
2252
2253 fn path(self, op: PathOp) -> Self {
2254 self.op(CanvasOp::Path(op))
2255 }
2256
2257 pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
2264 crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
2265 }
2266
2267 pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
2271 crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
2272 }
2273
2274 pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
2279 crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
2280 }
2281
2282 pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
2286 crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
2287 }
2288
2289 pub fn save(self) -> Self {
2291 self.op(CanvasOp::Save)
2292 }
2293
2294 pub fn restore(self) -> Self {
2296 self.op(CanvasOp::Restore)
2297 }
2298
2299 pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2301 let (x, y) = (self.num(x), self.num(y));
2302 self.op(CanvasOp::Translate(x, y))
2303 }
2304
2305 pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2307 let (x, y) = (self.num(x), self.num(y));
2308 self.op(CanvasOp::Scale(x, y))
2309 }
2310
2311 pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
2314 let a = self.num(angle);
2315 self.op(CanvasOp::Rotate(a))
2316 }
2317
2318 pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2321 let m = m.map(|n| self.num(n));
2322 self.op(CanvasOp::Transform(m))
2323 }
2324
2325 pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2328 let m = m.map(|n| self.num(n));
2329 self.op(CanvasOp::SetTransform(m))
2330 }
2331
2332 pub fn reset_transform(self) -> Self {
2334 self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
2335 }
2336
2337 pub fn begin_path(self) -> Self {
2339 self.op(CanvasOp::BeginPath)
2340 }
2341
2342 pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2344 let (x, y) = (self.num(x), self.num(y));
2345 self.path(PathOp::MoveTo(x, y))
2346 }
2347
2348 pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2350 let (x, y) = (self.num(x), self.num(y));
2351 self.path(PathOp::LineTo(x, y))
2352 }
2353
2354 pub fn quadratic_curve_to(
2357 mut self,
2358 control: impl Into<Point<CanvasArg>>,
2359 to: impl Into<Point<CanvasArg>>,
2360 ) -> Self {
2361 let (control, to) = (control.into(), to.into());
2362 let coords = [control.x, control.y, to.x, to.y].map(|v| self.num(v));
2363 self.path(PathOp::QuadTo(coords))
2364 }
2365
2366 pub fn bezier_curve_to(
2369 mut self,
2370 c1: impl Into<Point<CanvasArg>>,
2371 c2: impl Into<Point<CanvasArg>>,
2372 to: impl Into<Point<CanvasArg>>,
2373 ) -> Self {
2374 let (c1, c2, to) = (c1.into(), c2.into(), to.into());
2375 let coords = [c1.x, c1.y, c2.x, c2.y, to.x, to.y].map(|v| self.num(v));
2376 self.path(PathOp::CubicTo(coords))
2377 }
2378
2379 pub fn arc(
2382 self,
2383 x: impl Into<CanvasArg>,
2384 y: impl Into<CanvasArg>,
2385 radius: impl Into<CanvasArg>,
2386 start: impl Into<CanvasArg>,
2387 end: impl Into<CanvasArg>,
2388 ) -> Self {
2389 self.arc_in(x, y, radius, start, end, false)
2390 }
2391
2392 pub fn arc_counterclockwise(
2394 self,
2395 x: impl Into<CanvasArg>,
2396 y: impl Into<CanvasArg>,
2397 radius: impl Into<CanvasArg>,
2398 start: impl Into<CanvasArg>,
2399 end: impl Into<CanvasArg>,
2400 ) -> Self {
2401 self.arc_in(x, y, radius, start, end, true)
2402 }
2403
2404 fn arc_in(
2405 mut self,
2406 x: impl Into<CanvasArg>,
2407 y: impl Into<CanvasArg>,
2408 radius: impl Into<CanvasArg>,
2409 start: impl Into<CanvasArg>,
2410 end: impl Into<CanvasArg>,
2411 ccw: bool,
2412 ) -> Self {
2413 let (x, y, radius, start, end) = (
2414 self.num(x),
2415 self.num(y),
2416 self.num(radius),
2417 self.num(start),
2418 self.num(end),
2419 );
2420 self.path(PathOp::Arc {
2421 x,
2422 y,
2423 radius,
2424 start,
2425 end,
2426 ccw,
2427 })
2428 }
2429
2430 pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2433 let c = |v: Points| Num::Const(v.0);
2434 self.path(PathOp::ArcTo([
2435 c(p1.x),
2436 c(p1.y),
2437 c(p2.x),
2438 c(p2.y),
2439 c(radius),
2440 ]))
2441 }
2442
2443 pub fn ellipse(
2447 self,
2448 center: Point<Points>,
2449 radii: Size<Points>,
2450 rotation: Radians,
2451 start: Radians,
2452 end: Radians,
2453 counterclockwise: bool,
2454 ) -> Self {
2455 let c = Num::Const;
2456 self.path(PathOp::Ellipse {
2457 geometry: [
2458 c(center.x.0),
2459 c(center.y.0),
2460 c(radii.width.0),
2461 c(radii.height.0),
2462 c(rotation.0),
2463 ],
2464 start: c(start.0),
2465 end: c(end.0),
2466 ccw: counterclockwise,
2467 })
2468 }
2469
2470 pub fn rect(self, rect: Bounds<Points>) -> Self {
2472 self.path(PathOp::Rect(nums(rect)))
2473 }
2474
2475 pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2477 self.round_rect_corners(rect, Corners::all(radius))
2478 }
2479
2480 pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2482 let c = |v: Points| Num::Const(v.0);
2483 self.path(PathOp::RoundRect(
2484 nums(rect),
2485 [
2486 c(radii.top_left),
2487 c(radii.top_right),
2488 c(radii.bottom_right),
2489 c(radii.bottom_left),
2490 ],
2491 ))
2492 }
2493
2494 pub fn close_path(self) -> Self {
2496 self.path(PathOp::Close)
2497 }
2498
2499 pub fn fill(self) -> Self {
2501 self.fill_with(FillRule::NonZero)
2502 }
2503
2504 pub fn fill_with(self, rule: FillRule) -> Self {
2506 self.op(CanvasOp::Fill(None, rule))
2507 }
2508
2509 pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2512 self.op(CanvasOp::Fill(Some(path.clone()), rule))
2513 }
2514
2515 pub fn fill_svg(self, data: &str) -> Self {
2518 self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2519 }
2520
2521 pub fn stroke(self) -> Self {
2523 self.op(CanvasOp::Stroke(None))
2524 }
2525
2526 pub fn stroke_path(self, path: &Path) -> Self {
2528 self.op(CanvasOp::Stroke(Some(path.clone())))
2529 }
2530
2531 pub fn stroke_svg(self, data: &str) -> Self {
2533 self.stroke_path(&crate::canvas::svg_path(data))
2534 }
2535
2536 pub fn clip(self) -> Self {
2538 self.clip_with(FillRule::NonZero)
2539 }
2540
2541 pub fn clip_with(self, rule: FillRule) -> Self {
2543 self.op(CanvasOp::Clip(None, rule))
2544 }
2545
2546 pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2548 self.op(CanvasOp::Clip(Some(path.clone()), rule))
2549 }
2550
2551 pub fn fill_rect(
2553 mut self,
2554 x: impl Into<CanvasArg>,
2555 y: impl Into<CanvasArg>,
2556 w: impl Into<CanvasArg>,
2557 h: impl Into<CanvasArg>,
2558 ) -> Self {
2559 let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2560 self.op(CanvasOp::FillRect([x, y, w, h]))
2561 }
2562
2563 pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2565 self.op(CanvasOp::StrokeRect(nums(rect)))
2566 }
2567
2568 pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2570 self.op(CanvasOp::ClearRect(nums(rect)))
2571 }
2572
2573 pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2575 self.fill_style(color.into())
2576 }
2577
2578 pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2580 self.stroke_style(color.into())
2581 }
2582
2583 pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2586 let paint = self.paint(paint);
2587 self.op(CanvasOp::FillStyle(paint))
2588 }
2589
2590 pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2596 self.view_paint(
2597 ViewPaint::Fill(initial),
2598 CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2599 )
2600 }
2601
2602 pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2605 self.view_paint(
2606 ViewPaint::Stroke(initial),
2607 CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2608 )
2609 }
2610
2611 pub fn line_width_from_view(self) -> Self {
2614 self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2615 }
2616
2617 pub fn line_dash_from_view(self) -> Self {
2620 self.view_paint(
2621 ViewPaint::StrokeDasharray,
2622 CanvasOp::LineDash(Arc::from([])),
2623 )
2624 }
2625
2626 pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2635 self.view_paint(
2636 ViewPaint::Background {
2637 area,
2638 rule: FillRule::NonZero,
2639 },
2640 CanvasOp::Fill(None, FillRule::NonZero),
2641 )
2642 }
2643
2644 fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2645 let at = self.drawing.ops.len() as u32;
2646 self.drawing.view_paints.push((at, view));
2647 self.op(placeholder)
2648 }
2649
2650 pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2652 let paint = self.paint(paint);
2653 self.op(CanvasOp::StrokeStyle(paint))
2654 }
2655
2656 pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2658 let w = self.num(width);
2659 self.op(CanvasOp::LineWidth(w))
2660 }
2661
2662 pub fn line_cap(self, cap: LineCap) -> Self {
2664 self.op(CanvasOp::LineCap(cap))
2665 }
2666
2667 pub fn line_join(self, join: LineJoin) -> Self {
2669 self.op(CanvasOp::LineJoin(join))
2670 }
2671
2672 pub fn miter_limit(self, limit: f32) -> Self {
2675 self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2676 }
2677
2678 pub fn line_dash(self, segments: &[Points]) -> Self {
2680 self.op(CanvasOp::LineDash(segments.into()))
2681 }
2682
2683 pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2686 let o = self.num(offset);
2687 self.op(CanvasOp::LineDashOffset(o))
2688 }
2689
2690 pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2692 let a = self.num(alpha);
2693 self.op(CanvasOp::GlobalAlpha(a))
2694 }
2695
2696 pub fn composite(self, composite: Composite) -> Self {
2698 self.op(CanvasOp::Composite(composite))
2699 }
2700
2701 pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2703 self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2704 .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2705 .op(CanvasOp::ShadowOffset(offset))
2706 }
2707
2708 pub fn font(self, font: &str) -> Self {
2711 match CanvasFont::parse(font) {
2712 Some(font) => self.op(CanvasOp::Font(font)),
2713 None => self,
2714 }
2715 }
2716
2717 pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2721 self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2722 numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2723 )))
2724 }
2725
2726 pub fn text_align(self, align: CanvasTextAlign) -> Self {
2728 self.op(CanvasOp::TextAlign(align))
2729 }
2730
2731 pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2733 self.op(CanvasOp::TextBaseline(baseline))
2734 }
2735
2736 pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2738 self.text(text, x, y, None, false)
2739 }
2740
2741 pub fn fill_text_max_width(
2743 self,
2744 text: &str,
2745 x: impl Into<CanvasArg>,
2746 y: impl Into<CanvasArg>,
2747 max_width: Points,
2748 ) -> Self {
2749 self.text(text, x, y, Some(max_width), false)
2750 }
2751
2752 pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2754 self.text(text, x, y, None, true)
2755 }
2756
2757 pub fn stroke_text_max_width(
2760 self,
2761 text: &str,
2762 x: impl Into<CanvasArg>,
2763 y: impl Into<CanvasArg>,
2764 max_width: Points,
2765 ) -> Self {
2766 self.text(text, x, y, Some(max_width), true)
2767 }
2768
2769 fn text(
2770 mut self,
2771 text: &str,
2772 x: impl Into<CanvasArg>,
2773 y: impl Into<CanvasArg>,
2774 max_width: Option<Points>,
2775 stroke: bool,
2776 ) -> Self {
2777 let (text, x, y) = (text.into(), self.num(x), self.num(y));
2778 self.op(if stroke {
2779 CanvasOp::StrokeText {
2780 text,
2781 x,
2782 y,
2783 max_width,
2784 }
2785 } else {
2786 CanvasOp::FillText {
2787 text,
2788 x,
2789 y,
2790 max_width,
2791 }
2792 })
2793 }
2794
2795 pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2797 self.draw_image_part(uri, None, dest)
2798 }
2799
2800 pub fn draw_image_part(
2803 self,
2804 uri: &str,
2805 source: Option<Bounds<ScaledPixels>>,
2806 dest: Bounds<Points>,
2807 ) -> Self {
2808 self.op(CanvasOp::DrawImage {
2809 image: CanvasImage { uri: uri.into() },
2810 source,
2811 dest: nums(dest),
2812 })
2813 }
2814}
2815
2816fn nums(rect: Bounds<Points>) -> [Num; 4] {
2818 [
2819 rect.origin.x,
2820 rect.origin.y,
2821 rect.size.width,
2822 rect.size.height,
2823 ]
2824 .map(|v| Num::Const(v.0))
2825}
2826
2827impl From<Drawing> for Painter {
2828 fn from(drawing: Drawing) -> Self {
2829 Self {
2830 drawing,
2831 nodes: Vec::new(),
2832 }
2833 }
2834}
2835
2836crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2837crate::static_reactive!(HeaderTitleAlign: HeaderTitleAlign);
2838
2839impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2841 fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2842 super::Reactive::Static(Some(self))
2843 }
2844}
2845
2846impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2848 fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2849 super::Reactive::Static(Some(self))
2850 }
2851}
2852
2853impl IntoReactive<Option<crate::WindowsBackdrop>> for crate::WindowsBackdrop {
2855 fn into_reactive(self) -> super::Reactive<Option<crate::WindowsBackdrop>> {
2856 super::Reactive::Static(Some(self))
2857 }
2858}
2859
2860#[cfg(test)]
2861mod tests {
2862 use super::*;
2863 use crate::{
2864 element::{
2865 AnimatedValue,
2866 reactive::{Runtime, create_root, signal},
2867 },
2868 geometry::{point, px},
2869 shader::{ShaderUniforms, UniformValue},
2870 };
2871
2872 #[test]
2873 fn curves_accept_point_literals_and_record_constant_coordinates() {
2874 use Num::Const;
2875
2876 let drawing = Painter::new()
2877 .quadratic_curve_to(point(px(1.0), px(2.0)), point(px(3.0), px(4.0)))
2878 .bezier_curve_to(
2879 point(px(5.0), px(6.0)),
2880 point(px(7.0), px(8.0)),
2881 point(px(9.0), px(10.0)),
2882 )
2883 .finish();
2884
2885 assert!(drawing.slots.is_empty());
2886 assert_eq!(
2887 drawing.ops,
2888 [
2889 CanvasOp::Path(PathOp::QuadTo([1.0, 2.0, 3.0, 4.0].map(Const))),
2890 CanvasOp::Path(PathOp::CubicTo([5.0, 6.0, 7.0, 8.0, 9.0, 10.0].map(Const))),
2891 ]
2892 );
2893 }
2894
2895 #[test]
2896 fn curves_share_animation_slots_across_control_points_and_endpoints() {
2897 use Num::{Const, Slot};
2898
2899 let runtime = Runtime::default();
2900 let _entered = runtime.enter();
2901 let executor = std::rc::Rc::new(super::super::task::Executor::default());
2902 let (_owner, (x, y)) = create_root(|| {
2903 (
2904 AnimatedValue::new(&executor, 10.0),
2905 AnimatedValue::new(&executor, 20.0),
2906 )
2907 });
2908 let drawing = Painter::new()
2909 .quadratic_curve_to(
2910 point(CanvasArg::from(&x), 2.0.into()),
2911 point(3.0.into(), CanvasArg::from(&y)),
2912 )
2913 .bezier_curve_to(
2914 point(CanvasArg::from(&y), 6.0.into()),
2915 point(7.0.into(), CanvasArg::from(&x)),
2916 point(CanvasArg::from(&y), 10.0.into()),
2917 )
2918 .finish();
2919
2920 assert_eq!(drawing.slots, [x.node().id(), y.node().id()]);
2921 assert_eq!(
2922 drawing.ops,
2923 [
2924 CanvasOp::Path(PathOp::QuadTo([Slot(0), Const(2.0), Const(3.0), Slot(1)])),
2925 CanvasOp::Path(PathOp::CubicTo([
2926 Slot(1),
2927 Const(6.0),
2928 Const(7.0),
2929 Slot(0),
2930 Slot(1),
2931 Const(10.0),
2932 ])),
2933 ]
2934 );
2935 }
2936
2937 fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2938 attrs
2939 .props
2940 .iter()
2941 .find_map(|p| match p {
2942 Prop::Uniforms(u) => Some(u.clone()),
2943 _ => None,
2944 })
2945 .unwrap_or_default()
2946 }
2947
2948 fn released(executor: &super::super::task::Executor) -> usize {
2950 executor
2951 .take_actions()
2952 .into_iter()
2953 .filter(|a| {
2954 matches!(
2955 a,
2956 super::super::task::Action::Animation(
2957 crate::animation::AnimationOp::Release { .. }
2958 )
2959 )
2960 })
2961 .count()
2962 }
2963
2964 fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2965 u.0.iter()
2966 .find(|(n, _)| &**n == name)
2967 .map(|(_, v)| v.clone())
2968 }
2969
2970 #[test]
2971 fn screens_and_modals_take_a_transition_shader() {
2972 let runtime = Runtime::default();
2973 let _entered = runtime.enter();
2974 let source = "struct Uniforms { edge: f32 }\n\
2975 fn shade(uv: vec2f) -> vec4f {\n \
2976 return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2977 let shader = crate::shader::Shader::compile(source).expect("compiles");
2978 let wipe = crate::shader::TransitionShader::new(shader)
2979 .uniform("edge", 1.0_f32)
2980 .duration(std::time::Duration::from_millis(400));
2981 let expected = crate::shader::NavShaderSpec {
2982 source: source.into(),
2983 uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2984 duration: Some(400.0),
2985 };
2986 let spec = |attrs: &super::super::builder::Attrs| {
2987 attrs.props.iter().find_map(|p| match p {
2988 Prop::TransitionShader(s) => Some(s.clone()),
2989 _ => None,
2990 })
2991 };
2992 let page = screen().transition_shader(wipe.clone()).0;
2993 assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2994 let dialog = modal().transition_shader(wipe.clone()).0;
2995 assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2996 let on = signal(true);
2998 let bound = screen()
2999 .transition_shader(move || on.get().then(|| wipe.clone()))
3000 .0;
3001 assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
3002 on.set(false);
3003 assert_eq!(spec(&bound.resolved_attrs()), Some(None));
3004 }
3005
3006 #[test]
3007 fn uniform_takes_static_bound_and_animated_values() {
3008 let runtime = Runtime::default();
3009 let _entered = runtime.enter();
3010 let executor = std::rc::Rc::new(super::super::task::Executor::default());
3011 let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
3012 let speed = signal(1.0_f32);
3013 let view = shader()
3014 .uniform("center", [0.5_f32, 0.5])
3015 .uniform("wave", &wave)
3016 .uniform("speed", move || speed.get());
3017 let node = view.0;
3018
3019 let set = uniforms(&node.attrs);
3022 assert_eq!(
3023 value(&set, "center"),
3024 Some(UniformValue::List(vec![
3025 UniformValue::Number(0.5),
3026 UniformValue::Number(0.5)
3027 ]))
3028 );
3029 let id = wave.node().live().expect("live").id();
3030 assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
3031 assert_eq!(
3032 node.attrs.bound().len(),
3033 1,
3034 "the element holds the animated node"
3035 );
3036 assert_eq!(
3037 value(&set, "speed"),
3038 None,
3039 "a bound one is applied when resolved"
3040 );
3041
3042 assert_eq!(
3044 value(&uniforms(&node.resolved_attrs()), "speed"),
3045 Some(UniformValue::Number(1.0))
3046 );
3047 speed.set(2.0);
3048 assert_eq!(
3049 value(&uniforms(&node.resolved_attrs()), "speed"),
3050 Some(UniformValue::Number(2.0))
3051 );
3052
3053 value_owner.dispose();
3055 assert_eq!(released(&executor), 0, "the view keeps the animated node");
3056 drop(node);
3057 assert_eq!(released(&executor), 1, "and lets it go with the view");
3058 }
3059
3060 #[test]
3061 fn a_later_uniform_replaces_one_of_the_same_name() {
3062 let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
3063 let set = uniforms(&view.0.attrs);
3064 assert_eq!(set.0.len(), 1);
3065 assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
3066 }
3067
3068 #[test]
3069 fn web_view_url_scheme_builder_collects_schemes() {
3070 let web = web_view_html("<img src=\"a:1\">", None)
3071 .url_scheme("a", |request| request.fail())
3072 .url_scheme("b", |request| request.fail())
3073 .url_scheme("A", |request| request.fail())
3075 .url_scheme("https", |request| request.fail());
3077 let schemes: Vec<String> = web
3078 .0
3079 .attrs
3080 .props
3081 .iter()
3082 .find_map(|p| match p {
3083 Prop::Native(NativeProp::UrlSchemes(list)) => {
3084 Some(list.iter().map(|s| s.scheme().to_owned()).collect())
3085 }
3086 _ => None,
3087 })
3088 .unwrap();
3089 assert_eq!(schemes, ["b", "a"]);
3090 }
3091}