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