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 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, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
781 self.bind_prop(setting, Prop::Scrollbar)
782 }
783
784 pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
789 self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
790 }
791
792 pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
794 self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
795 }
796
797 pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
800 self.bind_prop(behavior, |behavior: SubmitBehavior| {
801 Prop::SubmitBehavior(Some(behavior))
802 })
803 }
804
805 pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
808 self.bind_prop(behavior, Prop::PasteBehavior)
809 }
810
811 pub fn paste_max_size(self, bytes: impl IntoReactive<u64>) -> Self {
816 self.bind_prop(bytes, |bytes: u64| Prop::PasteMaxSize(Some(bytes)))
817 }
818
819 pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
823 self.listen(EventKind::Paste, listener.into_listener(), events::paste)
824 }
825
826 pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
828 self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
829 }
830
831 pub fn select_text_on_focus(self, select: impl IntoReactive<bool>) -> Self {
835 self.bind_prop(select, |select: bool| Prop::SelectTextOnFocus(select))
836 }
837
838 pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
840 self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
841 }
842
843 pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
846 self.bind_prop(native_id, |id: String| {
847 Prop::InputAccessoryViewId(Some(id.into()))
848 })
849 }
850
851 pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
856 self.bind_prop(range, |(start, end): (u32, u32)| {
857 Prop::Selection(start, end)
858 })
859 }
860
861 pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
863 self.listen(
864 EventKind::ChangeText,
865 listener.into_listener(),
866 events::text,
867 )
868 }
869
870 pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
872 self.listen(
873 EventKind::SubmitEditing,
874 listener.into_listener(),
875 events::text,
876 )
877 }
878
879 pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
881 self.listen(
882 EventKind::SelectionChange,
883 listener.into_listener(),
884 events::selection,
885 )
886 }
887
888 pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
892 self.listen(
893 EventKind::CaretMove,
894 listener.into_listener(),
895 events::caret,
896 )
897 }
898
899 pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
902 self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
903 }
904
905 pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
909 self.listen(
910 EventKind::CompositionChange,
911 listener.into_listener(),
912 events::composition,
913 )
914 }
915
916 pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
918 self.listen(
919 EventKind::ContentSizeChange,
920 listener.into_listener(),
921 events::size,
922 )
923 }
924}
925
926impl Scroll {
927 pub fn horizontal(self) -> Self {
929 self.set(Prop::Horizontal(true))
930 }
931
932 pub fn scrollbar(self, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
936 self.bind_prop(setting, Prop::Scrollbar)
937 }
938
939 pub fn zoom_range(self, min: f32, max: f32) -> Self {
941 self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
942 .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
943 }
944
945 pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
947 self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
948 }
949
950 pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
953 self.bind_prop(bounces, |bounces: bool| {
954 Prop::Scroll(ScrollProp::BouncesZoom(bounces))
955 })
956 }
957
958 pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
960 self.bind_prop(enabled, |enabled: bool| {
961 Prop::Scroll(ScrollProp::Pinch(enabled))
962 })
963 }
964
965 pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
967 self.bind_prop(center, |center: bool| {
968 Prop::Scroll(ScrollProp::CenterContent(center))
969 })
970 }
971}
972
973impl super::Scrollable for Scroll {}
974
975impl Screen {
976 fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
977 let mut node = ElNode::new(Tag::HeaderItem);
978 node.key = Some(key.into());
979 set(&mut node, Prop::HeaderSlot(slot));
980 node.children.push(item.into_element().0);
981 self.0.children.push(node);
982 self
983 }
984
985 pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
987 self.bind_prop(title, |t| {
988 Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
989 })
990 }
991
992 pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
994 self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
995 }
996
997 pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
1000 self.bind_prop(hides, |v| {
1001 Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
1002 })
1003 }
1004
1005 pub fn supported_orientations(
1009 self,
1010 orientations: impl IntoIterator<Item = Orientation>,
1011 ) -> Self {
1012 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1013 self.set(Prop::Screen(ScreenProp::Orientations(bits)))
1014 }
1015
1016 pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
1018 self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
1019 }
1020
1021 pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
1023 self.bind_prop(transparent, |v| {
1024 Prop::Screen(ScreenProp::HeaderTransparent(v))
1025 })
1026 }
1027
1028 pub fn header_shadow_visible(self, visible: impl IntoReactive<bool>) -> Self {
1032 self.bind_prop(visible, |v| {
1033 Prop::Screen(ScreenProp::HeaderShadowVisible(v))
1034 })
1035 }
1036
1037 pub fn header_title_align(self, align: impl IntoReactive<HeaderTitleAlign>) -> Self {
1041 self.bind_prop(align, |a| Prop::Screen(ScreenProp::HeaderTitleAlign(a)))
1042 }
1043
1044 pub fn header_background_on_scroll(self, on: impl IntoReactive<bool>) -> Self {
1050 self.bind_prop(on, |v| {
1051 Prop::Screen(ScreenProp::HeaderBackgroundOnScroll(v))
1052 })
1053 }
1054
1055 pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
1060 let style = match style.into_reactive() {
1061 super::Reactive::Static(s) if s.1.is_bound() => {
1063 super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
1064 }
1065 style => style,
1066 };
1067 self.0.bind_attr(style, |a, s: super::Style| {
1068 set_in(&mut a.props, Prop::HeaderStyle(s.0));
1069 if !s.1.is_empty() {
1070 let typed = s.1.resolved();
1071 let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
1072 set_in(&mut a.props, Prop::HeaderClassList(list));
1073 }
1074 });
1075 self
1076 }
1077
1078 pub fn header_style_with(
1085 self,
1086 f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1087 ) -> Self {
1088 let list = move || {
1089 let style = f(super::StyleRefinement::default()).resolved();
1090 (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1091 };
1092 self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1093 Prop::HeaderClassList(list)
1094 })
1095 }
1096
1097 pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1099 self.bind_prop(title, |t| {
1100 Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1101 })
1102 }
1103
1104 pub fn header_right_system_item(
1108 self,
1109 item: impl IntoReactive<crate::HeaderSystemItem>,
1110 ) -> Self {
1111 self.bind_prop(item, |item| {
1112 Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1113 })
1114 }
1115
1116 pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1120 self.bind_prop(item, |item| {
1121 Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1122 })
1123 }
1124
1125 pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1129 self.bind_prop(name, |n| {
1130 Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1131 })
1132 }
1133
1134 pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1138 self.bind_prop(name, |n| {
1139 Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1140 })
1141 }
1142
1143 pub fn header_right_items(
1151 self,
1152 items: impl IntoReactive<Vec<super::header::HeaderItem>>,
1153 ) -> Self {
1154 self.bind_prop(items, |items| {
1155 Prop::Screen(ScreenProp::HeaderRightItems(super::header::register(items)))
1156 })
1157 }
1158
1159 pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1161 self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1162 }
1163
1164 pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1167 self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1168 }
1169
1170 pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1174 self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1175 }
1176
1177 pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1179 self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1180 }
1181
1182 pub fn transition_shader(
1186 self,
1187 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1188 ) -> Self {
1189 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1190 Prop::TransitionShader(s.map(Into::into))
1191 })
1192 }
1193
1194 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1198 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1199 }
1200
1201 pub fn header_left(self, item: impl IntoElement) -> Self {
1203 self.header_item(HeaderSlot::Left, "header-left", item)
1204 }
1205
1206 pub fn header_right(self, item: impl IntoElement) -> Self {
1208 self.header_item(HeaderSlot::Right, "header-right", item)
1209 }
1210
1211 pub fn header_title(self, item: impl IntoElement) -> Self {
1213 self.header_item(HeaderSlot::Title, "header-title", item)
1214 }
1215
1216 pub fn header(self, item: impl IntoElement) -> Self {
1220 self.header_item(HeaderSlot::Header, "header", item)
1221 }
1222
1223 pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1226 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1227 }
1228
1229 pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1232 self.listen(
1233 EventKind::BackRequest,
1234 listener.into_listener(),
1235 events::unit,
1236 )
1237 }
1238}
1239
1240impl Overlay {
1241 pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1245 let anchor = *anchor;
1246 self.bind_prop(
1247 move || match anchor.node() {
1248 Some(id) => OverlayAnchor::Node(id),
1249 None => OverlayAnchor::None,
1250 },
1251 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1252 )
1253 }
1254
1255 pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1261 let cover = *cover;
1262 self.bind_prop(
1263 move || if shown() { cover.node() } else { None },
1264 |id| Prop::Overlay(OverlayProp::Cover(id)),
1265 )
1266 }
1267
1268 pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1272 let (anchor, edges) = (*anchor, *edges);
1273 self.bind_prop(
1274 move || match (anchor.node(), edges.node()) {
1275 (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1276 (Some(id), None) => OverlayAnchor::Node(id),
1277 _ => OverlayAnchor::None,
1278 },
1279 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1280 )
1281 }
1282
1283 pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1289 let anchor = *anchor;
1290 self.bind_prop(
1291 move || match anchor.node() {
1292 Some(id) => OverlayAnchor::Content(id),
1293 None => OverlayAnchor::None,
1294 },
1295 |a| Prop::Overlay(OverlayProp::Anchor(a)),
1296 )
1297 }
1298
1299 pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1302 self.bind_prop(point, |p| {
1303 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1304 })
1305 }
1306
1307 pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1311 self.bind_prop(bounds, |b| {
1312 Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1313 })
1314 }
1315
1316 pub fn anchor_to(self, anchor: impl IntoReactive<OverlayAnchor>) -> Self {
1320 self.bind_prop(anchor, |a| Prop::Overlay(OverlayProp::Anchor(a)))
1321 }
1322
1323 pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1325 self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1326 }
1327
1328 pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1330 self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1331 }
1332
1333 pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1335 self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1336 }
1337
1338 pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1340 self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1341 }
1342
1343 pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1347 self.listen(
1348 EventKind::PressOutside,
1349 listener.into_listener(),
1350 events::page_point,
1351 )
1352 }
1353
1354 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1358 self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1359 }
1360
1361 pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1370 self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1371 }
1372
1373 pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1378 self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1379 }
1380
1381 pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1385 self.listen(
1386 EventKind::Show,
1387 listener.into_listener(),
1388 events::hint_reason,
1389 )
1390 }
1391
1392 pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1396 self.listen(
1397 EventKind::Dismiss,
1398 listener.into_listener(),
1399 events::hint_reason,
1400 )
1401 }
1402
1403 pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1406 self.listen(
1407 EventKind::Position,
1408 listener.into_listener(),
1409 events::overlay_position,
1410 )
1411 }
1412}
1413
1414impl Modal {
1415 pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1417 self.bind_prop(animation, |animation: ModalAnimation| {
1418 Prop::Modal(ModalProp::Animation(animation))
1419 })
1420 }
1421
1422 pub fn transition_shader(
1426 self,
1427 shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1428 ) -> Self {
1429 self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1430 Prop::TransitionShader(s.map(Into::into))
1431 })
1432 }
1433
1434 pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1436 self.bind_prop(presentation, |presentation: ModalPresentation| {
1437 Prop::Modal(ModalProp::Presentation(presentation))
1438 })
1439 }
1440
1441 pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1444 self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1445 }
1446
1447 pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1449 self.bind_prop(translucent, |translucent: bool| {
1450 Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1451 })
1452 }
1453
1454 pub fn supported_orientations(
1457 self,
1458 orientations: impl IntoIterator<Item = Orientation>,
1459 ) -> Self {
1460 let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1461 self.set(Prop::Modal(ModalProp::Orientations(bits)))
1462 }
1463
1464 pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1467 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1468 }
1469
1470 pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1474 self.bind_prop(close, |v: bool| {
1475 Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1476 })
1477 }
1478
1479 pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1481 self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1482 }
1483
1484 pub fn detents(self, detents: impl IntoReactive<Vec<SheetDetent>>) -> Self {
1491 self.bind_prop(detents, |v: Vec<SheetDetent>| {
1492 Prop::Modal(ModalProp::Detents(v))
1493 })
1494 }
1495
1496 pub fn detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1501 self.bind_prop(detent, |v: Option<SheetDetent>| {
1502 Prop::Modal(ModalProp::Detent(v))
1503 })
1504 }
1505
1506 pub fn default_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1509 self.bind_prop(detent, |v: Option<SheetDetent>| {
1510 Prop::Modal(ModalProp::DefaultDetent(v))
1511 })
1512 }
1513
1514 pub fn grabber(self, grabber: impl IntoReactive<bool>) -> Self {
1516 self.bind_prop(grabber, |v: bool| Prop::Modal(ModalProp::Grabber(v)))
1517 }
1518
1519 pub fn largest_undimmed_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1522 self.bind_prop(detent, |v: Option<SheetDetent>| {
1523 Prop::Modal(ModalProp::LargestUndimmedDetent(v))
1524 })
1525 }
1526
1527 pub fn on_detent_change<M>(self, listener: impl IntoListener<SheetDetent, M>) -> Self {
1530 self.listen(
1531 EventKind::DetentChange,
1532 listener.into_listener(),
1533 events::sheet_detent,
1534 )
1535 }
1536
1537 pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1541 self.listen(
1542 EventKind::RequestClose,
1543 listener.into_listener(),
1544 events::unit,
1545 )
1546 }
1547
1548 pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1550 self.listen(EventKind::Show, listener.into_listener(), events::unit)
1551 }
1552
1553 pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1555 self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1556 }
1557}
1558
1559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1561pub enum Orientation {
1562 Portrait,
1564 PortraitUpsideDown,
1566 Landscape,
1568 LandscapeLeft,
1572 LandscapeRight,
1576}
1577
1578impl Orientation {
1579 fn bits(self) -> u8 {
1580 use crate::ModalConfig as M;
1581 match self {
1582 Orientation::Portrait => M::PORTRAIT,
1583 Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1584 Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1585 Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1586 Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1587 }
1588 }
1589}
1590
1591impl WebView {
1592 pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1595 let base_url: Option<Arc<str>> = base_url.map(Into::into);
1596 self.bind_prop(html, move |html: String| {
1597 Prop::Native(NativeProp::Source(WebSource::Html {
1598 html: html.into(),
1599 base_url: base_url.clone(),
1600 }))
1601 })
1602 }
1603
1604 pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1606 self.bind_prop(script, |script: String| {
1607 Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1608 })
1609 }
1610
1611 pub fn allow_origin(self, origin: impl IntoReactive<String>) -> Self {
1618 self.bind_prop(origin, |origin: String| {
1619 Prop::Native(NativeProp::AllowOrigin(Some(origin.into())))
1620 })
1621 }
1622
1623 pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1625 self.bind_prop(script, |script: String| {
1626 Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1627 })
1628 }
1629
1630 pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1632 self.bind_prop(agent, |agent: String| {
1633 Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1634 })
1635 }
1636
1637 pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1639 self.bind_prop(enabled, |enabled: bool| {
1640 Prop::Native(NativeProp::Scrollable(enabled))
1641 })
1642 }
1643
1644 pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1646 self.bind_prop(enabled, |enabled: bool| {
1647 Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1648 })
1649 }
1650
1651 pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1653 self.bind_prop(enabled, |enabled: bool| {
1654 Prop::Native(NativeProp::BackForwardGestures(enabled))
1655 })
1656 }
1657
1658 pub fn incognito(self, incognito: bool) -> Self {
1663 self.set(Prop::Native(NativeProp::Incognito(incognito)))
1664 }
1665
1666 pub fn zoomable(self, zoomable: bool) -> Self {
1671 self.set(Prop::Native(NativeProp::Zoomable(zoomable)))
1672 }
1673
1674 pub fn url_scheme(
1689 self,
1690 scheme: &str,
1691 handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1692 ) -> Self {
1693 let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1694 Ok(scheme) => scheme,
1695 Err(e) => {
1696 log::warn!(target: "js", "web view: {e}");
1697 return self;
1698 }
1699 };
1700 let mut schemes = self
1701 .0
1702 .attrs
1703 .props
1704 .iter()
1705 .find_map(|p| match p {
1706 Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1707 _ => None,
1708 })
1709 .unwrap_or_default();
1710 schemes.retain(|s| s.scheme() != scheme.scheme());
1711 schemes.push(scheme);
1712 self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1713 }
1714
1715 pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1717 self.listen(
1718 EventKind::LoadStart,
1719 listener.into_listener(),
1720 events::navigation,
1721 )
1722 }
1723
1724 pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1726 self.listen(
1727 EventKind::Load,
1728 listener.into_listener(),
1729 events::navigation,
1730 )
1731 }
1732
1733 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1735 self.listen(EventKind::Error, listener.into_listener(), events::message)
1736 }
1737
1738 pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1744 self.listen(
1745 EventKind::Error,
1746 listener.into_listener(),
1747 events::unavailable,
1748 )
1749 }
1750
1751 pub fn on_process_terminated<M>(self, listener: impl IntoListener<str, M>) -> Self {
1757 self.listen(
1758 EventKind::Error,
1759 listener.into_listener(),
1760 events::terminated,
1761 )
1762 }
1763
1764 pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1766 self.listen(EventKind::Message, listener.into_listener(), events::data)
1767 }
1768
1769 pub fn on_navigation_state_change<M>(
1771 self,
1772 listener: impl IntoListener<WebNavigation, M>,
1773 ) -> Self {
1774 self.listen(
1775 EventKind::NavigationStateChange,
1776 listener.into_listener(),
1777 events::navigation,
1778 )
1779 }
1780
1781 pub fn on_download<M>(
1788 self,
1789 listener: impl IntoListener<crate::webview::WebDownload, M>,
1790 ) -> Self {
1791 self.listen(
1792 EventKind::Download,
1793 listener.into_listener(),
1794 events::web_download,
1795 )
1796 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1797 }
1798
1799 pub fn on_download_pending<M>(
1807 self,
1808 listener: impl IntoListener<crate::webview::WebDownloadPending, M>,
1809 ) -> Self {
1810 self.listen(
1811 EventKind::DownloadPending,
1812 listener.into_listener(),
1813 events::web_download_pending,
1814 )
1815 .set(Prop::Native(NativeProp::DeferDownloads(true)))
1816 }
1817}
1818
1819impl Video {
1820 pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1822 self.bind_prop(paused, |paused: bool| {
1823 Prop::Native(NativeProp::Paused(paused))
1824 })
1825 }
1826
1827 pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1829 self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1830 }
1831
1832 pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1834 self.bind_prop(volume, |volume: f32| {
1835 Prop::Native(NativeProp::Volume(volume))
1836 })
1837 }
1838
1839 pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1841 self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1842 }
1843
1844 pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1846 self.bind_prop(repeat, |repeat: bool| {
1847 Prop::Native(NativeProp::Repeat(repeat))
1848 })
1849 }
1850
1851 pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1853 self.bind_prop(controls, |controls: bool| {
1854 Prop::Native(NativeProp::Controls(controls))
1855 })
1856 }
1857
1858 pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1860 self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1861 }
1862
1863 pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1866 self.bind_prop(session, |session: AudioSession| {
1867 Prop::Native(NativeProp::AudioSession(session))
1868 })
1869 }
1870
1871 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1873 self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1874 }
1875
1876 pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1878 self.listen(EventKind::Load, listener.into_listener(), events::video)
1879 }
1880
1881 pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1883 self.listen(
1884 EventKind::Progress,
1885 listener.into_listener(),
1886 events::progress,
1887 )
1888 }
1889
1890 pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1892 self.listen(EventKind::End, listener.into_listener(), events::unit)
1893 }
1894
1895 pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1897 self.listen(
1898 EventKind::Buffer,
1899 listener.into_listener(),
1900 events::buffering,
1901 )
1902 }
1903
1904 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1906 self.listen(EventKind::Error, listener.into_listener(), events::message)
1907 }
1908}
1909
1910impl NativeView {
1911 pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1914 let name: Arc<str> = name.into();
1915 self.bind_prop(value, move |value| {
1916 Prop::ComponentProp(name.clone(), Some(value))
1917 })
1918 }
1919
1920 pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1926 if let Some(node) = value.animated_node().live() {
1927 set(
1928 &mut self.0,
1929 Prop::ComponentPropBinding(name.into(), Some(node.id())),
1930 );
1931 self.0.attrs.rare_mut().bound.push(node);
1932 }
1933 self
1934 }
1935
1936 pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1938 self.listen(
1939 EventKind::NativeEvent,
1940 listener.into_listener(),
1941 events::native,
1942 )
1943 }
1944}
1945
1946#[derive(Debug, Clone, PartialEq)]
1949pub struct CanvasArg(pub(crate) CanvasArgKind);
1950
1951#[derive(Debug, Clone, PartialEq)]
1952pub(crate) enum CanvasArgKind {
1953 Const(f32),
1954 Node(super::LiveNode),
1955}
1956
1957impl From<f32> for CanvasArg {
1958 fn from(n: f32) -> Self {
1959 Self(CanvasArgKind::Const(n))
1960 }
1961}
1962
1963impl From<Points> for CanvasArg {
1965 fn from(n: Points) -> Self {
1966 Self(CanvasArgKind::Const(n.0))
1967 }
1968}
1969
1970impl From<Radians> for CanvasArg {
1972 fn from(n: Radians) -> Self {
1973 Self(CanvasArgKind::Const(n.0))
1974 }
1975}
1976
1977impl<A: super::Animated> From<&A> for CanvasArg {
1979 fn from(a: &A) -> Self {
1980 Self(match a.animated_node().live() {
1981 Some(node) => CanvasArgKind::Node(node),
1982 None => CanvasArgKind::Const(0.0),
1983 })
1984 }
1985}
1986
1987#[derive(Debug, Clone, PartialEq)]
1992pub struct CanvasPaint(CanvasPaintKind);
1993
1994#[derive(Debug, Clone, PartialEq)]
1995enum CanvasPaintKind {
1996 Color(Color),
1997 Gradient(Arc<CanvasGradient>),
1998 Node(super::LiveNode),
1999}
2000
2001impl From<Color> for CanvasPaint {
2002 fn from(color: Color) -> Self {
2003 Self(CanvasPaintKind::Color(color))
2004 }
2005}
2006
2007impl From<Hsla> for CanvasPaint {
2008 fn from(color: Hsla) -> Self {
2009 Color::from(color).into()
2010 }
2011}
2012
2013impl From<Rgba> for CanvasPaint {
2014 fn from(color: Rgba) -> Self {
2015 Color::from(color).into()
2016 }
2017}
2018
2019impl From<CanvasGradient> for CanvasPaint {
2020 fn from(gradient: CanvasGradient) -> Self {
2021 Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
2022 }
2023}
2024
2025impl From<Arc<CanvasGradient>> for CanvasPaint {
2026 fn from(gradient: Arc<CanvasGradient>) -> Self {
2027 Self(CanvasPaintKind::Gradient(gradient))
2028 }
2029}
2030
2031impl<A: super::Animated> From<&A> for CanvasPaint {
2033 fn from(a: &A) -> Self {
2034 Self(match a.animated_node().live() {
2035 Some(node) => CanvasPaintKind::Node(node),
2036 None => CanvasPaintKind::Color(Color::TRANSPARENT),
2037 })
2038 }
2039}
2040
2041#[derive(Debug, Clone, Default)]
2049pub struct Painter {
2050 drawing: Drawing,
2051 nodes: Vec<super::LiveNode>,
2053}
2054
2055impl Painter {
2056 pub fn new() -> Self {
2058 Self::default()
2059 }
2060
2061 pub fn finish(self) -> Drawing {
2063 self.drawing
2064 }
2065
2066 pub fn render(
2077 self,
2078 size: Size<Points>,
2079 options: crate::canvas::render::RenderOptions,
2080 ) -> crate::element::Answer<Result<Vec<u8>, crate::element::JsError>> {
2081 crate::element::ambient::render_canvas(crate::canvas::render::RenderRequest {
2082 drawing: self.drawing,
2083 size,
2084 scale: options.scale,
2085 format: options.format,
2086 })
2087 }
2088
2089 pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
2093 match value.into().0 {
2094 CanvasArgKind::Const(n) => Num::Const(n),
2095 CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
2096 }
2097 }
2098
2099 pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
2102 match paint.into().0 {
2103 CanvasPaintKind::Color(color) => Paint::Color(color),
2104 CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
2105 CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
2106 }
2107 }
2108
2109 fn slot(&mut self, node: super::LiveNode) -> u16 {
2110 let slot = self.drawing.slot(node.id());
2111 self.nodes.push(node);
2112 slot
2113 }
2114
2115 pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
2118 self.drawing.nodes.push(node);
2119 self
2120 }
2121
2122 pub fn op(mut self, op: CanvasOp) -> Self {
2125 self.drawing.ops.push(op);
2126 self
2127 }
2128
2129 fn path(self, op: PathOp) -> Self {
2130 self.op(CanvasOp::Path(op))
2131 }
2132
2133 pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
2140 crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
2141 }
2142
2143 pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
2147 crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
2148 }
2149
2150 pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
2155 crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
2156 }
2157
2158 pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
2162 crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
2163 }
2164
2165 pub fn save(self) -> Self {
2167 self.op(CanvasOp::Save)
2168 }
2169
2170 pub fn restore(self) -> Self {
2172 self.op(CanvasOp::Restore)
2173 }
2174
2175 pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2177 let (x, y) = (self.num(x), self.num(y));
2178 self.op(CanvasOp::Translate(x, y))
2179 }
2180
2181 pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2183 let (x, y) = (self.num(x), self.num(y));
2184 self.op(CanvasOp::Scale(x, y))
2185 }
2186
2187 pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
2190 let a = self.num(angle);
2191 self.op(CanvasOp::Rotate(a))
2192 }
2193
2194 pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2197 let m = m.map(|n| self.num(n));
2198 self.op(CanvasOp::Transform(m))
2199 }
2200
2201 pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2204 let m = m.map(|n| self.num(n));
2205 self.op(CanvasOp::SetTransform(m))
2206 }
2207
2208 pub fn reset_transform(self) -> Self {
2210 self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
2211 }
2212
2213 pub fn begin_path(self) -> Self {
2215 self.op(CanvasOp::BeginPath)
2216 }
2217
2218 pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2220 let (x, y) = (self.num(x), self.num(y));
2221 self.path(PathOp::MoveTo(x, y))
2222 }
2223
2224 pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2226 let (x, y) = (self.num(x), self.num(y));
2227 self.path(PathOp::LineTo(x, y))
2228 }
2229
2230 pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
2232 let c = |v: Points| Num::Const(v.0);
2233 self.path(PathOp::QuadTo([
2234 c(control.x),
2235 c(control.y),
2236 c(to.x),
2237 c(to.y),
2238 ]))
2239 }
2240
2241 pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
2243 let c = |v: Points| Num::Const(v.0);
2244 self.path(PathOp::CubicTo([
2245 c(c1.x),
2246 c(c1.y),
2247 c(c2.x),
2248 c(c2.y),
2249 c(to.x),
2250 c(to.y),
2251 ]))
2252 }
2253
2254 pub fn arc(
2257 self,
2258 x: impl Into<CanvasArg>,
2259 y: impl Into<CanvasArg>,
2260 radius: impl Into<CanvasArg>,
2261 start: impl Into<CanvasArg>,
2262 end: impl Into<CanvasArg>,
2263 ) -> Self {
2264 self.arc_in(x, y, radius, start, end, false)
2265 }
2266
2267 pub fn arc_counterclockwise(
2269 self,
2270 x: impl Into<CanvasArg>,
2271 y: impl Into<CanvasArg>,
2272 radius: impl Into<CanvasArg>,
2273 start: impl Into<CanvasArg>,
2274 end: impl Into<CanvasArg>,
2275 ) -> Self {
2276 self.arc_in(x, y, radius, start, end, true)
2277 }
2278
2279 fn arc_in(
2280 mut self,
2281 x: impl Into<CanvasArg>,
2282 y: impl Into<CanvasArg>,
2283 radius: impl Into<CanvasArg>,
2284 start: impl Into<CanvasArg>,
2285 end: impl Into<CanvasArg>,
2286 ccw: bool,
2287 ) -> Self {
2288 let (x, y, radius, start, end) = (
2289 self.num(x),
2290 self.num(y),
2291 self.num(radius),
2292 self.num(start),
2293 self.num(end),
2294 );
2295 self.path(PathOp::Arc {
2296 x,
2297 y,
2298 radius,
2299 start,
2300 end,
2301 ccw,
2302 })
2303 }
2304
2305 pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2308 let c = |v: Points| Num::Const(v.0);
2309 self.path(PathOp::ArcTo([
2310 c(p1.x),
2311 c(p1.y),
2312 c(p2.x),
2313 c(p2.y),
2314 c(radius),
2315 ]))
2316 }
2317
2318 pub fn ellipse(
2322 self,
2323 center: Point<Points>,
2324 radii: Size<Points>,
2325 rotation: Radians,
2326 start: Radians,
2327 end: Radians,
2328 counterclockwise: bool,
2329 ) -> Self {
2330 let c = Num::Const;
2331 self.path(PathOp::Ellipse {
2332 geometry: [
2333 c(center.x.0),
2334 c(center.y.0),
2335 c(radii.width.0),
2336 c(radii.height.0),
2337 c(rotation.0),
2338 ],
2339 start: c(start.0),
2340 end: c(end.0),
2341 ccw: counterclockwise,
2342 })
2343 }
2344
2345 pub fn rect(self, rect: Bounds<Points>) -> Self {
2347 self.path(PathOp::Rect(nums(rect)))
2348 }
2349
2350 pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2352 self.round_rect_corners(rect, Corners::all(radius))
2353 }
2354
2355 pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2357 let c = |v: Points| Num::Const(v.0);
2358 self.path(PathOp::RoundRect(
2359 nums(rect),
2360 [
2361 c(radii.top_left),
2362 c(radii.top_right),
2363 c(radii.bottom_right),
2364 c(radii.bottom_left),
2365 ],
2366 ))
2367 }
2368
2369 pub fn close_path(self) -> Self {
2371 self.path(PathOp::Close)
2372 }
2373
2374 pub fn fill(self) -> Self {
2376 self.fill_with(FillRule::NonZero)
2377 }
2378
2379 pub fn fill_with(self, rule: FillRule) -> Self {
2381 self.op(CanvasOp::Fill(None, rule))
2382 }
2383
2384 pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2387 self.op(CanvasOp::Fill(Some(path.clone()), rule))
2388 }
2389
2390 pub fn fill_svg(self, data: &str) -> Self {
2393 self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2394 }
2395
2396 pub fn stroke(self) -> Self {
2398 self.op(CanvasOp::Stroke(None))
2399 }
2400
2401 pub fn stroke_path(self, path: &Path) -> Self {
2403 self.op(CanvasOp::Stroke(Some(path.clone())))
2404 }
2405
2406 pub fn stroke_svg(self, data: &str) -> Self {
2408 self.stroke_path(&crate::canvas::svg_path(data))
2409 }
2410
2411 pub fn clip(self) -> Self {
2413 self.clip_with(FillRule::NonZero)
2414 }
2415
2416 pub fn clip_with(self, rule: FillRule) -> Self {
2418 self.op(CanvasOp::Clip(None, rule))
2419 }
2420
2421 pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2423 self.op(CanvasOp::Clip(Some(path.clone()), rule))
2424 }
2425
2426 pub fn fill_rect(
2428 mut self,
2429 x: impl Into<CanvasArg>,
2430 y: impl Into<CanvasArg>,
2431 w: impl Into<CanvasArg>,
2432 h: impl Into<CanvasArg>,
2433 ) -> Self {
2434 let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2435 self.op(CanvasOp::FillRect([x, y, w, h]))
2436 }
2437
2438 pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2440 self.op(CanvasOp::StrokeRect(nums(rect)))
2441 }
2442
2443 pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2445 self.op(CanvasOp::ClearRect(nums(rect)))
2446 }
2447
2448 pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2450 self.fill_style(color.into())
2451 }
2452
2453 pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2455 self.stroke_style(color.into())
2456 }
2457
2458 pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2461 let paint = self.paint(paint);
2462 self.op(CanvasOp::FillStyle(paint))
2463 }
2464
2465 pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2471 self.view_paint(
2472 ViewPaint::Fill(initial),
2473 CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2474 )
2475 }
2476
2477 pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2480 self.view_paint(
2481 ViewPaint::Stroke(initial),
2482 CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2483 )
2484 }
2485
2486 pub fn line_width_from_view(self) -> Self {
2489 self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2490 }
2491
2492 pub fn line_dash_from_view(self) -> Self {
2495 self.view_paint(
2496 ViewPaint::StrokeDasharray,
2497 CanvasOp::LineDash(Arc::from([])),
2498 )
2499 }
2500
2501 pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2510 self.view_paint(
2511 ViewPaint::Background {
2512 area,
2513 rule: FillRule::NonZero,
2514 },
2515 CanvasOp::Fill(None, FillRule::NonZero),
2516 )
2517 }
2518
2519 fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2520 let at = self.drawing.ops.len() as u32;
2521 self.drawing.view_paints.push((at, view));
2522 self.op(placeholder)
2523 }
2524
2525 pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2527 let paint = self.paint(paint);
2528 self.op(CanvasOp::StrokeStyle(paint))
2529 }
2530
2531 pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2533 let w = self.num(width);
2534 self.op(CanvasOp::LineWidth(w))
2535 }
2536
2537 pub fn line_cap(self, cap: LineCap) -> Self {
2539 self.op(CanvasOp::LineCap(cap))
2540 }
2541
2542 pub fn line_join(self, join: LineJoin) -> Self {
2544 self.op(CanvasOp::LineJoin(join))
2545 }
2546
2547 pub fn miter_limit(self, limit: f32) -> Self {
2550 self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2551 }
2552
2553 pub fn line_dash(self, segments: &[Points]) -> Self {
2555 self.op(CanvasOp::LineDash(segments.into()))
2556 }
2557
2558 pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2561 let o = self.num(offset);
2562 self.op(CanvasOp::LineDashOffset(o))
2563 }
2564
2565 pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2567 let a = self.num(alpha);
2568 self.op(CanvasOp::GlobalAlpha(a))
2569 }
2570
2571 pub fn composite(self, composite: Composite) -> Self {
2573 self.op(CanvasOp::Composite(composite))
2574 }
2575
2576 pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2578 self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2579 .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2580 .op(CanvasOp::ShadowOffset(offset))
2581 }
2582
2583 pub fn font(self, font: &str) -> Self {
2586 match CanvasFont::parse(font) {
2587 Some(font) => self.op(CanvasOp::Font(font)),
2588 None => self,
2589 }
2590 }
2591
2592 pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2596 self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2597 numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2598 )))
2599 }
2600
2601 pub fn text_align(self, align: CanvasTextAlign) -> Self {
2603 self.op(CanvasOp::TextAlign(align))
2604 }
2605
2606 pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2608 self.op(CanvasOp::TextBaseline(baseline))
2609 }
2610
2611 pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2613 self.text(text, x, y, None, false)
2614 }
2615
2616 pub fn fill_text_max_width(
2618 self,
2619 text: &str,
2620 x: impl Into<CanvasArg>,
2621 y: impl Into<CanvasArg>,
2622 max_width: Points,
2623 ) -> Self {
2624 self.text(text, x, y, Some(max_width), false)
2625 }
2626
2627 pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2629 self.text(text, x, y, None, true)
2630 }
2631
2632 pub fn stroke_text_max_width(
2635 self,
2636 text: &str,
2637 x: impl Into<CanvasArg>,
2638 y: impl Into<CanvasArg>,
2639 max_width: Points,
2640 ) -> Self {
2641 self.text(text, x, y, Some(max_width), true)
2642 }
2643
2644 fn text(
2645 mut self,
2646 text: &str,
2647 x: impl Into<CanvasArg>,
2648 y: impl Into<CanvasArg>,
2649 max_width: Option<Points>,
2650 stroke: bool,
2651 ) -> Self {
2652 let (text, x, y) = (text.into(), self.num(x), self.num(y));
2653 self.op(if stroke {
2654 CanvasOp::StrokeText {
2655 text,
2656 x,
2657 y,
2658 max_width,
2659 }
2660 } else {
2661 CanvasOp::FillText {
2662 text,
2663 x,
2664 y,
2665 max_width,
2666 }
2667 })
2668 }
2669
2670 pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2672 self.draw_image_part(uri, None, dest)
2673 }
2674
2675 pub fn draw_image_part(
2678 self,
2679 uri: &str,
2680 source: Option<Bounds<ScaledPixels>>,
2681 dest: Bounds<Points>,
2682 ) -> Self {
2683 self.op(CanvasOp::DrawImage {
2684 image: CanvasImage { uri: uri.into() },
2685 source,
2686 dest: nums(dest),
2687 })
2688 }
2689}
2690
2691fn nums(rect: Bounds<Points>) -> [Num; 4] {
2693 [
2694 rect.origin.x,
2695 rect.origin.y,
2696 rect.size.width,
2697 rect.size.height,
2698 ]
2699 .map(|v| Num::Const(v.0))
2700}
2701
2702impl From<Drawing> for Painter {
2703 fn from(drawing: Drawing) -> Self {
2704 Self {
2705 drawing,
2706 nodes: Vec::new(),
2707 }
2708 }
2709}
2710
2711crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2712crate::static_reactive!(HeaderTitleAlign: HeaderTitleAlign);
2713
2714impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2716 fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2717 super::Reactive::Static(Some(self))
2718 }
2719}
2720
2721impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2723 fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2724 super::Reactive::Static(Some(self))
2725 }
2726}
2727
2728impl IntoReactive<Option<crate::WindowsBackdrop>> for crate::WindowsBackdrop {
2730 fn into_reactive(self) -> super::Reactive<Option<crate::WindowsBackdrop>> {
2731 super::Reactive::Static(Some(self))
2732 }
2733}
2734
2735#[cfg(test)]
2736mod tests {
2737 use super::*;
2738 use crate::{
2739 element::{
2740 AnimatedValue,
2741 reactive::{Runtime, create_root, signal},
2742 },
2743 shader::{ShaderUniforms, UniformValue},
2744 };
2745
2746 fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2747 attrs
2748 .props
2749 .iter()
2750 .find_map(|p| match p {
2751 Prop::Uniforms(u) => Some(u.clone()),
2752 _ => None,
2753 })
2754 .unwrap_or_default()
2755 }
2756
2757 fn released(executor: &super::super::task::Executor) -> usize {
2759 executor
2760 .take_actions()
2761 .into_iter()
2762 .filter(|a| {
2763 matches!(
2764 a,
2765 super::super::task::Action::Animation(
2766 crate::animation::AnimationOp::Release { .. }
2767 )
2768 )
2769 })
2770 .count()
2771 }
2772
2773 fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2774 u.0.iter()
2775 .find(|(n, _)| &**n == name)
2776 .map(|(_, v)| v.clone())
2777 }
2778
2779 #[test]
2780 fn screens_and_modals_take_a_transition_shader() {
2781 let runtime = Runtime::default();
2782 let _entered = runtime.enter();
2783 let source = "struct Uniforms { edge: f32 }\n\
2784 fn shade(uv: vec2f) -> vec4f {\n \
2785 return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2786 let shader = crate::shader::Shader::compile(source).expect("compiles");
2787 let wipe = crate::shader::TransitionShader::new(shader)
2788 .uniform("edge", 1.0_f32)
2789 .duration(std::time::Duration::from_millis(400));
2790 let expected = crate::shader::NavShaderSpec {
2791 source: source.into(),
2792 uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2793 duration: Some(400.0),
2794 };
2795 let spec = |attrs: &super::super::builder::Attrs| {
2796 attrs.props.iter().find_map(|p| match p {
2797 Prop::TransitionShader(s) => Some(s.clone()),
2798 _ => None,
2799 })
2800 };
2801 let page = screen().transition_shader(wipe.clone()).0;
2802 assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2803 let dialog = modal().transition_shader(wipe.clone()).0;
2804 assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2805 let on = signal(true);
2807 let bound = screen()
2808 .transition_shader(move || on.get().then(|| wipe.clone()))
2809 .0;
2810 assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
2811 on.set(false);
2812 assert_eq!(spec(&bound.resolved_attrs()), Some(None));
2813 }
2814
2815 #[test]
2816 fn uniform_takes_static_bound_and_animated_values() {
2817 let runtime = Runtime::default();
2818 let _entered = runtime.enter();
2819 let executor = std::rc::Rc::new(super::super::task::Executor::default());
2820 let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
2821 let speed = signal(1.0_f32);
2822 let view = shader()
2823 .uniform("center", [0.5_f32, 0.5])
2824 .uniform("wave", &wave)
2825 .uniform("speed", move || speed.get());
2826 let node = view.0;
2827
2828 let set = uniforms(&node.attrs);
2831 assert_eq!(
2832 value(&set, "center"),
2833 Some(UniformValue::List(vec![
2834 UniformValue::Number(0.5),
2835 UniformValue::Number(0.5)
2836 ]))
2837 );
2838 let id = wave.node().live().expect("live").id();
2839 assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
2840 assert_eq!(
2841 node.attrs.bound().len(),
2842 1,
2843 "the element holds the animated node"
2844 );
2845 assert_eq!(
2846 value(&set, "speed"),
2847 None,
2848 "a bound one is applied when resolved"
2849 );
2850
2851 assert_eq!(
2853 value(&uniforms(&node.resolved_attrs()), "speed"),
2854 Some(UniformValue::Number(1.0))
2855 );
2856 speed.set(2.0);
2857 assert_eq!(
2858 value(&uniforms(&node.resolved_attrs()), "speed"),
2859 Some(UniformValue::Number(2.0))
2860 );
2861
2862 value_owner.dispose();
2864 assert_eq!(released(&executor), 0, "the view keeps the animated node");
2865 drop(node);
2866 assert_eq!(released(&executor), 1, "and lets it go with the view");
2867 }
2868
2869 #[test]
2870 fn a_later_uniform_replaces_one_of_the_same_name() {
2871 let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
2872 let set = uniforms(&view.0.attrs);
2873 assert_eq!(set.0.len(), 1);
2874 assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
2875 }
2876
2877 #[test]
2878 fn web_view_url_scheme_builder_collects_schemes() {
2879 let web = web_view_html("<img src=\"a:1\">", None)
2880 .url_scheme("a", |request| request.fail())
2881 .url_scheme("b", |request| request.fail())
2882 .url_scheme("A", |request| request.fail())
2884 .url_scheme("https", |request| request.fail());
2886 let schemes: Vec<String> = web
2887 .0
2888 .attrs
2889 .props
2890 .iter()
2891 .find_map(|p| match p {
2892 Prop::Native(NativeProp::UrlSchemes(list)) => {
2893 Some(list.iter().map(|s| s.scheme().to_owned()).collect())
2894 }
2895 _ => None,
2896 })
2897 .unwrap();
2898 assert_eq!(schemes, ["b", "a"]);
2899 }
2900}