Skip to main content

nsh_core/element/
host.rs

1//! The host elements beyond views, texts and images: inputs, scroll views,
2//! navigation stacks and their screens, modals, canvases, web views, videos
3//! and the embedder's native components, with their props and typed events. Their props are the
4//! core's [`Prop`]s, kept per element and diffed by kind: a prop an
5//! element's binding (or a region's element made again) no longer sets
6//! goes back to its default, as when JS clears it.
7
8use std::sync::Arc;
9
10use super::{
11    Accessible, AnyElement, Interactive, IntoReactive,
12    builder::{ElNode, Element, IntoElement, IntoListener, Listener, ParentElement},
13    events::{
14        self, CaretEvent, Composition, HintReason, NativeEvent, OverlayPosition, Selection,
15        VideoInfo, VideoProgress, WebNavigation,
16    },
17};
18use crate::{
19    AudioSession, AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, Hsla, JsonValue,
20    KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp,
21    OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType, Rgba,
22    ScreenAnimation, ScreenProp, ScrollProp, Size, StatusBarSetting, SubmitBehavior, Tag,
23    WebSource,
24    canvas::{
25        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
26        Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
27    },
28    geometry::{Bounds, Corners, Percentage, Point, Radians, ScaledPixels},
29    js::host::HostProps,
30    overlay::{Align, OverlayAnchor, Placement},
31    style::SvgPaint,
32};
33
34/// Whether `a` and `b` set the same property (their values aside).
35pub(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
44/// `prop`'s property at its default (what clearing it from JS sets), for
45/// the props elements set; `None` for those set once.
46pub(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
55/// Sets `prop` on `node`, replacing the value of the same property.
56pub(crate) fn set(node: &mut ElNode, prop: Prop) {
57    set_in(&mut node.attrs.props, prop);
58}
59
60crate::static_reactive!(Color: Color);
61crate::static_reactive!(Hsla: Hsla, Rgba, Color);
62crate::static_reactive!(crate::AccessibilityRole: crate::AccessibilityRole);
63crate::static_reactive!(AutoCapitalize: AutoCapitalize);
64crate::static_reactive!(AutoFill: AutoFill);
65crate::static_reactive!(crate::HeaderSystemItem: crate::HeaderSystemItem);
66crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
67crate::static_reactive!(KeyboardType: KeyboardType);
68crate::static_reactive!(ModalAnimation: ModalAnimation);
69crate::static_reactive!(ModalPresentation: ModalPresentation);
70crate::static_reactive!(ResizeMode: ResizeMode);
71crate::static_reactive!(ReturnKeyType: ReturnKeyType);
72crate::static_reactive!(SubmitBehavior: SubmitBehavior);
73crate::static_reactive!(PasteBehavior: PasteBehavior);
74crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
75crate::static_reactive!(JsonValue: JsonValue);
76crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
77crate::static_reactive!(Placement: Placement);
78crate::static_reactive!(Align: Align);
79
80/// Sets `prop` among `props`, replacing one of its kind.
81pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
82    match props.iter_mut().find(|p| same_kind(p, &prop)) {
83        Some(p) => *p = prop,
84        None => props.push(prop),
85    }
86}
87
88/// Sets the prop `prop` makes of `value`: now when it is static, else as a
89/// bound part.
90pub(crate) fn bind_prop<T: 'static>(
91    node: &mut ElNode,
92    value: impl IntoReactive<T>,
93    prop: impl Fn(T) -> Prop + 'static,
94) {
95    node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
96}
97
98/// Adds a typed listener of `kind`.
99fn listen<T: ?Sized + ToOwned + 'static>(
100    node: &mut ElNode,
101    kind: EventKind,
102    listener: Listener<T>,
103    decode: events::Decode<T>,
104) {
105    node.handlers.push((kind, events::typed(listener, decode)));
106}
107
108macro_rules! host_element {
109    ($(#[$doc:meta])* $name:ident) => {
110        $(#[$doc])*
111        #[derive(Clone)]
112        pub struct $name(ElNode);
113
114        impl Element for $name {
115            fn node(&mut self) -> &mut ElNode {
116                &mut self.0
117            }
118        }
119
120        impl IntoElement for $name {
121            fn into_element(self) -> AnyElement {
122                AnyElement(self.0)
123            }
124        }
125
126        impl Accessible for $name {}
127        impl Interactive for $name {}
128
129        impl super::builder::IntoTooltip for $name {
130            fn apply_tooltip(self, node: &mut ElNode) {
131                self.into_element().apply_tooltip(node);
132            }
133        }
134
135        // Not every element has props of its own and events.
136        #[allow(dead_code)]
137        impl $name {
138            fn set(mut self, prop: Prop) -> Self {
139                set(&mut self.0, prop);
140                self
141            }
142
143            fn bind_prop<T: 'static>(
144                mut self,
145                value: impl IntoReactive<T>,
146                prop: impl Fn(T) -> Prop + 'static,
147            ) -> Self {
148                bind_prop(&mut self.0, value, prop);
149                self
150            }
151
152            fn listen<T: ?Sized + ToOwned + 'static>(
153                mut self,
154                kind: EventKind,
155                listener: Listener<T>,
156                decode: events::Decode<T>,
157            ) -> Self {
158                listen(&mut self.0, kind, listener, decode);
159                self
160            }
161        }
162    };
163}
164
165host_element! {
166    /// A text field (`<input>`), made by [`input`]: one line, or several
167    /// with [`Input::multiline`]. Its text style comes from its styles.
168    Input
169}
170
171host_element! {
172    /// A scroll view (`<scroll>`), made by [`scroll`]: its children are its
173    /// content.
174    Scroll
175}
176
177host_element! {
178    /// A native navigation stack (`<stack>`, TS: `NavStack` of `nsh/base`),
179    /// made by `nsh_base::nav_stack`:
180    /// UINavigationController on iOS (swipe back, native header), a stack
181    /// with a toolbar and predictive back on Android. Its children are its
182    /// [`Screen`]s, bottom to top.
183    Stack
184}
185
186host_element! {
187    /// One page of a [`Stack`] (`<screen>`, TS: `NavPage` of `nsh/base`),
188    /// made by `nsh_base::nav_page`: its header options and its content (its
189    /// children).
190    Screen
191}
192
193host_element! {
194    /// A dialog (`<modal>`, TS: `Dialog` of `nsh/base`), made by
195    /// `nsh_base::dialog`: presented while it is in the view, over everything
196    /// else; its children are its content.
197    Modal
198}
199
200host_element! {
201    /// A bar over the keyboard (`<inputaccessory>`, TS: `InputAccessoryView`
202    /// of `nsh/ios`), made by [`input_accessory_view`]: its children are its
203    /// content.
204    InputAccessoryView
205}
206
207host_element! {
208    /// A view drawn with a [`Drawing`] (`<canvas>`), made by [`canvas`].
209    CanvasView
210}
211
212host_element! {
213    /// An SVG drawn as authored, made by [`svg`].
214    Svg
215}
216
217host_element! {
218    /// A view whose box a shader draws under its children (`<shader>`, TS:
219    /// `Shader` of `nsh`), made by [`shader`] ([`crate::shader`]).
220    ShaderView
221}
222
223host_element! {
224    /// A web page (`<webview>`), made by [`web_view`].
225    WebView
226}
227
228host_element! {
229    /// A video player (`<video>`), made by [`video`].
230    Video
231}
232
233host_element! {
234    /// A native component the embedding app registered (`<native>`), made
235    /// by [`native`].
236    NativeView
237}
238
239host_element! {
240    /// Its children on top of the root view it is in (`<overlay>`, TS:
241    /// `Overlay` of `nsh`), made by [`overlay`]: the surface, or the dialog
242    /// around it; outside its parent's layout and clipping, while it stays
243    /// where it is for everything else (context, events, lifetime).
244    Overlay
245}
246
247impl ParentElement for Overlay {}
248impl ParentElement for ShaderView {}
249impl ParentElement for Scroll {}
250impl ParentElement for Stack {}
251impl ParentElement for Screen {}
252impl ParentElement for Modal {}
253
254/// Android has no input accessories: there the bar keeps no content.
255impl ParentElement for InputAccessoryView {
256    fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
257        if !cfg!(target_os = "android") {
258            child.__push_into(&mut self.0.children);
259        }
260        self
261    }
262
263    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
264        if !cfg!(target_os = "android") {
265            self.0
266                .children
267                .extend(children.into_iter().map(|c| c.into_element().0));
268        }
269        self
270    }
271}
272
273/// An overlay: its children shown on top of the root view it is in (the
274/// surface, or the dialog around it), above what that root view shows and
275/// the overlays shown before it, while it is in the view (in a region:
276/// [`super::If`]). Without an anchor it is laid out as a `position: fixed`
277/// box of the root view (`.absolute().inset_0()` covers it); with one
278/// ([`Overlay::anchor`], [`Overlay::anchor_point`]) it goes on a side of it
279/// and follows it ([`crate::overlay`]).
280pub fn overlay() -> Overlay {
281    Overlay(ElNode::new(Tag::Overlay))
282}
283
284/// A text field.
285pub fn input() -> Input {
286    Input(ElNode::new(Tag::Input))
287}
288
289/// A vertical scroll view ([`Scroll::horizontal`] for a horizontal one).
290pub fn scroll() -> Scroll {
291    Scroll(ElNode::new(Tag::Scroll))
292}
293
294/// A native navigation stack of [`screen`]s: put a screen in to push it,
295/// leave it out to pop it. Give each screen a [`Element::key`] (its route)
296/// so the screens below keep their state.
297///
298/// The core's part of `nsh_base::nav_stack`, which apps use.
299#[doc(hidden)]
300pub fn stack() -> Stack {
301    Stack(ElNode::new(Tag::Stack))
302}
303
304/// A screen of a [`stack`]. What it shows reads its insets below the
305/// header ([`super::Scope::insets`]).
306///
307/// The core's part of `nsh_base::nav_page`, which apps use.
308#[doc(hidden)]
309pub fn screen() -> Screen {
310    let mut node = ElNode::new(Tag::Screen);
311    // Its insets come with this event.
312    node.handlers.push((EventKind::Insets, Listener::noop()));
313    Screen(node)
314}
315
316/// A modal presenting its children. Put it in the view to present it (in
317/// a region: [`super::If`]), leave it out to dismiss it.
318///
319/// The core's part of `nsh_base::dialog`, which apps use.
320#[doc(hidden)]
321pub fn modal() -> Modal {
322    let mut node = ElNode::new(Tag::Modal);
323    // Its insets (`Scope::insets` inside it) come with this event.
324    node.handlers.push((EventKind::Insets, Listener::noop()));
325    Modal(node)
326}
327
328/// A bar shown over the keyboard of the inputs whose
329/// [`Input::input_accessory`] is `native_id` (iOS's `inputAccessoryView`):
330/// as wide as the window and as tall as its content, moving with the
331/// keyboard natively. It takes no room where the view places it; on
332/// Android, which has no input accessories, it is an empty hidden view.
333pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
334    let tag = if cfg!(target_os = "android") {
335        Tag::View
336    } else {
337        Tag::InputAccessory
338    };
339    let mut node = ElNode::new(tag);
340    if cfg!(target_os = "android") {
341        node.style.value(
342            crate::StyleKey::Display,
343            crate::PropertyValue::Display(taffy::Display::None),
344        );
345    } else {
346        set(&mut node, Prop::NativeId(Some(native_id.into())));
347    }
348    InputAccessoryView(node)
349}
350
351/// A canvas showing what `painter` recorded (animated values in it move
352/// natively). A closure draws in a binding: `canvas(move || draw(theme()))`
353/// draws again when what it read changes (a size kept from `on_layout`,
354/// the appearance).
355pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
356    let mut node = ElNode::new(Tag::Canvas);
357    node.bind_attr(painter, |attrs, painter: Painter| {
358        attrs.drawing = Some(Arc::new(painter.drawing));
359        attrs.bound = painter.nodes;
360    });
361    CanvasView(node)
362}
363
364crate::static_reactive!(Painter: Painter, Drawing);
365
366/// An SVG image drawn as authored, in its own colors, as an `<svg>` written
367/// inline in a web page draws: `svg(asset!("logo.svg"))`, a URL, a file or
368/// the markup itself (`svg(ImageSrc::svg_markup(include_str!("logo.svg")))`).
369/// Its `currentColor` is the element's text color (`color`, inherited), so
370/// an icon drawn with `stroke="currentColor"` follows the theme and the
371/// app's `text-*` classes. It lays out at the SVG's `width` and `height`
372/// (else its `viewBox`'s size) where its style sets no size, keeping that
373/// aspect ratio where it sets one side, as an image does; its `viewBox`
374/// is fitted into the box it gets as its `preserveAspectRatio` says.
375///
376/// On the native backends it is a canvas of the SVG's shapes, which the
377/// platform draws at its device pixels: sharp at every size and scale. Its
378/// bytes load as an image's do (the shared loader and its caches); the
379/// drawing is parsed once per source and kept in the decoded images'
380/// budget (`docs/dev/images.md`), leased while an element shows it. Inline
381/// markup and a drawing in memory show in the first frame; others when
382/// they load. A source that cannot be drawn draws nothing (logged). The
383/// web runtime shows it as an image the browser draws, with its
384/// `currentColor` written out as the element's text color.
385pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
386    #[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
387    {
388        let mut node = ElNode::new(Tag::Canvas);
389        let shown = svg_drawing(src);
390        node.bind_attr(
391            move || shown.get(),
392            |attrs, drawing| attrs.drawing = drawing,
393        );
394        Svg(node)
395    }
396    #[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
397    {
398        let mut node = ElNode::new(Tag::Image);
399        node.style.value(
400            crate::StyleKey::ObjectFit,
401            crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
402        );
403        node.bind_attr(src, |attrs, src| attrs.src = Some(src));
404        // The platform draws it: its `currentColor` is the text color.
405        set(
406            &mut node,
407            Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
408        );
409        Svg(node)
410    }
411}
412
413/// The drawing an [`svg`] of `src` shows: here and now when its bytes are
414/// in hand (inline markup) or it is in memory, else once it loads. A
415/// source that changes drops the load running and the lease of the
416/// drawing shown.
417#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
418fn svg_drawing(
419    src: impl IntoReactive<super::ImageSrc>,
420) -> super::reactive::Signal<Option<Arc<Drawing>>> {
421    use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
422    let src = src.into_reactive();
423    let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
424    let lease = stored(crate::image::Lease::none());
425    let task = stored(None::<super::Spawned<()>>);
426    render_effect(move || {
427        let src = match &src {
428            super::Reactive::Static(src) => src.clone(),
429            super::Reactive::Bound(f) => f(),
430        };
431        untracked(|| {
432            drop(task.replace(None));
433            let context = crate::image::loader::context();
434            let source = crate::ImageSource {
435                uri: src.uri.as_str().into(),
436                size: None,
437                scales: crate::ImageScales::NONE,
438                data: None,
439            }
440            .inline();
441            let Some(location) = context.locate(&source) else {
442                log::warn!("svg: unsupported source `{}`", source.uri);
443                shown.set(None);
444                lease.replace(crate::image::Lease::none());
445                return;
446            };
447            if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
448                shown.set(Some(drawing));
449                lease.replace(held);
450                return;
451            }
452            let load = crate::svg::drawings::load(location, context);
453            task.replace(Some(super::spawn(async move {
454                let (drawing, held) = load.await;
455                shown.set(Some(drawing));
456                lease.replace(held);
457            })));
458        });
459    });
460    shown
461}
462
463/// A view whose box a shader draws, under its children: give it the
464/// program with [`ShaderView::source`] and its uniforms with
465/// [`ShaderView::uniform`]. Without a program it draws nothing of its own.
466pub fn shader() -> ShaderView {
467    ShaderView(ElNode::new(Tag::Shader))
468}
469
470/// A view whose children draw through a shader: give it the program with
471/// [`ShaderView::source`], which reads what they draw with
472/// `sample_content`. Without a program the children draw as they are.
473pub fn shader_effect() -> ShaderView {
474    ShaderView(ElNode::new(Tag::ShaderEffect))
475}
476
477/// A view whose children change through a shader when its
478/// [`ShaderView::value`] changes: `sample_from` is a picture of what they
479/// drew, `sample_to` what they draw now, `nsh.progress` how far it is.
480/// Without a program it cross-fades ([`ShaderView::fallback`]).
481pub fn shader_transition() -> ShaderView {
482    ShaderView(ElNode::new(Tag::ShaderTransition))
483}
484
485/// The whole surface drawn through a shader, which reads it with
486/// `sample_content`. It takes no space and has no children.
487pub fn screen_effect() -> ShaderView {
488    ShaderView(ElNode::new(Tag::ScreenEffect))
489}
490
491/// The whole surface changing through a shader when its
492/// [`ShaderView::value`] changes, as [`shader_transition`] does for its
493/// children. It takes no space and has no children.
494pub fn screen_transition() -> ShaderView {
495    ShaderView(ElNode::new(Tag::ScreenTransition))
496}
497
498crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);
499
500/// A value [`ShaderView::uniform`] takes ([`IntoUniform`]).
501pub struct Uniform(UniformSource);
502
503enum UniformSource {
504    Value(super::Reactive<crate::shader::UniformValue>),
505    Animated(super::AnimatedNode),
506}
507
508/// What [`ShaderView::uniform`] takes: a number, a color or a list, bound
509/// or not, or an animated value (`&AnimatedValue`, `&AnimatedNode`).
510pub trait IntoUniform {
511    /// As a [`Uniform`].
512    fn into_uniform(self) -> Uniform;
513}
514
515impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
516    fn into_uniform(self) -> Uniform {
517        Uniform(UniformSource::Value(self.into_reactive()))
518    }
519}
520
521impl IntoUniform for &super::AnimatedValue {
522    fn into_uniform(self) -> Uniform {
523        Uniform(UniformSource::Animated(super::Animated::animated_node(
524            self,
525        )))
526    }
527}
528
529impl IntoUniform for &super::AnimatedNode {
530    fn into_uniform(self) -> Uniform {
531        Uniform(UniformSource::Animated(*self))
532    }
533}
534crate::static_reactive!(
535    crate::shader::UniformValue: crate::shader::UniformValue,
536    f32,
537    i32,
538    Color,
539    Hsla,
540    [f32; 2],
541    [f32; 3],
542    [f32; 4],
543    Vec<crate::shader::UniformValue>
544);
545
546impl ShaderView {
547    /// The program that draws its box, compiled once with
548    /// [`Shader::compile`](crate::shader::Shader::compile) (a bound one
549    /// draws the new program when it changes).
550    pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
551        self.bind_prop(shader, |s| Prop::Shader(Some(s)))
552    }
553
554    /// Sets the member `name` of the shader's `struct Uniforms` to `value`
555    /// ([`IntoUniform`]): a number, a color or a list (a vector, an array of
556    /// `vec4f`), which a bound value (`move || …`) sets again when it
557    /// changes; or an animated value (`&wave`, a number, or colors for a
558    /// `vec3f` / `vec4f`), which the platform writes on every frame it
559    /// changes, without the engine (one whose owner is gone counts as 0).
560    pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
561        let name: Arc<str> = name.into();
562        let value = match value.into_uniform().0 {
563            UniformSource::Value(value) => value,
564            UniformSource::Animated(node) => {
565                let value = match node.live() {
566                    Some(node) => {
567                        let id = node.id();
568                        self.0.attrs.bound.push(node);
569                        crate::shader::UniformValue::Animated(id)
570                    }
571                    None => crate::shader::UniformValue::Number(0.0),
572                };
573                super::Reactive::Static(value)
574            }
575        };
576        self.0.bind_attr(value, move |attrs, value| {
577            let mut uniforms = attrs
578                .props
579                .iter()
580                .find_map(|p| match p {
581                    Prop::Uniforms(u) => Some(u.clone()),
582                    _ => None,
583                })
584                .unwrap_or_default();
585            match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
586                Some(entry) => entry.1 = value,
587                None => uniforms.0.push((name.clone(), value)),
588            }
589            set_in(&mut attrs.props, Prop::Uniforms(uniforms));
590        });
591        self
592    }
593
594    /// Stops its clock (`nsh.time` keeps its value), or starts it again.
595    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
596        self.bind_prop(paused, Prop::ShaderPaused)
597    }
598
599    /// An effect's `nsh.progress`, a fraction (a bound one sets it again
600    /// when it changes).
601    pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
602        self.bind_prop(progress, |p| {
603            Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
604        })
605    }
606
607    /// An effect's `nsh.progress` moved by an animated value, which the
608    /// platform writes on every frame it changes, without the engine.
609    pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
610        let progress = match value.animated_node().live() {
611            Some(node) => {
612                let id = node.id();
613                self.0.attrs.bound.push(node);
614                crate::shader::ShaderProgress::Animated(id)
615            }
616            None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
617        };
618        self.set(Prop::ShaderProgress(progress))
619    }
620
621    /// How far beyond its box, in points, an effect or a transition draws
622    /// and its pictures reach (`maxSampleOffset`).
623    pub fn max_sample_offset(self, offset: Points) -> Self {
624        self.set(Prop::MaxSampleOffset(offset))
625    }
626
627    /// A transition's value: when it changes, the transition runs (not for
628    /// the first one).
629    pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
630        self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
631    }
632
633    /// How long a transition runs (300 ms by default).
634    pub fn duration(self, duration: std::time::Duration) -> Self {
635        self.set(Prop::TransitionDuration(Some(
636            duration.as_secs_f32() * 1000.0,
637        )))
638    }
639
640    /// What a transition without a program runs: a cross-fade (the
641    /// default) or nothing.
642    pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
643        self.set(Prop::TransitionFallback(fallback))
644    }
645}
646
647crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);
648
649/// A web view loading `url` (a bound one loads again when it changes).
650pub fn web_view(url: impl IntoReactive<String>) -> WebView {
651    WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
652        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
653    })
654}
655
656/// A web view showing the page `html`, its relative links resolved against
657/// `base_url` (TS: `html` and `baseUrl`).
658pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
659    WebView(ElNode::new(Tag::WebView)).html(html, base_url)
660}
661
662/// A video playing the file or stream at `url` (a bound one plays the new
663/// one when it changes).
664pub fn video(url: impl IntoReactive<String>) -> Video {
665    Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
666        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
667    })
668}
669
670/// The embedder's native component registered as `name`.
671pub fn native(name: &str) -> NativeView {
672    NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
673}
674
675impl Input {
676    /// The text, when the component controls it (update it from
677    /// [`Self::on_change`]).
678    pub fn value(self, text: impl IntoReactive<String>) -> Self {
679        self.bind_prop(text, |text: String| Prop::Value(text))
680    }
681
682    /// The first text, when the input keeps its own.
683    pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
684        self.bind_prop(text, |text: String| Prop::DefaultValue(text))
685    }
686
687    /// Shown while it is empty.
688    pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
689        self.bind_prop(text, |text: String| Prop::Placeholder(text))
690    }
691
692    /// The placeholder's color (`cx.color(theme.muted_foreground)`).
693    pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
694        self.bind_prop(color, |color: Hsla| {
695            Prop::PlaceholderColor(Some(color.into()))
696        })
697    }
698
699    /// The selection highlight's color (on iOS also the caret's, unless
700    /// [`Self::caret_color`] is set: UIKit tints both with one).
701    pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
702        self.bind_prop(color, |color: Hsla| {
703            Prop::SelectionColor(Some(color.into()))
704        })
705    }
706
707    /// The caret's color.
708    pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
709        self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
710    }
711
712    /// Hides what is typed (passwords; TS: `masked`).
713    pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
714        self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
715    }
716
717    /// The software keyboard's layout.
718    pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
719        self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
720    }
721
722    /// The software keyboard's light or dark look (iOS; TS:
723    /// `ios={{ keyboardAppearance }}`).
724    pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
725        self.bind_prop(appearance, |appearance: KeyboardAppearance| {
726            Prop::KeyboardAppearance(appearance)
727        })
728    }
729
730    /// The return key's label.
731    pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
732        self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
733    }
734
735    /// Automatic capitals.
736    pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
737        self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
738    }
739
740    /// The system's corrections (default on): spelling and, on iOS and
741    /// macOS, smart quotes, dashes and text replacement.
742    pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
743        self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
744    }
745
746    /// What it holds, for autofill and suggestions.
747    pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
748        self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
749    }
750
751    /// Several lines, growing with the text (return adds a line).
752    pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
753        self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
754    }
755
756    /// Whether a multiline input's scroll bar shows (default yes): the
757    /// platform's indicator, or the app's built-in bar once it set one.
758    pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
759        self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
760    }
761
762    /// At most `length` characters.
763    pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
764        self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
765    }
766
767    /// The text can be selected and copied but not changed.
768    pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
769        self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
770    }
771
772    /// What return does (`submitBehavior`; default: submit and unfocus for
773    /// one line, a line break for several).
774    pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
775        self.bind_prop(behavior, |behavior: SubmitBehavior| {
776            Prop::SubmitBehavior(Some(behavior))
777        })
778    }
779
780    /// What a paste does (`pasteBehavior`; default: insert its text).
781    /// [`Self::on_paste`] hears what was pasted either way.
782    pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
783        self.bind_prop(behavior, Prop::PasteBehavior)
784    }
785
786    /// The user pasted: the text, the files with their bytes (a
787    /// screenshot) and local files' URLs, before the text it inserts is
788    /// reported.
789    pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
790        self.listen(EventKind::Paste, listener.into_listener(), events::paste)
791    }
792
793    /// Focused when it appears.
794    pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
795        self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
796    }
797
798    /// The caret is drawn (default yes; TS: `caret`).
799    pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
800        self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
801    }
802
803    /// Shows the input accessory with this `nativeID` over the keyboard
804    /// ([`input_accessory_view`]; iOS).
805    pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
806        self.bind_prop(native_id, |id: String| {
807            Prop::InputAccessoryViewId(Some(id.into()))
808        })
809    }
810
811    /// Selects `(start, end)` (UTF-16 units; a caret when equal) when the
812    /// input is made and whenever the value changes (TS: the controlled
813    /// `selectedRange`); the user moves it on from there
814    /// ([`Self::on_selection_change`]).
815    pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
816        self.bind_prop(range, |(start, end): (u32, u32)| {
817            Prop::Selection(start, end)
818        })
819    }
820
821    /// The text changed (the new text).
822    pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
823        self.listen(
824            EventKind::ChangeText,
825            listener.into_listener(),
826            events::text,
827        )
828    }
829
830    /// The return (enter) key was pressed (the text).
831    pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
832        self.listen(
833            EventKind::SubmitEditing,
834            listener.into_listener(),
835            events::text,
836        )
837    }
838
839    /// The selection or caret moved.
840    pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
841        self.listen(
842            EventKind::SelectionChange,
843            listener.into_listener(),
844            events::selection,
845        )
846    }
847
848    /// The caret moved: with the selection, or as the text scrolled or
849    /// wrapped again ([`CaretEvent`]: where it is, in the input and in the
850    /// root view).
851    pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
852        self.listen(
853            EventKind::CaretMove,
854            listener.into_listener(),
855            events::caret,
856        )
857    }
858
859    /// A key was pressed: the character, `Backspace` or `Enter`.
860    pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
861        self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
862    }
863
864    /// An input method's composition started, changed or ended (the text
865    /// being composed, empty once it ends): the text is the input's only
866    /// once committed, reported by [`Self::on_change`] first.
867    pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
868        self.listen(
869            EventKind::CompositionChange,
870            listener.into_listener(),
871            events::composition,
872        )
873    }
874
875    /// The text's size changed (multiline inputs growing).
876    pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
877        self.listen(
878            EventKind::ContentSizeChange,
879            listener.into_listener(),
880            events::size,
881        )
882    }
883}
884
885impl Scroll {
886    /// Scrolls horizontally.
887    pub fn horizontal(self) -> Self {
888        self.set(Prop::Horizontal(true))
889    }
890
891    /// Whether the scroll indicator shows (default yes).
892    pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
893        self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
894    }
895
896    /// Pinch zoom between `min` and `max`.
897    pub fn zoom_range(self, min: f32, max: f32) -> Self {
898        self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
899            .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
900    }
901
902    /// The zoom.
903    pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
904        self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
905    }
906
907    /// Pinches may go past the zoom limits and spring back (default yes;
908    /// TS: `bouncesZoom`).
909    pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
910        self.bind_prop(bounces, |bounces: bool| {
911            Prop::Scroll(ScrollProp::BouncesZoom(bounces))
912        })
913    }
914
915    /// The user can pinch to zoom (default yes; TS: `zoomable`).
916    pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
917        self.bind_prop(enabled, |enabled: bool| {
918            Prop::Scroll(ScrollProp::Pinch(enabled))
919        })
920    }
921
922    /// Content smaller than the view sits in its center (zoomed images).
923    pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
924        self.bind_prop(center, |center: bool| {
925            Prop::Scroll(ScrollProp::CenterContent(center))
926        })
927    }
928}
929
930impl super::Scrollable for Scroll {}
931
932impl Screen {
933    fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
934        let mut node = ElNode::new(Tag::HeaderItem);
935        node.key = Some(key.into());
936        set(&mut node, Prop::HeaderSlot(slot));
937        node.children.push(item.into_element().0);
938        self.0.children.push(node);
939        self
940    }
941
942    /// The header's title.
943    pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
944        self.bind_prop(title, |t| {
945            Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
946        })
947    }
948
949    /// Whether the header shows (default true).
950    pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
951        self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
952    }
953
954    /// Whether the system tab bar leaves while this page is on top (default
955    /// false), moving with the transition (iOS and Android).
956    pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
957        self.bind_prop(hides, |v| {
958            Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
959        })
960    }
961
962    /// A large title (iOS); the content scrolls under the header.
963    pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
964        self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
965    }
966
967    /// The content extends under the header.
968    pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
969        self.bind_prop(transparent, |v| {
970            Prop::Screen(ScreenProp::HeaderTransparent(v))
971        })
972    }
973
974    /// The header's colors: `backgroundColor`, `color` (the title's) and
975    /// `tintColor` (the buttons'), as [`super::Style::from_decls`] makes
976    /// them (TS: `headerStyle`); a style of typed styles applies as
977    /// [`Self::header_style_with`]'s do.
978    pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
979        let style = match style.into_reactive() {
980            // Its bound parts are read in the binding, which follows them.
981            super::Reactive::Static(s) if s.1.is_bound() => {
982                super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
983            }
984            style => style,
985        };
986        self.0.bind_attr(style, |a, s: super::Style| {
987            set_in(&mut a.props, Prop::HeaderStyle(s.0));
988            if !s.1.is_empty() {
989                let typed = s.1.resolved();
990                let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
991                set_in(&mut a.props, Prop::HeaderClassList(list));
992            }
993        });
994        self
995    }
996
997    /// The header's colors as typed styles: the background
998    /// ([`super::Styled::bg`]), the title's color
999    /// ([`super::Styled::text_color`]) and the buttons'
1000    /// ([`super::Styled::tint_color`]), theme colors following the
1001    /// appearance natively (TS: `headerClass`). `f` runs again when what it
1002    /// reads changes. [`Self::header_style`] wins over it, key by key.
1003    pub fn header_style_with(
1004        self,
1005        f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1006    ) -> Self {
1007        let list = move || {
1008            let style = f(super::StyleRefinement::default()).resolved();
1009            (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1010        };
1011        self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1012            Prop::HeaderClassList(list)
1013        })
1014    }
1015
1016    /// The label of the back button leading back to this screen (iOS).
1017    pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1018        self.bind_prop(title, |t| {
1019            Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1020        })
1021    }
1022
1023    /// The trailing header button is UIKit's own, drawn instead of the
1024    /// `header_right` view (iOS; a press on it presses that view's first
1025    /// pressable view).
1026    pub fn header_right_system_item(
1027        self,
1028        item: impl IntoReactive<crate::HeaderSystemItem>,
1029    ) -> Self {
1030        self.bind_prop(item, |item| {
1031            Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1032        })
1033    }
1034
1035    /// The leading header button is UIKit's own, drawn instead of the
1036    /// `header_left` view (iOS; a press on it presses that view's first
1037    /// pressable view).
1038    pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1039        self.bind_prop(item, |item| {
1040            Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1041        })
1042    }
1043
1044    /// The trailing header button is UIKit's own showing the SF Symbol of
1045    /// this name, drawn instead of the `header_right` view (iOS; a press on
1046    /// it presses that view's first pressable view).
1047    pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1048        self.bind_prop(name, |n| {
1049            Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1050        })
1051    }
1052
1053    /// The leading header button is UIKit's own showing the SF Symbol of
1054    /// this name, drawn instead of the `header_left` view (iOS; a press on
1055    /// it presses that view's first pressable view).
1056    pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1057        self.bind_prop(name, |n| {
1058            Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1059        })
1060    }
1061
1062    /// Whether the back button shows (default true).
1063    pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1064        self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1065    }
1066
1067    /// The interactive back gesture pops (iOS swipe back, Android
1068    /// predictive back); the back buttons pop either way (default true).
1069    pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1070        self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1071    }
1072
1073    /// The back buttons and the swipe back pop the screen (default true);
1074    /// false keeps it, reporting [`Self::on_back_press`] instead. Decided
1075    /// natively when the system asks, so set it before the user acts.
1076    pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1077        self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1078    }
1079
1080    /// How the screen enters and leaves.
1081    pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1082        self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1083    }
1084
1085    /// The program it comes and goes through instead of its
1086    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
1087    /// go back to it) leaves the change to the animation.
1088    pub fn transition_shader(
1089        self,
1090        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1091    ) -> Self {
1092        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1093            Prop::TransitionShader(s.map(Into::into))
1094        })
1095    }
1096
1097    /// What the status bar shows while the screen is up (iOS and Android;
1098    /// TS: `statusBar`): over the screens below it and the app's default,
1099    /// field by field, as a view controller's `preferredStatusBarStyle`.
1100    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1101        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1102    }
1103
1104    /// An element at the header's start (instead of the back button).
1105    pub fn header_left(self, item: impl IntoElement) -> Self {
1106        self.header_item(HeaderSlot::Left, "header-left", item)
1107    }
1108
1109    /// An element at the header's end.
1110    pub fn header_right(self, item: impl IntoElement) -> Self {
1111        self.header_item(HeaderSlot::Right, "header-right", item)
1112    }
1113
1114    /// An element replacing the title.
1115    pub fn header_title(self, item: impl IntoElement) -> Self {
1116        self.header_item(HeaderSlot::Title, "header-title", item)
1117    }
1118
1119    /// The app's header on platforms without a system header (desktops,
1120    /// the web): placed at the top of the screen, as wide as it and as tall
1121    /// as it lays out, with the content below it (TS: `header`).
1122    pub fn header(self, item: impl IntoElement) -> Self {
1123        self.header_item(HeaderSlot::Header, "header", item)
1124    }
1125
1126    /// The user popped the screen natively (back button, swipe): leave it
1127    /// out of the view (its region).
1128    pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1129        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1130    }
1131
1132    /// The user pressed back on the screen (every back press, whether or
1133    /// not [`Self::pop_on_back`] let it pop).
1134    pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1135        self.listen(
1136            EventKind::BackRequest,
1137            listener.into_listener(),
1138            events::unit,
1139        )
1140    }
1141}
1142
1143impl Overlay {
1144    /// Places it against the element carrying `anchor` (rendered before
1145    /// it), following it as it moves: on the [`Self::placement`] side, on
1146    /// the other when only that one has room, kept inside the safe area.
1147    pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1148        let anchor = *anchor;
1149        self.bind_prop(
1150            move || match anchor.node() {
1151                Some(id) => OverlayAnchor::Node(id),
1152                None => OverlayAnchor::None,
1153            },
1154            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1155        )
1156    }
1157
1158    /// Lays the element carrying `cover`, inside it, over its anchor (a
1159    /// select's selected item over the trigger) instead of placing it on
1160    /// a side ([`crate::overlay::OverlayConfig::cover`]). A ref is not
1161    /// tracked: `shown` (tracked) says when that element is rendered, as
1162    /// its `on_layout` can tell.
1163    pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1164        let cover = *cover;
1165        self.bind_prop(
1166            move || if shown() { cover.node() } else { None },
1167            |id| Prop::Overlay(OverlayProp::Cover(id)),
1168        )
1169    }
1170
1171    /// Places it beside the element carrying `anchor`, outside the edges
1172    /// of the one carrying `edges` (the menu around it), as a submenu
1173    /// beside its row ([`OverlayAnchor::Beside`]).
1174    pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1175        let (anchor, edges) = (*anchor, *edges);
1176        self.bind_prop(
1177            move || match (anchor.node(), edges.node()) {
1178                (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1179                (Some(id), None) => OverlayAnchor::Node(id),
1180                _ => OverlayAnchor::None,
1181            },
1182            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1183        )
1184    }
1185
1186    /// Places it against what the element carrying `anchor` draws: the box
1187    /// around its children, so a trigger in a wrapper its parent stretches
1188    /// is placed against what shows ([`OverlayAnchor::Content`]). A ref a
1189    /// component gives its slot goes by the app's element's own box,
1190    /// whether a TSX or a Rust app filled the slot.
1191    pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1192        let anchor = *anchor;
1193        self.bind_prop(
1194            move || match anchor.node() {
1195                Some(id) => OverlayAnchor::Content(id),
1196                None => OverlayAnchor::None,
1197            },
1198            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1199        )
1200    }
1201
1202    /// Places it against a point of the root view (a touch's `page`: a
1203    /// menu where the pointer is).
1204    pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1205        self.bind_prop(point, |p| {
1206            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1207        })
1208    }
1209
1210    /// Places it against a box of the root view: an input's caret
1211    /// ([`CaretEvent::page_bounds`]), where suggestions for what is being
1212    /// typed open.
1213    pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1214        self.bind_prop(bounds, |b| {
1215            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1216        })
1217    }
1218
1219    /// The side of the anchor it goes on (default below).
1220    pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1221        self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1222    }
1223
1224    /// How it lines up with the anchor along that side (default centered).
1225    pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1226        self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1227    }
1228
1229    /// The gap between the anchor and it.
1230    pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1231        self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1232    }
1233
1234    /// The distance it keeps from the edges of the safe area.
1235    pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1236        self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1237    }
1238
1239    /// A press went down outside it, its anchor and the overlays inside it
1240    /// (where, in the root view). Closing is the listener's: leave it out
1241    /// of the view.
1242    pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1243        self.listen(
1244            EventKind::PressOutside,
1245            listener.into_listener(),
1246            events::page_point,
1247        )
1248    }
1249
1250    /// Escape or the Android back button, while it is the top overlay
1251    /// listening (it takes them from those below, the pages and
1252    /// [`super::on_back_press`]).
1253    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1254        self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1255    }
1256
1257    /// Makes it a hint (a tooltip): shown once the pointer rested on its
1258    /// anchor (its parent without one) for `delay`, until the pointer
1259    /// leaves or presses the anchor, on the desktops only, and while the
1260    /// keyboard focus is on the anchor (or in it, outside an overlay), in
1261    /// every idiom, until the focus leaves; Escape hides it. It is placed
1262    /// against the anchor and should not take the pointer
1263    /// ([`Interactive::pointer_events`] none). [`Self::hint_open`] decides
1264    /// instead of the pointer.
1265    pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1266        self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1267    }
1268
1269    /// A hint shown (`Some(true)`) or hidden (`Some(false)`) whatever the
1270    /// pointer does: its owner follows [`Self::on_hint_show`] /
1271    /// [`Self::on_hint_hide`] (a `Tooltip` controlled by the app). `None`:
1272    /// the pointer decides.
1273    pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1274        self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1275    }
1276
1277    /// The pointer rested on a hint's anchor for its delay, or the
1278    /// keyboard focus came to it: it asks to show (and shows, unless
1279    /// [`Self::hint_open`] decides), with why.
1280    pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1281        self.listen(
1282            EventKind::Show,
1283            listener.into_listener(),
1284            events::hint_reason,
1285        )
1286    }
1287
1288    /// The pointer left or pressed a hint's anchor, the focus left it,
1289    /// Escape was pressed or the hint left the view, after it asked to
1290    /// show: it asks to hide, with why.
1291    pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1292        self.listen(
1293            EventKind::Dismiss,
1294            listener.into_listener(),
1295            events::hint_reason,
1296        )
1297    }
1298
1299    /// The core placed it against its anchor: the side it went on, its
1300    /// frame and the room on that side.
1301    pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1302        self.listen(
1303            EventKind::Position,
1304            listener.into_listener(),
1305            events::overlay_position,
1306        )
1307    }
1308}
1309
1310impl Modal {
1311    /// How it comes in (default: slides up).
1312    pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1313        self.bind_prop(animation, |animation: ModalAnimation| {
1314            Prop::Modal(ModalProp::Animation(animation))
1315        })
1316    }
1317
1318    /// The program it comes and goes through instead of its
1319    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
1320    /// go back to it) leaves the change to the animation.
1321    pub fn transition_shader(
1322        self,
1323        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1324    ) -> Self {
1325        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1326            Prop::TransitionShader(s.map(Into::into))
1327        })
1328    }
1329
1330    /// Full screen, or a sheet (iOS).
1331    pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1332        self.bind_prop(presentation, |presentation: ModalPresentation| {
1333            Prop::Modal(ModalProp::Presentation(presentation))
1334        })
1335    }
1336
1337    /// What the status bar shows while it is presented (iOS and Android;
1338    /// TS: `statusBar`): over what is below it, field by field.
1339    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1340        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1341    }
1342
1343    /// Under the status bar (Android).
1344    pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1345        self.bind_prop(translucent, |translucent: bool| {
1346            Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1347        })
1348    }
1349
1350    /// The orientations it allows while it is presented (iOS; default:
1351    /// those of what presents it).
1352    pub fn supported_orientations(
1353        self,
1354        orientations: impl IntoIterator<Item = Orientation>,
1355    ) -> Self {
1356        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1357        self.set(Prop::Modal(ModalProp::Orientations(bits)))
1358    }
1359
1360    /// Escape and the Android back button close it natively (default
1361    /// true); either way they report [`Self::on_cancel`].
1362    pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1363        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1364    }
1365
1366    /// A press on a backdrop the platform presents itself (a native
1367    /// sheet's) closes it (default true); a backdrop the app renders is
1368    /// the app's to handle.
1369    pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1370        self.bind_prop(close, |v: bool| {
1371            Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1372        })
1373    }
1374
1375    /// Swiping a sheet down closes it natively (default true).
1376    pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1377        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1378    }
1379
1380    /// The user tried to close it (Escape or back, a backdrop press, a
1381    /// swipe down), whether or not it closed: leave it out of the view
1382    /// (its region) to close it.
1383    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1384        self.listen(
1385            EventKind::RequestClose,
1386            listener.into_listener(),
1387            events::unit,
1388        )
1389    }
1390
1391    /// It finished appearing.
1392    pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1393        self.listen(EventKind::Show, listener.into_listener(), events::unit)
1394    }
1395
1396    /// The user or the system closed it.
1397    pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1398        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1399    }
1400}
1401
1402/// An orientation of the screen ([`Modal::supported_orientations`]).
1403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1404pub enum Orientation {
1405    /// Upright.
1406    Portrait,
1407    /// Upside down.
1408    PortraitUpsideDown,
1409    /// Either landscape.
1410    Landscape,
1411    /// Landscape, the top on the left.
1412    LandscapeLeft,
1413    /// Landscape, the top on the right.
1414    LandscapeRight,
1415}
1416
1417impl Orientation {
1418    fn bits(self) -> u8 {
1419        use crate::ModalConfig as M;
1420        match self {
1421            Orientation::Portrait => M::PORTRAIT,
1422            Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1423            Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1424            Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1425            Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1426        }
1427    }
1428}
1429
1430impl WebView {
1431    /// Loads `html` (relative links against `base_url`) instead of a URL;
1432    /// a bound page loads again when it changes.
1433    pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1434        let base_url: Option<Arc<str>> = base_url.map(Into::into);
1435        self.bind_prop(html, move |html: String| {
1436            Prop::Native(NativeProp::Source(WebSource::Html {
1437                html: html.into(),
1438                base_url: base_url.clone(),
1439            }))
1440        })
1441    }
1442
1443    /// Runs after each page loads.
1444    pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1445        self.bind_prop(script, |script: String| {
1446            Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1447        })
1448    }
1449
1450    /// Runs before each page's own scripts.
1451    pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1452        self.bind_prop(script, |script: String| {
1453            Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1454        })
1455    }
1456
1457    /// The user agent it sends.
1458    pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1459        self.bind_prop(agent, |agent: String| {
1460            Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1461        })
1462    }
1463
1464    /// Scrolls (default yes).
1465    pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1466        self.bind_prop(enabled, |enabled: bool| {
1467            Prop::Native(NativeProp::Scrollable(enabled))
1468        })
1469    }
1470
1471    /// Runs the pages' JavaScript (default yes).
1472    pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1473        self.bind_prop(enabled, |enabled: bool| {
1474            Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1475        })
1476    }
1477
1478    /// Swipes go back and forward (iOS).
1479    pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1480        self.bind_prop(enabled, |enabled: bool| {
1481            Prop::Native(NativeProp::BackForwardGestures(enabled))
1482        })
1483    }
1484
1485    /// Keeps the page's website data (cookies, storage, the cache) only
1486    /// as long as the web view, apart from the app's other web views
1487    /// (default no; Android: no HTTP cache and no saved form data). Read
1488    /// when the web view is made, so it takes a value, not a signal.
1489    pub fn incognito(self, incognito: bool) -> Self {
1490        self.set(Prop::Native(NativeProp::Incognito(incognito)))
1491    }
1492
1493    /// Serves the page the URLs of `scheme` (`"app-image"` for
1494    /// `<img src="app-image:1">`) from the app: `handler` answers each
1495    /// request with bytes and a MIME type
1496    /// ([`WebResourceRequest::respond`](crate::web_resource::WebResourceRequest::respond)),
1497    /// now or later and from any thread, and the web engine loads them as
1498    /// it loads any subresource, with no `data:` URL or script in between
1499    /// (iOS and macOS, Linux). The platform calls `handler` on its main
1500    /// thread, so it returns at once and leaves slow work to a thread of
1501    /// its own. Several schemes are several calls; one called again
1502    /// replaces its handler. `scheme` is a letter followed by letters,
1503    /// digits, `+`, `-` or `.`, none of the web's or the system's (`http`,
1504    /// `file`, `data`, ...): another is ignored with a warning. Read when
1505    /// the web view is made, as [`incognito`](Self::incognito)
1506    /// ([`crate::web_resource`]).
1507    pub fn url_scheme(
1508        self,
1509        scheme: &str,
1510        handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1511    ) -> Self {
1512        let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1513            Ok(scheme) => scheme,
1514            Err(e) => {
1515                log::warn!(target: "js", "web view: {e}");
1516                return self;
1517            }
1518        };
1519        let mut schemes = self
1520            .0
1521            .attrs
1522            .props
1523            .iter()
1524            .find_map(|p| match p {
1525                Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1526                _ => None,
1527            })
1528            .unwrap_or_default();
1529        schemes.retain(|s| s.scheme() != scheme.scheme());
1530        schemes.push(scheme);
1531        self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1532    }
1533
1534    /// A page started loading.
1535    pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1536        self.listen(
1537            EventKind::LoadStart,
1538            listener.into_listener(),
1539            events::navigation,
1540        )
1541    }
1542
1543    /// A page loaded.
1544    pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1545        self.listen(
1546            EventKind::Load,
1547            listener.into_listener(),
1548            events::navigation,
1549        )
1550    }
1551
1552    /// A page failed to load (the message).
1553    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1554        self.listen(EventKind::Error, listener.into_listener(), events::message)
1555    }
1556
1557    /// The platform shows no web view here: it has no web engine, or its
1558    /// engine failed to start (the message; TS: `onError` with `code`
1559    /// `"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"`). [`on_error`](Self::on_error)
1560    /// hears it too. [`web_view_available`](crate::element::web_view_available)
1561    /// asks ahead.
1562    pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1563        self.listen(
1564            EventKind::Error,
1565            listener.into_listener(),
1566            events::unavailable,
1567        )
1568    }
1569
1570    /// The page called `window.nsh.postMessage(data)`.
1571    pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1572        self.listen(EventKind::Message, listener.into_listener(), events::data)
1573    }
1574
1575    /// It navigated.
1576    pub fn on_navigation_state_change<M>(
1577        self,
1578        listener: impl IntoListener<WebNavigation, M>,
1579    ) -> Self {
1580        self.listen(
1581            EventKind::NavigationStateChange,
1582            listener.into_listener(),
1583            events::navigation,
1584        )
1585    }
1586}
1587
1588impl Video {
1589    /// Paused.
1590    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1591        self.bind_prop(paused, |paused: bool| {
1592            Prop::Native(NativeProp::Paused(paused))
1593        })
1594    }
1595
1596    /// Without sound.
1597    pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1598        self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1599    }
1600
1601    /// 0..1.
1602    pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1603        self.bind_prop(volume, |volume: f32| {
1604            Prop::Native(NativeProp::Volume(volume))
1605        })
1606    }
1607
1608    /// Playback speed.
1609    pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1610        self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1611    }
1612
1613    /// Starts over at the end.
1614    pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1615        self.bind_prop(repeat, |repeat: bool| {
1616            Prop::Native(NativeProp::Repeat(repeat))
1617        })
1618    }
1619
1620    /// The platform's playback controls.
1621    pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1622        self.bind_prop(controls, |controls: bool| {
1623            Prop::Native(NativeProp::Controls(controls))
1624        })
1625    }
1626
1627    /// Milliseconds between [`Self::on_progress`] events (default 250).
1628    pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1629        self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1630    }
1631
1632    /// What its sound does to the rest of the device's audio while it
1633    /// plays (default: the app's audio settings).
1634    pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1635        self.bind_prop(session, |session: AudioSession| {
1636            Prop::Native(NativeProp::AudioSession(session))
1637        })
1638    }
1639
1640    /// It started loading.
1641    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1642        self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1643    }
1644
1645    /// It loaded: length and size.
1646    pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1647        self.listen(EventKind::Load, listener.into_listener(), events::video)
1648    }
1649
1650    /// It played on.
1651    pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1652        self.listen(
1653            EventKind::Progress,
1654            listener.into_listener(),
1655            events::progress,
1656        )
1657    }
1658
1659    /// It played to its end.
1660    pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1661        self.listen(EventKind::End, listener.into_listener(), events::unit)
1662    }
1663
1664    /// It started (`true`) or stopped buffering.
1665    pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1666        self.listen(
1667            EventKind::Buffer,
1668            listener.into_listener(),
1669            events::buffering,
1670        )
1671    }
1672
1673    /// It failed (the message).
1674    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1675        self.listen(EventKind::Error, listener.into_listener(), events::message)
1676    }
1677}
1678
1679impl NativeView {
1680    /// Its prop `name` (any JSON value), as JS's `nativeComponent` passes it;
1681    /// a bound one is passed again when it changes.
1682    pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1683        let name: Arc<str> = name.into();
1684        self.bind_prop(value, move |value| {
1685            Prop::ComponentProp(name.clone(), Some(value))
1686        })
1687    }
1688
1689    /// Binds its prop `name` to an animated value: the platform hands the
1690    /// value (a number or a color) to the component on every frame it
1691    /// changes, with no engine work per frame (JS: an animated value given
1692    /// to a `nativeComponent` prop). A value set with [`Self::prop`] under
1693    /// that name waits until the binding goes.
1694    pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1695        if let Some(node) = value.animated_node().live() {
1696            set(
1697                &mut self.0,
1698                Prop::ComponentPropBinding(name.into(), Some(node.id())),
1699            );
1700            self.0.attrs.bound.push(node);
1701        }
1702        self
1703    }
1704
1705    /// It emitted an event.
1706    pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1707        self.listen(
1708            EventKind::NativeEvent,
1709            listener.into_listener(),
1710            events::native,
1711        )
1712    }
1713}
1714
1715/// A number in a drawing: a constant, or an animated value the canvas reads
1716/// while it draws (it draws again natively as the value moves).
1717#[derive(Debug, Clone, PartialEq)]
1718pub struct CanvasArg(pub(crate) CanvasArgKind);
1719
1720#[derive(Debug, Clone, PartialEq)]
1721pub(crate) enum CanvasArgKind {
1722    Const(f32),
1723    Node(super::LiveNode),
1724}
1725
1726impl From<f32> for CanvasArg {
1727    fn from(n: f32) -> Self {
1728        Self(CanvasArgKind::Const(n))
1729    }
1730}
1731
1732/// A length (coordinates, sizes, line widths, radii).
1733impl From<Points> for CanvasArg {
1734    fn from(n: Points) -> Self {
1735        Self(CanvasArgKind::Const(n.0))
1736    }
1737}
1738
1739/// An angle (arcs, rotations).
1740impl From<Radians> for CanvasArg {
1741    fn from(n: Radians) -> Self {
1742        Self(CanvasArgKind::Const(n.0))
1743    }
1744}
1745
1746/// An animated value whose owner is gone counts as 0.
1747impl<A: super::Animated> From<&A> for CanvasArg {
1748    fn from(a: &A) -> Self {
1749        Self(match a.animated_node().live() {
1750            Some(node) => CanvasArgKind::Node(node),
1751            None => CanvasArgKind::Const(0.0),
1752        })
1753    }
1754}
1755
1756/// What a drawing fills or strokes with (`fillStyle` / `strokeStyle`): a
1757/// color, a gradient ([`CanvasGradient::linear`], `radial`, `conic`), or a
1758/// animated value interpolating colors
1759/// ([`super::AnimatedNode::interpolate_colors`]), read as it moves.
1760#[derive(Debug, Clone, PartialEq)]
1761pub struct CanvasPaint(CanvasPaintKind);
1762
1763#[derive(Debug, Clone, PartialEq)]
1764enum CanvasPaintKind {
1765    Color(Color),
1766    Gradient(Arc<CanvasGradient>),
1767    Node(super::LiveNode),
1768}
1769
1770impl From<Color> for CanvasPaint {
1771    fn from(color: Color) -> Self {
1772        Self(CanvasPaintKind::Color(color))
1773    }
1774}
1775
1776impl From<Hsla> for CanvasPaint {
1777    fn from(color: Hsla) -> Self {
1778        Color::from(color).into()
1779    }
1780}
1781
1782impl From<Rgba> for CanvasPaint {
1783    fn from(color: Rgba) -> Self {
1784        Color::from(color).into()
1785    }
1786}
1787
1788impl From<CanvasGradient> for CanvasPaint {
1789    fn from(gradient: CanvasGradient) -> Self {
1790        Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
1791    }
1792}
1793
1794impl From<Arc<CanvasGradient>> for CanvasPaint {
1795    fn from(gradient: Arc<CanvasGradient>) -> Self {
1796        Self(CanvasPaintKind::Gradient(gradient))
1797    }
1798}
1799
1800/// An animated value whose owner is gone paints nothing (transparent).
1801impl<A: super::Animated> From<&A> for CanvasPaint {
1802    fn from(a: &A) -> Self {
1803        Self(match a.animated_node().live() {
1804            Some(node) => CanvasPaintKind::Node(node),
1805            None => CanvasPaintKind::Color(Color::TRANSPARENT),
1806        })
1807    }
1808}
1809
1810/// Records a [`Drawing`] with the HTML Canvas 2D operations (Rust names):
1811/// `Painter::new().fill_color(red).fill_rect(px(0.0), px(0.0), w, h).finish()`.
1812/// Coordinates are points from the canvas's top left. Numbers and paints
1813/// may be animated values (the canvas draws again natively as they move);
1814/// operations without a method here are built by hand with
1815/// [`Painter::num`], [`Painter::paint`] and [`Painter::op`]. Text is
1816/// measured with [`super::measure_text`].
1817#[derive(Debug, Clone, Default)]
1818pub struct Painter {
1819    drawing: Drawing,
1820    /// The nodes of the animated values the drawing reads, held with it.
1821    nodes: Vec<super::LiveNode>,
1822}
1823
1824impl Painter {
1825    /// An empty drawing.
1826    pub fn new() -> Self {
1827        Self::default()
1828    }
1829
1830    /// The drawing.
1831    pub fn finish(self) -> Drawing {
1832        self.drawing
1833    }
1834
1835    /// `value` as a number of this drawing, for an operation built by hand
1836    /// ([`Self::op`]): an animated value becomes a slot the canvas reads while
1837    /// it draws, kept alive with the drawing.
1838    pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
1839        match value.into().0 {
1840            CanvasArgKind::Const(n) => Num::Const(n),
1841            CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
1842        }
1843    }
1844
1845    /// `paint` as a paint of this drawing, for an operation built by hand
1846    /// ([`Self::op`]).
1847    pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
1848        match paint.into().0 {
1849            CanvasPaintKind::Color(color) => Paint::Color(color),
1850            CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
1851            CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
1852        }
1853    }
1854
1855    fn slot(&mut self, node: super::LiveNode) -> u16 {
1856        let slot = self.drawing.slot(node.id());
1857        self.nodes.push(node);
1858        slot
1859    }
1860
1861    /// Adds `node`: a part of the drawing that assistive technologies and
1862    /// UI tests see as an element of its own ([`crate::canvas::CanvasNode`]).
1863    pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
1864        self.drawing.nodes.push(node);
1865        self
1866    }
1867
1868    /// Records `op` (one built by hand: its numbers and paints from
1869    /// [`Self::num`] and [`Self::paint`]).
1870    pub fn op(mut self, op: CanvasOp) -> Self {
1871        self.drawing.ops.push(op);
1872        self
1873    }
1874
1875    fn path(self, op: PathOp) -> Self {
1876        self.op(CanvasOp::Path(op))
1877    }
1878
1879    /// Whether `point` (in the canvas, as a touch's location) is inside the
1880    /// current path by `rule`, with the transform, as recorded so far (TS:
1881    /// `cx.isPointInPath(x, y, rule)`). Answered from the geometry here,
1882    /// with no platform round trip; a number given as an animated value
1883    /// counts as 0, as in TS. To find what is under a tap, build the
1884    /// canvas's painter in a function the press handler calls too.
1885    pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
1886        crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
1887    }
1888
1889    /// Whether `point` is on the stroke of the current path with the line
1890    /// width and cap recorded so far (TS: `cx.isPointInStroke(x, y)`;
1891    /// round joins, no dashes). See [`Self::is_point_in_path`].
1892    pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
1893        crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
1894    }
1895
1896    /// Whether `point` is inside `path` by `rule`, with the transform
1897    /// recorded so far (TS: `cx.isPointInPath(path2d, x, y, rule)`): the
1898    /// shape [`Self::fill_path`] drew under a tap. See
1899    /// [`Self::is_point_in_path`].
1900    pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
1901        crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
1902    }
1903
1904    /// Whether `point` is on the stroke of `path` with the transform, line
1905    /// width and cap recorded so far (TS: `cx.isPointInStroke(path2d, x,
1906    /// y)`). See [`Self::is_point_in_path`].
1907    pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
1908        crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
1909    }
1910
1911    /// Saves the state (styles, transform, clip).
1912    pub fn save(self) -> Self {
1913        self.op(CanvasOp::Save)
1914    }
1915
1916    /// Restores the state saved last.
1917    pub fn restore(self) -> Self {
1918        self.op(CanvasOp::Restore)
1919    }
1920
1921    /// Moves the origin.
1922    pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1923        let (x, y) = (self.num(x), self.num(y));
1924        self.op(CanvasOp::Translate(x, y))
1925    }
1926
1927    /// Scales the axes.
1928    pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1929        let (x, y) = (self.num(x), self.num(y));
1930        self.op(CanvasOp::Scale(x, y))
1931    }
1932
1933    /// Rotates the axes, clockwise (a [`Radians`], or an animated value of
1934    /// radians).
1935    pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
1936        let a = self.num(angle);
1937        self.op(CanvasOp::Rotate(a))
1938    }
1939
1940    /// Multiplies the transform by the matrix `[a c e; b d f]`
1941    /// (`transform`).
1942    pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1943        let m = m.map(|n| self.num(n));
1944        self.op(CanvasOp::Transform(m))
1945    }
1946
1947    /// Replaces the transform with the matrix `[a c e; b d f]`
1948    /// (`setTransform`).
1949    pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1950        let m = m.map(|n| self.num(n));
1951        self.op(CanvasOp::SetTransform(m))
1952    }
1953
1954    /// Back to no transform (`resetTransform`).
1955    pub fn reset_transform(self) -> Self {
1956        self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
1957    }
1958
1959    /// Starts a new path.
1960    pub fn begin_path(self) -> Self {
1961        self.op(CanvasOp::BeginPath)
1962    }
1963
1964    /// Starts a subpath at (`x`, `y`).
1965    pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1966        let (x, y) = (self.num(x), self.num(y));
1967        self.path(PathOp::MoveTo(x, y))
1968    }
1969
1970    /// A straight line to (`x`, `y`).
1971    pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1972        let (x, y) = (self.num(x), self.num(y));
1973        self.path(PathOp::LineTo(x, y))
1974    }
1975
1976    /// A quadratic Bézier curve to `to` (`quadraticCurveTo`).
1977    pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
1978        let c = |v: Points| Num::Const(v.0);
1979        self.path(PathOp::QuadTo([
1980            c(control.x),
1981            c(control.y),
1982            c(to.x),
1983            c(to.y),
1984        ]))
1985    }
1986
1987    /// A cubic Bézier curve to `to` (`bezierCurveTo`).
1988    pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
1989        let c = |v: Points| Num::Const(v.0);
1990        self.path(PathOp::CubicTo([
1991            c(c1.x),
1992            c(c1.y),
1993            c(c2.x),
1994            c(c2.y),
1995            c(to.x),
1996            c(to.y),
1997        ]))
1998    }
1999
2000    /// A circular arc around (`x`, `y`); angles clockwise from the x axis
2001    /// ([`Radians`], or animated values of radians).
2002    pub fn arc(
2003        self,
2004        x: impl Into<CanvasArg>,
2005        y: impl Into<CanvasArg>,
2006        radius: impl Into<CanvasArg>,
2007        start: impl Into<CanvasArg>,
2008        end: impl Into<CanvasArg>,
2009    ) -> Self {
2010        self.arc_in(x, y, radius, start, end, false)
2011    }
2012
2013    /// [`Self::arc`] drawn counterclockwise.
2014    pub fn arc_counterclockwise(
2015        self,
2016        x: impl Into<CanvasArg>,
2017        y: impl Into<CanvasArg>,
2018        radius: impl Into<CanvasArg>,
2019        start: impl Into<CanvasArg>,
2020        end: impl Into<CanvasArg>,
2021    ) -> Self {
2022        self.arc_in(x, y, radius, start, end, true)
2023    }
2024
2025    fn arc_in(
2026        mut self,
2027        x: impl Into<CanvasArg>,
2028        y: impl Into<CanvasArg>,
2029        radius: impl Into<CanvasArg>,
2030        start: impl Into<CanvasArg>,
2031        end: impl Into<CanvasArg>,
2032        ccw: bool,
2033    ) -> Self {
2034        let (x, y, radius, start, end) = (
2035            self.num(x),
2036            self.num(y),
2037            self.num(radius),
2038            self.num(start),
2039            self.num(end),
2040        );
2041        self.path(PathOp::Arc {
2042            x,
2043            y,
2044            radius,
2045            start,
2046            end,
2047            ccw,
2048        })
2049    }
2050
2051    /// An arc of `radius` tangent to the lines to `p1` and on to `p2`
2052    /// (`arcTo`): a rounded corner.
2053    pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2054        let c = |v: Points| Num::Const(v.0);
2055        self.path(PathOp::ArcTo([
2056            c(p1.x),
2057            c(p1.y),
2058            c(p2.x),
2059            c(p2.y),
2060            c(radius),
2061        ]))
2062    }
2063
2064    /// An elliptical arc around `center` with radii `radii` turned by
2065    /// `rotation`; angles clockwise (`counterclockwise` draws the other
2066    /// way).
2067    pub fn ellipse(
2068        self,
2069        center: Point<Points>,
2070        radii: Size<Points>,
2071        rotation: Radians,
2072        start: Radians,
2073        end: Radians,
2074        counterclockwise: bool,
2075    ) -> Self {
2076        let c = Num::Const;
2077        self.path(PathOp::Ellipse {
2078            geometry: [
2079                c(center.x.0),
2080                c(center.y.0),
2081                c(radii.width.0),
2082                c(radii.height.0),
2083                c(rotation.0),
2084            ],
2085            start: c(start.0),
2086            end: c(end.0),
2087            ccw: counterclockwise,
2088        })
2089    }
2090
2091    /// A rectangle subpath.
2092    pub fn rect(self, rect: Bounds<Points>) -> Self {
2093        self.path(PathOp::Rect(nums(rect)))
2094    }
2095
2096    /// A rectangle subpath with round corners (one radius for all).
2097    pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2098        self.round_rect_corners(rect, Corners::all(radius))
2099    }
2100
2101    /// A rectangle subpath with round corners.
2102    pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2103        let c = |v: Points| Num::Const(v.0);
2104        self.path(PathOp::RoundRect(
2105            nums(rect),
2106            [
2107                c(radii.top_left),
2108                c(radii.top_right),
2109                c(radii.bottom_right),
2110                c(radii.bottom_left),
2111            ],
2112        ))
2113    }
2114
2115    /// A straight line back to the subpath's start.
2116    pub fn close_path(self) -> Self {
2117        self.path(PathOp::Close)
2118    }
2119
2120    /// Fills the current path.
2121    pub fn fill(self) -> Self {
2122        self.fill_with(FillRule::NonZero)
2123    }
2124
2125    /// Fills the current path by `rule`.
2126    pub fn fill_with(self, rule: FillRule) -> Self {
2127        self.op(CanvasOp::Fill(None, rule))
2128    }
2129
2130    /// Fills `path` (TS: `fill(path2d)`; parse SVG data once with
2131    /// [`crate::canvas::svg_path`]).
2132    pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2133        self.op(CanvasOp::Fill(Some(path.clone()), rule))
2134    }
2135
2136    /// Fills SVG path data (parsed now: [`Self::fill_path`] reuses a
2137    /// parsed path).
2138    pub fn fill_svg(self, data: &str) -> Self {
2139        self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2140    }
2141
2142    /// Strokes the current path.
2143    pub fn stroke(self) -> Self {
2144        self.op(CanvasOp::Stroke(None))
2145    }
2146
2147    /// Strokes `path` (TS: `stroke(path2d)`).
2148    pub fn stroke_path(self, path: &Path) -> Self {
2149        self.op(CanvasOp::Stroke(Some(path.clone())))
2150    }
2151
2152    /// Strokes SVG path data (parsed now).
2153    pub fn stroke_svg(self, data: &str) -> Self {
2154        self.stroke_path(&crate::canvas::svg_path(data))
2155    }
2156
2157    /// Clips to the current path.
2158    pub fn clip(self) -> Self {
2159        self.clip_with(FillRule::NonZero)
2160    }
2161
2162    /// Clips to the current path by `rule`.
2163    pub fn clip_with(self, rule: FillRule) -> Self {
2164        self.op(CanvasOp::Clip(None, rule))
2165    }
2166
2167    /// Clips to `path` (TS: `clip(path2d)`).
2168    pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2169        self.op(CanvasOp::Clip(Some(path.clone()), rule))
2170    }
2171
2172    /// Fills a rectangle (its numbers [`Points`], or animated values).
2173    pub fn fill_rect(
2174        mut self,
2175        x: impl Into<CanvasArg>,
2176        y: impl Into<CanvasArg>,
2177        w: impl Into<CanvasArg>,
2178        h: impl Into<CanvasArg>,
2179    ) -> Self {
2180        let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2181        self.op(CanvasOp::FillRect([x, y, w, h]))
2182    }
2183
2184    /// Strokes a rectangle.
2185    pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2186        self.op(CanvasOp::StrokeRect(nums(rect)))
2187    }
2188
2189    /// Makes a rectangle transparent.
2190    pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2191        self.op(CanvasOp::ClearRect(nums(rect)))
2192    }
2193
2194    /// Fills with `color`.
2195    pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2196        self.fill_style(color.into())
2197    }
2198
2199    /// Strokes with `color`.
2200    pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2201        self.stroke_style(color.into())
2202    }
2203
2204    /// Fills with `paint`: a color, a gradient or an animated value of colors
2205    /// (`fillStyle`).
2206    pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2207        let paint = self.paint(paint);
2208        self.op(CanvasOp::FillStyle(paint))
2209    }
2210
2211    /// Fills with the canvas view's `fill` style (CSS's, inherited from the
2212    /// views around it; `currentColor` is its text color), or `initial`
2213    /// where nothing sets one: shapes a component draws take the app's
2214    /// `fill-*` classes, and follow them and the appearance without being
2215    /// drawn again ([`Drawing::view_paints`]).
2216    pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2217        self.view_paint(
2218            ViewPaint::Fill(initial),
2219            CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2220        )
2221    }
2222
2223    /// Strokes with the canvas view's `stroke` style, or `initial` where
2224    /// nothing sets one ([`Self::fill_style_from_view`]).
2225    pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2226        self.view_paint(
2227            ViewPaint::Stroke(initial),
2228            CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2229        )
2230    }
2231
2232    /// Strokes as wide as the canvas view's `strokeWidth` style (1 where
2233    /// nothing sets one, CSS's initial value).
2234    pub fn line_width_from_view(self) -> Self {
2235        self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2236    }
2237
2238    /// Dashes strokes as the canvas view's `strokeDasharray` style does
2239    /// (solid where nothing sets one).
2240    pub fn line_dash_from_view(self) -> Self {
2241        self.view_paint(
2242            ViewPaint::StrokeDasharray,
2243            CanvasOp::LineDash(Arc::from([])),
2244        )
2245    }
2246
2247    /// Fills the current path with the canvas view's background: its
2248    /// `backgroundColor` and its `backgroundImage` gradients (`bg-*`,
2249    /// `bg-linear-*` classes, the appearance's colors), positioned over
2250    /// `area` (this drawing's coordinates) as over a box of that size. The
2251    /// view then draws no background of its own: the background shows only
2252    /// where the path fills, as CSS's `clip-path` shows a box's
2253    /// ([`ViewPaint::Background`]). The canvas's state is kept around the
2254    /// fill.
2255    pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2256        self.view_paint(
2257            ViewPaint::Background {
2258                area,
2259                rule: FillRule::NonZero,
2260            },
2261            CanvasOp::Fill(None, FillRule::NonZero),
2262        )
2263    }
2264
2265    fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2266        let at = self.drawing.ops.len() as u32;
2267        self.drawing.view_paints.push((at, view));
2268        self.op(placeholder)
2269    }
2270
2271    /// Strokes with `paint` (`strokeStyle`).
2272    pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2273        let paint = self.paint(paint);
2274        self.op(CanvasOp::StrokeStyle(paint))
2275    }
2276
2277    /// The stroke width.
2278    pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2279        let w = self.num(width);
2280        self.op(CanvasOp::LineWidth(w))
2281    }
2282
2283    /// How strokes end.
2284    pub fn line_cap(self, cap: LineCap) -> Self {
2285        self.op(CanvasOp::LineCap(cap))
2286    }
2287
2288    /// How stroke segments join.
2289    pub fn line_join(self, join: LineJoin) -> Self {
2290        self.op(CanvasOp::LineJoin(join))
2291    }
2292
2293    /// How far mitered joins reach, in line widths (`miterLimit`; at least
2294    /// 1).
2295    pub fn miter_limit(self, limit: f32) -> Self {
2296        self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2297    }
2298
2299    /// Dashes: lengths of dashes and gaps.
2300    pub fn line_dash(self, segments: &[Points]) -> Self {
2301        self.op(CanvasOp::LineDash(segments.into()))
2302    }
2303
2304    /// Where the dashes start along the line (`lineDashOffset`; an animated
2305    /// value marches them).
2306    pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2307        let o = self.num(offset);
2308        self.op(CanvasOp::LineDashOffset(o))
2309    }
2310
2311    /// The opacity of what is drawn next.
2312    pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2313        let a = self.num(alpha);
2314        self.op(CanvasOp::GlobalAlpha(a))
2315    }
2316
2317    /// How what is drawn next combines with the canvas.
2318    pub fn composite(self, composite: Composite) -> Self {
2319        self.op(CanvasOp::Composite(composite))
2320    }
2321
2322    /// Shadows of what is drawn next.
2323    pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2324        self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2325            .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2326            .op(CanvasOp::ShadowOffset(offset))
2327    }
2328
2329    /// The font (CSS `font` shorthand: `"600 14px Inter"`); an invalid one
2330    /// keeps the previous font, as in HTML.
2331    pub fn font(self, font: &str) -> Self {
2332        match CanvasFont::parse(font) {
2333            Some(font) => self.op(CanvasOp::Font(font)),
2334            None => self,
2335        }
2336    }
2337
2338    /// The number forms of text (TS: `fontVariantNumeric`): with
2339    /// [`crate::style::FontVariant::TABULAR_NUMS`] figures have equal widths, so changing
2340    /// values do not jitter; `FontVariant::default()` keeps the font's.
2341    pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2342        self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2343            numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2344        )))
2345    }
2346
2347    /// Where text sits relative to its x.
2348    pub fn text_align(self, align: CanvasTextAlign) -> Self {
2349        self.op(CanvasOp::TextAlign(align))
2350    }
2351
2352    /// Where text sits relative to its y.
2353    pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2354        self.op(CanvasOp::TextBaseline(baseline))
2355    }
2356
2357    /// Fills `text` at (`x`, `y`).
2358    pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2359        self.text(text, x, y, None, false)
2360    }
2361
2362    /// Fills `text` at (`x`, `y`), narrowed to fit `max_width`.
2363    pub fn fill_text_max_width(
2364        self,
2365        text: &str,
2366        x: impl Into<CanvasArg>,
2367        y: impl Into<CanvasArg>,
2368        max_width: Points,
2369    ) -> Self {
2370        self.text(text, x, y, Some(max_width), false)
2371    }
2372
2373    /// Strokes the outline of `text` at (`x`, `y`).
2374    pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2375        self.text(text, x, y, None, true)
2376    }
2377
2378    /// Strokes the outline of `text` at (`x`, `y`), narrowed to fit
2379    /// `max_width`.
2380    pub fn stroke_text_max_width(
2381        self,
2382        text: &str,
2383        x: impl Into<CanvasArg>,
2384        y: impl Into<CanvasArg>,
2385        max_width: Points,
2386    ) -> Self {
2387        self.text(text, x, y, Some(max_width), true)
2388    }
2389
2390    fn text(
2391        mut self,
2392        text: &str,
2393        x: impl Into<CanvasArg>,
2394        y: impl Into<CanvasArg>,
2395        max_width: Option<Points>,
2396        stroke: bool,
2397    ) -> Self {
2398        let (text, x, y) = (text.into(), self.num(x), self.num(y));
2399        self.op(if stroke {
2400            CanvasOp::StrokeText {
2401                text,
2402                x,
2403                y,
2404                max_width,
2405            }
2406        } else {
2407            CanvasOp::FillText {
2408                text,
2409                x,
2410                y,
2411                max_width,
2412            }
2413        })
2414    }
2415
2416    /// Draws the image at `uri` (a URL or `asset:/path`) into `dest`.
2417    pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2418        self.draw_image_part(uri, None, dest)
2419    }
2420
2421    /// Draws the part `source` of the image at `uri` (in the image's
2422    /// pixels; `None`: all of it) into `dest`.
2423    pub fn draw_image_part(
2424        self,
2425        uri: &str,
2426        source: Option<Bounds<ScaledPixels>>,
2427        dest: Bounds<Points>,
2428    ) -> Self {
2429        self.op(CanvasOp::DrawImage {
2430            image: CanvasImage { uri: uri.into() },
2431            source,
2432            dest: nums(dest),
2433        })
2434    }
2435}
2436
2437/// `[x, y, w, h]` of `rect`, as a recorded rectangle's numbers.
2438fn nums(rect: Bounds<Points>) -> [Num; 4] {
2439    [
2440        rect.origin.x,
2441        rect.origin.y,
2442        rect.size.width,
2443        rect.size.height,
2444    ]
2445    .map(|v| Num::Const(v.0))
2446}
2447
2448impl From<Drawing> for Painter {
2449    fn from(drawing: Drawing) -> Self {
2450        Self {
2451            drawing,
2452            nodes: Vec::new(),
2453        }
2454    }
2455}
2456
2457crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2458
2459/// A program where an optional one goes (`.transition_shader(wipe)`).
2460impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2461    fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2462        super::Reactive::Static(Some(self))
2463    }
2464}
2465
2466/// A backdrop where an optional one goes (`.macos_backdrop(backdrop)`).
2467impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2468    fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2469        super::Reactive::Static(Some(self))
2470    }
2471}
2472
2473#[cfg(test)]
2474mod tests {
2475    use super::*;
2476    use crate::{
2477        element::{
2478            AnimatedValue,
2479            reactive::{Runtime, create_root, signal},
2480        },
2481        shader::{ShaderUniforms, UniformValue},
2482    };
2483
2484    fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2485        attrs
2486            .props
2487            .iter()
2488            .find_map(|p| match p {
2489                Prop::Uniforms(u) => Some(u.clone()),
2490                _ => None,
2491            })
2492            .unwrap_or_default()
2493    }
2494
2495    /// The animation nodes released since the last call.
2496    fn released(executor: &super::super::task::Executor) -> usize {
2497        executor
2498            .take_actions()
2499            .into_iter()
2500            .filter(|a| {
2501                matches!(
2502                    a,
2503                    super::super::task::Action::Animation(
2504                        crate::animation::AnimationOp::Release { .. }
2505                    )
2506                )
2507            })
2508            .count()
2509    }
2510
2511    fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2512        u.0.iter()
2513            .find(|(n, _)| &**n == name)
2514            .map(|(_, v)| v.clone())
2515    }
2516
2517    #[test]
2518    fn screens_and_modals_take_a_transition_shader() {
2519        let runtime = Runtime::default();
2520        let _entered = runtime.enter();
2521        let source = "struct Uniforms { edge: f32 }\n\
2522            fn shade(uv: vec2f) -> vec4f {\n    \
2523            return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2524        let shader = crate::shader::Shader::compile(source).expect("compiles");
2525        let wipe = crate::shader::TransitionShader::new(shader)
2526            .uniform("edge", 1.0_f32)
2527            .duration(std::time::Duration::from_millis(400));
2528        let expected = crate::shader::NavShaderSpec {
2529            source: source.into(),
2530            uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2531            duration: Some(400.0),
2532        };
2533        let spec = |attrs: &super::super::builder::Attrs| {
2534            attrs.props.iter().find_map(|p| match p {
2535                Prop::TransitionShader(s) => Some(s.clone()),
2536                _ => None,
2537            })
2538        };
2539        let page = screen().transition_shader(wipe.clone()).0;
2540        assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2541        let dialog = modal().transition_shader(wipe.clone()).0;
2542        assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2543        // A binding goes back to the page's or the dialog's own animation.
2544        let on = signal(true);
2545        let bound = screen()
2546            .transition_shader(move || on.get().then(|| wipe.clone()))
2547            .0;
2548        assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
2549        on.set(false);
2550        assert_eq!(spec(&bound.resolved_attrs()), Some(None));
2551    }
2552
2553    #[test]
2554    fn uniform_takes_static_bound_and_animated_values() {
2555        let runtime = Runtime::default();
2556        let _entered = runtime.enter();
2557        let executor = std::rc::Rc::new(super::super::task::Executor::default());
2558        let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
2559        let speed = signal(1.0_f32);
2560        let view = shader()
2561            .uniform("center", [0.5_f32, 0.5])
2562            .uniform("wave", &wave)
2563            .uniform("speed", move || speed.get());
2564        let node = view.0;
2565
2566        // The static and animated ones are set at once; the animated one by
2567        // its node, which the element holds.
2568        let set = uniforms(&node.attrs);
2569        assert_eq!(
2570            value(&set, "center"),
2571            Some(UniformValue::List(vec![
2572                UniformValue::Number(0.5),
2573                UniformValue::Number(0.5)
2574            ]))
2575        );
2576        let id = wave.node().live().expect("live").id();
2577        assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
2578        assert_eq!(
2579            node.attrs.bound.len(),
2580            1,
2581            "the element holds the animated node"
2582        );
2583        assert_eq!(
2584            value(&set, "speed"),
2585            None,
2586            "a bound one is applied when resolved"
2587        );
2588
2589        // The bound one follows its signal.
2590        assert_eq!(
2591            value(&uniforms(&node.resolved_attrs()), "speed"),
2592            Some(UniformValue::Number(1.0))
2593        );
2594        speed.set(2.0);
2595        assert_eq!(
2596            value(&uniforms(&node.resolved_attrs()), "speed"),
2597            Some(UniformValue::Number(2.0))
2598        );
2599
2600        // The node outlives the owner of the handle it came from.
2601        value_owner.dispose();
2602        assert_eq!(released(&executor), 0, "the view keeps the animated node");
2603        drop(node);
2604        assert_eq!(released(&executor), 1, "and lets it go with the view");
2605    }
2606
2607    #[test]
2608    fn a_later_uniform_replaces_one_of_the_same_name() {
2609        let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
2610        let set = uniforms(&view.0.attrs);
2611        assert_eq!(set.0.len(), 1);
2612        assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
2613    }
2614
2615    #[test]
2616    fn web_view_url_scheme_builder_collects_schemes() {
2617        let web = web_view_html("<img src=\"a:1\">", None)
2618            .url_scheme("a", |request| request.fail())
2619            .url_scheme("b", |request| request.fail())
2620            // Replaces `a`'s handler.
2621            .url_scheme("A", |request| request.fail())
2622            // Not a scheme the app may serve: ignored.
2623            .url_scheme("https", |request| request.fail());
2624        let schemes: Vec<String> = web
2625            .0
2626            .attrs
2627            .props
2628            .iter()
2629            .find_map(|p| match p {
2630                Prop::Native(NativeProp::UrlSchemes(list)) => {
2631                    Some(list.iter().map(|s| s.scheme().to_owned()).collect())
2632                }
2633                _ => None,
2634            })
2635            .unwrap();
2636        assert_eq!(schemes, ["b", "a"]);
2637    }
2638}