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, HeaderTitleAlign, Hsla,
20    JsonValue, KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp,
21    NativeProp, OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType,
22    Rgba, ScreenAnimation, ScreenProp, ScrollProp, SheetDetent, Size, StatusBarSetting,
23    SubmitBehavior, Tag, WebSource,
24    canvas::{
25        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
26        Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
27    },
28    geometry::{Bounds, Corners, Percentage, Point, Radians, ScaledPixels},
29    js::host::HostProps,
30    overlay::{Align, OverlayAnchor, Placement},
31    style::SvgPaint,
32};
33
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; or
776    /// a built-in bar of this input's own theme (TS `scrollbar={theme}`:
777    /// `nsh_base::ScrollbarTheme` converts into a setting). The built-in
778    /// bar lies over the input's frame, padding included, while the text
779    /// stays in the content box.
780    pub fn scrollbar(self, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
781        self.bind_prop(setting, Prop::Scrollbar)
782    }
783
784    /// At most `length` characters, counted as Unicode scalar values
785    /// (Rust's `char`; an emoji such as 😀 is one) on every platform. A
786    /// longer paste goes in cut to what fits, between user-perceived
787    /// characters.
788    pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
789        self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
790    }
791
792    /// The text can be selected and copied but not changed.
793    pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
794        self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
795    }
796
797    /// What return does (`submitBehavior`; default: submit and unfocus for
798    /// one line, a line break for several).
799    pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
800        self.bind_prop(behavior, |behavior: SubmitBehavior| {
801            Prop::SubmitBehavior(Some(behavior))
802        })
803    }
804
805    /// What a paste does (`pasteBehavior`; default: insert its text).
806    /// [`Self::on_paste`] hears what was pasted either way.
807    pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
808        self.bind_prop(behavior, Prop::PasteBehavior)
809    }
810
811    /// Reads pasted files of at most `bytes` bytes (`pasteMaxSize`); a
812    /// larger one reaches [`Self::on_paste`] in
813    /// [`PasteEvent::too_large`], its name, type and size only. Default:
814    /// every file is read.
815    pub fn paste_max_size(self, bytes: impl IntoReactive<u64>) -> Self {
816        self.bind_prop(bytes, |bytes: u64| Prop::PasteMaxSize(Some(bytes)))
817    }
818
819    /// The user pasted: the text, the files with their bytes (a
820    /// screenshot) and local files' URLs, before the text it inserts is
821    /// reported.
822    pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
823        self.listen(EventKind::Paste, listener.into_listener(), events::paste)
824    }
825
826    /// Focused when it appears.
827    pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
828        self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
829    }
830
831    /// Selects the whole text when the input takes the focus (TS:
832    /// `selectTextOnFocus`); a click that drags or extends a selection keeps
833    /// the user's.
834    pub fn select_text_on_focus(self, select: impl IntoReactive<bool>) -> Self {
835        self.bind_prop(select, |select: bool| Prop::SelectTextOnFocus(select))
836    }
837
838    /// The caret is drawn (default yes; TS: `caret`).
839    pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
840        self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
841    }
842
843    /// Shows the input accessory with this `nativeID` over the keyboard
844    /// ([`input_accessory_view`]; iOS).
845    pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
846        self.bind_prop(native_id, |id: String| {
847            Prop::InputAccessoryViewId(Some(id.into()))
848        })
849    }
850
851    /// Selects `(start, end)` (UTF-16 units; a caret when equal) when the
852    /// input is made and whenever the value changes (TS: the controlled
853    /// `selectedRange`); the user moves it on from there
854    /// ([`Self::on_selection_change`]).
855    pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
856        self.bind_prop(range, |(start, end): (u32, u32)| {
857            Prop::Selection(start, end)
858        })
859    }
860
861    /// The text changed (the new text).
862    pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
863        self.listen(
864            EventKind::ChangeText,
865            listener.into_listener(),
866            events::text,
867        )
868    }
869
870    /// The return (enter) key was pressed (the text).
871    pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
872        self.listen(
873            EventKind::SubmitEditing,
874            listener.into_listener(),
875            events::text,
876        )
877    }
878
879    /// The selection or caret moved.
880    pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
881        self.listen(
882            EventKind::SelectionChange,
883            listener.into_listener(),
884            events::selection,
885        )
886    }
887
888    /// The caret moved: with the selection, or as the text scrolled or
889    /// wrapped again ([`CaretEvent`]: where it is, in the input and in the
890    /// root view).
891    pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
892        self.listen(
893            EventKind::CaretMove,
894            listener.into_listener(),
895            events::caret,
896        )
897    }
898
899    /// A key was pressed: the character, `Backspace`, `Enter`, `Escape`,
900    /// `ArrowUp` or `ArrowDown`.
901    pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
902        self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
903    }
904
905    /// An input method's composition started, changed or ended (the text
906    /// being composed, empty once it ends): the text is the input's only
907    /// once committed, reported by [`Self::on_change`] first.
908    pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
909        self.listen(
910            EventKind::CompositionChange,
911            listener.into_listener(),
912            events::composition,
913        )
914    }
915
916    /// The text's size changed (multiline inputs growing).
917    pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
918        self.listen(
919            EventKind::ContentSizeChange,
920            listener.into_listener(),
921            events::size,
922        )
923    }
924}
925
926impl Scroll {
927    /// Scrolls horizontally.
928    pub fn horizontal(self) -> Self {
929        self.set(Prop::Horizontal(true))
930    }
931
932    /// Whether the scroll indicator shows (default yes); or a built-in bar
933    /// of this view's own theme (TS `scrollbar={theme}`:
934    /// `nsh_base::ScrollbarTheme` converts into a setting).
935    pub fn scrollbar(self, setting: impl IntoReactive<crate::ScrollbarSetting>) -> Self {
936        self.bind_prop(setting, Prop::Scrollbar)
937    }
938
939    /// Pinch zoom between `min` and `max`.
940    pub fn zoom_range(self, min: f32, max: f32) -> Self {
941        self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
942            .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
943    }
944
945    /// The zoom.
946    pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
947        self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
948    }
949
950    /// Pinches may go past the zoom limits and spring back (default yes;
951    /// TS: `bouncesZoom`).
952    pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
953        self.bind_prop(bounces, |bounces: bool| {
954            Prop::Scroll(ScrollProp::BouncesZoom(bounces))
955        })
956    }
957
958    /// The user can pinch to zoom (default yes; TS: `zoomable`).
959    pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
960        self.bind_prop(enabled, |enabled: bool| {
961            Prop::Scroll(ScrollProp::Pinch(enabled))
962        })
963    }
964
965    /// Content smaller than the view sits in its center (zoomed images).
966    pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
967        self.bind_prop(center, |center: bool| {
968            Prop::Scroll(ScrollProp::CenterContent(center))
969        })
970    }
971}
972
973impl super::Scrollable for Scroll {}
974
975impl Screen {
976    fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
977        let mut node = ElNode::new(Tag::HeaderItem);
978        node.key = Some(key.into());
979        set(&mut node, Prop::HeaderSlot(slot));
980        node.children.push(item.into_element().0);
981        self.0.children.push(node);
982        self
983    }
984
985    /// The header's title.
986    pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
987        self.bind_prop(title, |t| {
988            Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
989        })
990    }
991
992    /// Whether the header shows (default true).
993    pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
994        self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
995    }
996
997    /// Whether the system tab bar leaves while this page is on top (default
998    /// false), moving with the transition (iOS and Android).
999    pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
1000        self.bind_prop(hides, |v| {
1001            Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
1002        })
1003    }
1004
1005    /// The orientations the screen may take while the page is shown (iOS
1006    /// and Android; default: the app's). Of the pages displayed, the one
1007    /// shown most recently with a setting decides.
1008    pub fn supported_orientations(
1009        self,
1010        orientations: impl IntoIterator<Item = Orientation>,
1011    ) -> Self {
1012        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1013        self.set(Prop::Screen(ScreenProp::Orientations(bits)))
1014    }
1015
1016    /// A large title (iOS); the content scrolls under the header.
1017    pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
1018        self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
1019    }
1020
1021    /// The content extends under the header.
1022    pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
1023        self.bind_prop(transparent, |v| {
1024            Prop::Screen(ScreenProp::HeaderTransparent(v))
1025        })
1026    }
1027
1028    /// The hairline under the header (iOS; on by default, as UIKit's opaque
1029    /// bars draw it). Off matches iOS 26's bars, which separate the
1030    /// content by the scroll edge effect instead (TS: `headerShadowVisible`).
1031    pub fn header_shadow_visible(self, visible: impl IntoReactive<bool>) -> Self {
1032        self.bind_prop(visible, |v| {
1033            Prop::Screen(ScreenProp::HeaderShadowVisible(v))
1034        })
1035    }
1036
1037    /// Where the title sits in the header (TS: `headerTitleAlign`): at the
1038    /// start (the default) or centered. Android's header follows it; iOS's
1039    /// system bar always centers the title and ignores the value.
1040    pub fn header_title_align(self, align: impl IntoReactive<HeaderTitleAlign>) -> Self {
1041        self.bind_prop(align, |a| Prop::Screen(ScreenProp::HeaderTitleAlign(a)))
1042    }
1043
1044    /// With [`Self::header_transparent`], the header stays clear while the
1045    /// content rests at its top and shows its background (UIKit's default,
1046    /// or [`Self::header_style_with`]'s color) once the content scrolls
1047    /// under it, as UIKit's own bars do (iOS; off by default; TS:
1048    /// `headerBackgroundOnScroll`).
1049    pub fn header_background_on_scroll(self, on: impl IntoReactive<bool>) -> Self {
1050        self.bind_prop(on, |v| {
1051            Prop::Screen(ScreenProp::HeaderBackgroundOnScroll(v))
1052        })
1053    }
1054
1055    /// The header's colors: `backgroundColor`, `color` (the title's) and
1056    /// `tintColor` (the buttons'), as [`super::Style::from_decls`] makes
1057    /// them (TS: `headerStyle`); a style of typed styles applies as
1058    /// [`Self::header_style_with`]'s do.
1059    pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
1060        let style = match style.into_reactive() {
1061            // Its bound parts are read in the binding, which follows them.
1062            super::Reactive::Static(s) if s.1.is_bound() => {
1063                super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
1064            }
1065            style => style,
1066        };
1067        self.0.bind_attr(style, |a, s: super::Style| {
1068            set_in(&mut a.props, Prop::HeaderStyle(s.0));
1069            if !s.1.is_empty() {
1070                let typed = s.1.resolved();
1071                let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
1072                set_in(&mut a.props, Prop::HeaderClassList(list));
1073            }
1074        });
1075        self
1076    }
1077
1078    /// The header's colors as typed styles: the background
1079    /// ([`super::Styled::bg`]), the title's color
1080    /// ([`super::Styled::text_color`]) and the buttons'
1081    /// ([`super::Styled::tint_color`]), theme colors following the
1082    /// appearance natively (TS: `headerClass`). `f` runs again when what it
1083    /// reads changes. [`Self::header_style`] wins over it, key by key.
1084    pub fn header_style_with(
1085        self,
1086        f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
1087    ) -> Self {
1088        let list = move || {
1089            let style = f(super::StyleRefinement::default()).resolved();
1090            (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
1091        };
1092        self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
1093            Prop::HeaderClassList(list)
1094        })
1095    }
1096
1097    /// The label of the back button leading back to this screen (iOS).
1098    pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
1099        self.bind_prop(title, |t| {
1100            Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
1101        })
1102    }
1103
1104    /// The trailing header button is UIKit's own, drawn instead of the
1105    /// `header_right` view (iOS; a press on it presses that view's first
1106    /// pressable view).
1107    pub fn header_right_system_item(
1108        self,
1109        item: impl IntoReactive<crate::HeaderSystemItem>,
1110    ) -> Self {
1111        self.bind_prop(item, |item| {
1112            Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
1113        })
1114    }
1115
1116    /// The leading header button is UIKit's own, drawn instead of the
1117    /// `header_left` view (iOS; a press on it presses that view's first
1118    /// pressable view).
1119    pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
1120        self.bind_prop(item, |item| {
1121            Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
1122        })
1123    }
1124
1125    /// The trailing header button is UIKit's own showing the SF Symbol of
1126    /// this name, drawn instead of the `header_right` view (iOS; a press on
1127    /// it presses that view's first pressable view).
1128    pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1129        self.bind_prop(name, |n| {
1130            Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
1131        })
1132    }
1133
1134    /// The leading header button is UIKit's own showing the SF Symbol of
1135    /// this name, drawn instead of the `header_left` view (iOS; a press on
1136    /// it presses that view's first pressable view).
1137    pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
1138        self.bind_prop(name, |n| {
1139            Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
1140        })
1141    }
1142
1143    /// The trailing header buttons are UIKit's own (`ios={{
1144    /// headerRightItems }}`): a non-empty list wins over
1145    /// [`Self::header_right_system_item`] / [`Self::header_right_symbol`]
1146    /// and leaves the `header_right` view out of the iOS bar. Empty is
1147    /// unset. Each item's [`super::header::HeaderItem::on_press`] and its
1148    /// menu items' [`super::desktop::MenuItem::on_select`] run when the
1149    /// platform reports their ids as the root's [`EventKind::Menu`].
1150    pub fn header_right_items(
1151        self,
1152        items: impl IntoReactive<Vec<super::header::HeaderItem>>,
1153    ) -> Self {
1154        self.bind_prop(items, |items| {
1155            Prop::Screen(ScreenProp::HeaderRightItems(super::header::register(items)))
1156        })
1157    }
1158
1159    /// Whether the back button shows (default true).
1160    pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
1161        self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
1162    }
1163
1164    /// The interactive back gesture pops (iOS swipe back, Android
1165    /// predictive back); the back buttons pop either way (default true).
1166    pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
1167        self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
1168    }
1169
1170    /// The back buttons and the swipe back pop the screen (default true);
1171    /// false keeps it, reporting [`Self::on_back_press`] instead. Decided
1172    /// natively when the system asks, so set it before the user acts.
1173    pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
1174        self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
1175    }
1176
1177    /// How the screen enters and leaves.
1178    pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
1179        self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
1180    }
1181
1182    /// The program it comes and goes through instead of its
1183    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
1184    /// go back to it) leaves the change to the animation.
1185    pub fn transition_shader(
1186        self,
1187        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1188    ) -> Self {
1189        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1190            Prop::TransitionShader(s.map(Into::into))
1191        })
1192    }
1193
1194    /// What the status bar shows while the screen is up (iOS and Android;
1195    /// TS: `statusBar`): over the screens below it and the app's default,
1196    /// field by field, as a view controller's `preferredStatusBarStyle`.
1197    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1198        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1199    }
1200
1201    /// An element at the header's start (instead of the back button).
1202    pub fn header_left(self, item: impl IntoElement) -> Self {
1203        self.header_item(HeaderSlot::Left, "header-left", item)
1204    }
1205
1206    /// An element at the header's end.
1207    pub fn header_right(self, item: impl IntoElement) -> Self {
1208        self.header_item(HeaderSlot::Right, "header-right", item)
1209    }
1210
1211    /// An element replacing the title.
1212    pub fn header_title(self, item: impl IntoElement) -> Self {
1213        self.header_item(HeaderSlot::Title, "header-title", item)
1214    }
1215
1216    /// The app's header on platforms without a system header (desktops,
1217    /// the web): placed at the top of the screen, as wide as it and as tall
1218    /// as it lays out, with the content below it (TS: `header`).
1219    pub fn header(self, item: impl IntoElement) -> Self {
1220        self.header_item(HeaderSlot::Header, "header", item)
1221    }
1222
1223    /// The user popped the screen natively (back button, swipe): leave it
1224    /// out of the view (its region).
1225    pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
1226        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1227    }
1228
1229    /// The user pressed back on the screen (every back press, whether or
1230    /// not [`Self::pop_on_back`] let it pop).
1231    pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1232        self.listen(
1233            EventKind::BackRequest,
1234            listener.into_listener(),
1235            events::unit,
1236        )
1237    }
1238}
1239
1240impl Overlay {
1241    /// Places it against the element carrying `anchor` (rendered before
1242    /// it), following it as it moves: on the [`Self::placement`] side, on
1243    /// the other when only that one has room, kept inside the safe area.
1244    pub fn anchor(self, anchor: &super::ElementRef) -> Self {
1245        let anchor = *anchor;
1246        self.bind_prop(
1247            move || match anchor.node() {
1248                Some(id) => OverlayAnchor::Node(id),
1249                None => OverlayAnchor::None,
1250            },
1251            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1252        )
1253    }
1254
1255    /// Lays the element carrying `cover`, inside it, over its anchor (a
1256    /// select's selected item over the trigger) instead of placing it on
1257    /// a side ([`crate::overlay::OverlayConfig::cover`]). A ref is not
1258    /// tracked: `shown` (tracked) says when that element is rendered, as
1259    /// its `on_layout` can tell.
1260    pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
1261        let cover = *cover;
1262        self.bind_prop(
1263            move || if shown() { cover.node() } else { None },
1264            |id| Prop::Overlay(OverlayProp::Cover(id)),
1265        )
1266    }
1267
1268    /// Places it beside the element carrying `anchor`, outside the edges
1269    /// of the one carrying `edges` (the menu around it), as a submenu
1270    /// beside its row ([`OverlayAnchor::Beside`]).
1271    pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
1272        let (anchor, edges) = (*anchor, *edges);
1273        self.bind_prop(
1274            move || match (anchor.node(), edges.node()) {
1275                (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
1276                (Some(id), None) => OverlayAnchor::Node(id),
1277                _ => OverlayAnchor::None,
1278            },
1279            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1280        )
1281    }
1282
1283    /// Places it against what the element carrying `anchor` draws: the box
1284    /// around its children, so a trigger in a wrapper its parent stretches
1285    /// is placed against what shows ([`OverlayAnchor::Content`]). A ref a
1286    /// component gives its slot goes by the app's element's own box,
1287    /// whether a TSX or a Rust app filled the slot.
1288    pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
1289        let anchor = *anchor;
1290        self.bind_prop(
1291            move || match anchor.node() {
1292                Some(id) => OverlayAnchor::Content(id),
1293                None => OverlayAnchor::None,
1294            },
1295            |a| Prop::Overlay(OverlayProp::Anchor(a)),
1296        )
1297    }
1298
1299    /// Places it against a point of the root view (a touch's `page`: a
1300    /// menu where the pointer is).
1301    pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
1302        self.bind_prop(point, |p| {
1303            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
1304        })
1305    }
1306
1307    /// Places it against a box of the root view: an input's caret
1308    /// ([`CaretEvent::page_bounds`]), where suggestions for what is being
1309    /// typed open.
1310    pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
1311        self.bind_prop(bounds, |b| {
1312            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
1313        })
1314    }
1315
1316    /// Places it against `anchor`, which may change from one kind to
1317    /// another while it is shown: a context menu opened below its trigger
1318    /// and then, by a secondary click, at the pointer.
1319    pub fn anchor_to(self, anchor: impl IntoReactive<OverlayAnchor>) -> Self {
1320        self.bind_prop(anchor, |a| Prop::Overlay(OverlayProp::Anchor(a)))
1321    }
1322
1323    /// The side of the anchor it goes on (default below).
1324    pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
1325        self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
1326    }
1327
1328    /// How it lines up with the anchor along that side (default centered).
1329    pub fn align(self, align: impl IntoReactive<Align>) -> Self {
1330        self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
1331    }
1332
1333    /// The gap between the anchor and it.
1334    pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
1335        self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
1336    }
1337
1338    /// The distance it keeps from the edges of the safe area.
1339    pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
1340        self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
1341    }
1342
1343    /// A press went down outside it, its anchor and the overlays inside it
1344    /// (where, in the root view). Closing is the listener's: leave it out
1345    /// of the view.
1346    pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
1347        self.listen(
1348            EventKind::PressOutside,
1349            listener.into_listener(),
1350            events::page_point,
1351        )
1352    }
1353
1354    /// Escape or the Android back button, while it is the top overlay
1355    /// listening (it takes them from those below, the pages and
1356    /// [`super::on_back_press`]).
1357    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1358        self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
1359    }
1360
1361    /// Makes it a hint (a tooltip): shown once the pointer rested on its
1362    /// anchor (its parent without one) for `delay`, until the pointer
1363    /// leaves or presses the anchor, on the desktops only, and while the
1364    /// keyboard focus is on the anchor (or in it, outside an overlay), in
1365    /// every idiom, until the focus leaves; Escape hides it. It is placed
1366    /// against the anchor and should not take the pointer
1367    /// ([`Interactive::pointer_events`] none). [`Self::hint_open`] decides
1368    /// instead of the pointer.
1369    pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
1370        self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
1371    }
1372
1373    /// A hint shown (`Some(true)`) or hidden (`Some(false)`) whatever the
1374    /// pointer does: its owner follows [`Self::on_hint_show`] /
1375    /// [`Self::on_hint_hide`] (a `Tooltip` controlled by the app). `None`:
1376    /// the pointer decides.
1377    pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
1378        self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
1379    }
1380
1381    /// The pointer rested on a hint's anchor for its delay, or the
1382    /// keyboard focus came to it: it asks to show (and shows, unless
1383    /// [`Self::hint_open`] decides), with why.
1384    pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1385        self.listen(
1386            EventKind::Show,
1387            listener.into_listener(),
1388            events::hint_reason,
1389        )
1390    }
1391
1392    /// The pointer left or pressed a hint's anchor, the focus left it,
1393    /// Escape was pressed or the hint left the view, after it asked to
1394    /// show: it asks to hide, with why.
1395    pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
1396        self.listen(
1397            EventKind::Dismiss,
1398            listener.into_listener(),
1399            events::hint_reason,
1400        )
1401    }
1402
1403    /// The core placed it against its anchor: the side it went on, its
1404    /// frame and the room on that side.
1405    pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
1406        self.listen(
1407            EventKind::Position,
1408            listener.into_listener(),
1409            events::overlay_position,
1410        )
1411    }
1412}
1413
1414impl Modal {
1415    /// How it comes in (default: slides up).
1416    pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
1417        self.bind_prop(animation, |animation: ModalAnimation| {
1418            Prop::Modal(ModalProp::Animation(animation))
1419        })
1420    }
1421
1422    /// The program it comes and goes through instead of its
1423    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
1424    /// go back to it) leaves the change to the animation.
1425    pub fn transition_shader(
1426        self,
1427        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
1428    ) -> Self {
1429        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
1430            Prop::TransitionShader(s.map(Into::into))
1431        })
1432    }
1433
1434    /// Full screen, or a sheet (iOS).
1435    pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
1436        self.bind_prop(presentation, |presentation: ModalPresentation| {
1437            Prop::Modal(ModalProp::Presentation(presentation))
1438        })
1439    }
1440
1441    /// What the status bar shows while it is presented (iOS and Android;
1442    /// TS: `statusBar`): over what is below it, field by field.
1443    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
1444        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
1445    }
1446
1447    /// Under the status bar (Android).
1448    pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
1449        self.bind_prop(translucent, |translucent: bool| {
1450            Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
1451        })
1452    }
1453
1454    /// The orientations it allows while it is presented (iOS; default:
1455    /// those of what presents it).
1456    pub fn supported_orientations(
1457        self,
1458        orientations: impl IntoIterator<Item = Orientation>,
1459    ) -> Self {
1460        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
1461        self.set(Prop::Modal(ModalProp::Orientations(bits)))
1462    }
1463
1464    /// Escape and the Android back button close it natively (default
1465    /// true); either way they report [`Self::on_cancel`].
1466    pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
1467        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
1468    }
1469
1470    /// A press on a backdrop the platform presents itself (a native
1471    /// sheet's) closes it (default true); a backdrop the app renders is
1472    /// the app's to handle.
1473    pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
1474        self.bind_prop(close, |v: bool| {
1475            Prop::Modal(ModalProp::CloseOnBackdropPress(v))
1476        })
1477    }
1478
1479    /// Swiping a sheet down closes it natively (default true).
1480    pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
1481        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
1482    }
1483
1484    /// The heights an iOS sheet ([`ModalPresentation::PageSheet`] /
1485    /// [`ModalPresentation::FormSheet`]) rests at (none by default: the
1486    /// system's full height): the user drags it between them, the system
1487    /// way, and past the smallest it closes when [`Self::close_on_swipe`]
1488    /// allows. Ignored on other platforms and presentations, where
1489    /// `nsh_base::sheet` rests at detents.
1490    pub fn detents(self, detents: impl IntoReactive<Vec<SheetDetent>>) -> Self {
1491        self.bind_prop(detents, |v: Vec<SheetDetent>| {
1492            Prop::Modal(ModalProp::Detents(v))
1493        })
1494    }
1495
1496    /// The detent of [`Self::detents`] the sheet rests at: it moves there
1497    /// when the value changes. The user's moves stand even when the app
1498    /// does not follow them; follow [`Self::on_detent_change`] to keep the
1499    /// value in step.
1500    pub fn detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1501        self.bind_prop(detent, |v: Option<SheetDetent>| {
1502            Prop::Modal(ModalProp::Detent(v))
1503        })
1504    }
1505
1506    /// The detent it opens at without [`Self::detent`] (default the
1507    /// smallest).
1508    pub fn default_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1509        self.bind_prop(detent, |v: Option<SheetDetent>| {
1510            Prop::Modal(ModalProp::DefaultDetent(v))
1511        })
1512    }
1513
1514    /// The sheet shows the system's grabber at its top (default false).
1515    pub fn grabber(self, grabber: impl IntoReactive<bool>) -> Self {
1516        self.bind_prop(grabber, |v: bool| Prop::Modal(ModalProp::Grabber(v)))
1517    }
1518
1519    /// Up to this detent of [`Self::detents`], what is behind the sheet is
1520    /// not dimmed and takes touches (default: dimmed at every detent).
1521    pub fn largest_undimmed_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
1522        self.bind_prop(detent, |v: Option<SheetDetent>| {
1523            Prop::Modal(ModalProp::LargestUndimmedDetent(v))
1524        })
1525    }
1526
1527    /// The user moved the sheet to another of its [`Self::detents`]
1528    /// (dragging it, its grabber, a scroll at its edge, a screen reader).
1529    pub fn on_detent_change<M>(self, listener: impl IntoListener<SheetDetent, M>) -> Self {
1530        self.listen(
1531            EventKind::DetentChange,
1532            listener.into_listener(),
1533            events::sheet_detent,
1534        )
1535    }
1536
1537    /// The user tried to close it (Escape or back, a backdrop press, a
1538    /// swipe down), whether or not it closed: leave it out of the view
1539    /// (its region) to close it.
1540    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
1541        self.listen(
1542            EventKind::RequestClose,
1543            listener.into_listener(),
1544            events::unit,
1545        )
1546    }
1547
1548    /// It finished appearing.
1549    pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
1550        self.listen(EventKind::Show, listener.into_listener(), events::unit)
1551    }
1552
1553    /// The user or the system closed it.
1554    pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
1555        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
1556    }
1557}
1558
1559/// An orientation of the screen ([`Modal::supported_orientations`]).
1560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1561pub enum Orientation {
1562    /// Upright.
1563    Portrait,
1564    /// Upside down.
1565    PortraitUpsideDown,
1566    /// Either landscape.
1567    Landscape,
1568    /// Landscape with the device turned clockwise from upright, its home
1569    /// side on the left: UIKit's `landscapeLeft`, Android's reverse
1570    /// landscape.
1571    LandscapeLeft,
1572    /// Landscape with the device turned counterclockwise from upright, its
1573    /// home side on the right: UIKit's `landscapeRight`, Android's
1574    /// landscape.
1575    LandscapeRight,
1576}
1577
1578impl Orientation {
1579    fn bits(self) -> u8 {
1580        use crate::ModalConfig as M;
1581        match self {
1582            Orientation::Portrait => M::PORTRAIT,
1583            Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1584            Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1585            Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1586            Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1587        }
1588    }
1589}
1590
1591impl WebView {
1592    /// Loads `html` (relative links against `base_url`) instead of a URL;
1593    /// a bound page loads again when it changes.
1594    pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1595        let base_url: Option<Arc<str>> = base_url.map(Into::into);
1596        self.bind_prop(html, move |html: String| {
1597            Prop::Native(NativeProp::Source(WebSource::Html {
1598                html: html.into(),
1599                base_url: base_url.clone(),
1600            }))
1601        })
1602    }
1603
1604    /// Runs after each page loads.
1605    pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1606        self.bind_prop(script, |script: String| {
1607            Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1608        })
1609    }
1610
1611    /// One more origin the web view may show and navigate to besides
1612    /// `webview.hosts`, known only while the app runs
1613    /// (`scheme://host[:port]`, matched exactly): needs
1614    /// `"runtimeOrigin": true` in `capabilities.webview`
1615    /// ([`crate::access::WebOrigin`]). Set with the source, it applies to
1616    /// it; changed later, from the next navigation.
1617    pub fn allow_origin(self, origin: impl IntoReactive<String>) -> Self {
1618        self.bind_prop(origin, |origin: String| {
1619            Prop::Native(NativeProp::AllowOrigin(Some(origin.into())))
1620        })
1621    }
1622
1623    /// Runs before each page's own scripts.
1624    pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1625        self.bind_prop(script, |script: String| {
1626            Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1627        })
1628    }
1629
1630    /// The user agent it sends.
1631    pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1632        self.bind_prop(agent, |agent: String| {
1633            Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1634        })
1635    }
1636
1637    /// Scrolls (default yes).
1638    pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1639        self.bind_prop(enabled, |enabled: bool| {
1640            Prop::Native(NativeProp::Scrollable(enabled))
1641        })
1642    }
1643
1644    /// Runs the pages' JavaScript (default yes).
1645    pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1646        self.bind_prop(enabled, |enabled: bool| {
1647            Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1648        })
1649    }
1650
1651    /// Swipes go back and forward (iOS).
1652    pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1653        self.bind_prop(enabled, |enabled: bool| {
1654            Prop::Native(NativeProp::BackForwardGestures(enabled))
1655        })
1656    }
1657
1658    /// Keeps the page's website data (cookies, storage, the cache) only
1659    /// as long as the web view, apart from the app's other web views
1660    /// (default no; Android: no HTTP cache and no saved form data). Read
1661    /// when the web view is made, so it takes a value, not a signal.
1662    pub fn incognito(self, incognito: bool) -> Self {
1663        self.set(Prop::Native(NativeProp::Incognito(incognito)))
1664    }
1665
1666    /// Lets the person pinch to zoom the page, also past its viewport's
1667    /// scale limits (default no: each platform's own behavior, see the
1668    /// `zoomable` prop). Read when the web view is made, as
1669    /// [`incognito`](Self::incognito).
1670    pub fn zoomable(self, zoomable: bool) -> Self {
1671        self.set(Prop::Native(NativeProp::Zoomable(zoomable)))
1672    }
1673
1674    /// Serves the page the URLs of `scheme` (`"app-image"` for
1675    /// `<img src="app-image:1">`) from the app: `handler` answers each
1676    /// request with bytes and a MIME type
1677    /// ([`WebResourceRequest::respond`](crate::web_resource::WebResourceRequest::respond)),
1678    /// now or later and from any thread, and the web engine loads them as
1679    /// it loads any subresource, with no `data:` URL or script in between
1680    /// (iOS and macOS, Linux). The platform calls `handler` on its main
1681    /// thread, so it returns at once and leaves slow work to a thread of
1682    /// its own. Several schemes are several calls; one called again
1683    /// replaces its handler. `scheme` is a letter followed by letters,
1684    /// digits, `+`, `-` or `.`, none of the web's or the system's (`http`,
1685    /// `file`, `data`, ...): another is ignored with a warning. Read when
1686    /// the web view is made, as [`incognito`](Self::incognito)
1687    /// ([`crate::web_resource`]).
1688    pub fn url_scheme(
1689        self,
1690        scheme: &str,
1691        handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
1692    ) -> Self {
1693        let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
1694            Ok(scheme) => scheme,
1695            Err(e) => {
1696                log::warn!(target: "js", "web view: {e}");
1697                return self;
1698            }
1699        };
1700        let mut schemes = self
1701            .0
1702            .attrs
1703            .props
1704            .iter()
1705            .find_map(|p| match p {
1706                Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
1707                _ => None,
1708            })
1709            .unwrap_or_default();
1710        schemes.retain(|s| s.scheme() != scheme.scheme());
1711        schemes.push(scheme);
1712        self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
1713    }
1714
1715    /// A page started loading.
1716    pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1717        self.listen(
1718            EventKind::LoadStart,
1719            listener.into_listener(),
1720            events::navigation,
1721        )
1722    }
1723
1724    /// A page loaded.
1725    pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1726        self.listen(
1727            EventKind::Load,
1728            listener.into_listener(),
1729            events::navigation,
1730        )
1731    }
1732
1733    /// A page failed to load (the message).
1734    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1735        self.listen(EventKind::Error, listener.into_listener(), events::message)
1736    }
1737
1738    /// The platform shows no web view here: it has no web engine, or its
1739    /// engine failed to start (the message; TS: `onError` with `code`
1740    /// `"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"`). [`on_error`](Self::on_error)
1741    /// hears it too. [`web_view_available`](crate::element::web_view_available)
1742    /// asks ahead.
1743    pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
1744        self.listen(
1745            EventKind::Error,
1746            listener.into_listener(),
1747            events::unavailable,
1748        )
1749    }
1750
1751    /// The page's web content process ended: it crashed, or the system
1752    /// reclaimed its memory (the message; TS: `onError` with `code`
1753    /// `"ERR_NSH_WEBVIEW_TERMINATED"`). The app keeps running and the web
1754    /// view shows no page until [`reload`](crate::element::ElementRef::reload),
1755    /// [`load`](crate::element::ElementRef::load) or a new source. [`on_error`](Self::on_error) hears it too.
1756    pub fn on_process_terminated<M>(self, listener: impl IntoListener<str, M>) -> Self {
1757        self.listen(
1758            EventKind::Error,
1759            listener.into_listener(),
1760            events::terminated,
1761        )
1762    }
1763
1764    /// The page called `window.nsh.postMessage(data)`.
1765    pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1766        self.listen(EventKind::Message, listener.into_listener(), events::data)
1767    }
1768
1769    /// It navigated.
1770    pub fn on_navigation_state_change<M>(
1771        self,
1772        listener: impl IntoListener<WebNavigation, M>,
1773    ) -> Self {
1774        self.listen(
1775            EventKind::NavigationStateChange,
1776            listener.into_listener(),
1777            events::navigation,
1778        )
1779    }
1780
1781    /// A download started, finished, failed or was cancelled (the core's
1782    /// `onDownload` lifecycle). Registering it makes automatic
1783    /// downloads write into the app's data directory
1784    /// (`downloads/<id>/<filename>`), unless
1785    /// [`on_download_pending`](Self::on_download_pending) is also
1786    /// registered, which makes every destination the app's.
1787    pub fn on_download<M>(
1788        self,
1789        listener: impl IntoListener<crate::webview::WebDownload, M>,
1790    ) -> Self {
1791        self.listen(
1792            EventKind::Download,
1793            listener.into_listener(),
1794            events::web_download,
1795        )
1796        .set(Prop::Native(NativeProp::DeferDownloads(true)))
1797    }
1798
1799    /// The page asked to download a file and waits for the app's
1800    /// destination. Registering this listener is what asks for that: the
1801    /// platform holds the transfer and writes nothing until the app answers
1802    /// ([`accept`](crate::webview::WebDownloadPending::accept) or
1803    /// [`cancel`](crate::webview::WebDownloadPending::cancel)), and a
1804    /// download the app never answers is cancelled after a bounded wait.
1805    /// Without this listener the platform keeps its automatic behavior.
1806    pub fn on_download_pending<M>(
1807        self,
1808        listener: impl IntoListener<crate::webview::WebDownloadPending, M>,
1809    ) -> Self {
1810        self.listen(
1811            EventKind::DownloadPending,
1812            listener.into_listener(),
1813            events::web_download_pending,
1814        )
1815        .set(Prop::Native(NativeProp::DeferDownloads(true)))
1816    }
1817}
1818
1819impl Video {
1820    /// Paused.
1821    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1822        self.bind_prop(paused, |paused: bool| {
1823            Prop::Native(NativeProp::Paused(paused))
1824        })
1825    }
1826
1827    /// Without sound.
1828    pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1829        self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1830    }
1831
1832    /// 0..1.
1833    pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1834        self.bind_prop(volume, |volume: f32| {
1835            Prop::Native(NativeProp::Volume(volume))
1836        })
1837    }
1838
1839    /// Playback speed.
1840    pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1841        self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1842    }
1843
1844    /// Starts over at the end.
1845    pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1846        self.bind_prop(repeat, |repeat: bool| {
1847            Prop::Native(NativeProp::Repeat(repeat))
1848        })
1849    }
1850
1851    /// The platform's playback controls.
1852    pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1853        self.bind_prop(controls, |controls: bool| {
1854            Prop::Native(NativeProp::Controls(controls))
1855        })
1856    }
1857
1858    /// Milliseconds between [`Self::on_progress`] events (default 250).
1859    pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1860        self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1861    }
1862
1863    /// What its sound does to the rest of the device's audio while it
1864    /// plays (default: the app's audio settings).
1865    pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1866        self.bind_prop(session, |session: AudioSession| {
1867            Prop::Native(NativeProp::AudioSession(session))
1868        })
1869    }
1870
1871    /// It started loading.
1872    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1873        self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1874    }
1875
1876    /// It loaded: length and size.
1877    pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1878        self.listen(EventKind::Load, listener.into_listener(), events::video)
1879    }
1880
1881    /// It played on.
1882    pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1883        self.listen(
1884            EventKind::Progress,
1885            listener.into_listener(),
1886            events::progress,
1887        )
1888    }
1889
1890    /// It played to its end.
1891    pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1892        self.listen(EventKind::End, listener.into_listener(), events::unit)
1893    }
1894
1895    /// It started (`true`) or stopped buffering.
1896    pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1897        self.listen(
1898            EventKind::Buffer,
1899            listener.into_listener(),
1900            events::buffering,
1901        )
1902    }
1903
1904    /// It failed (the message).
1905    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1906        self.listen(EventKind::Error, listener.into_listener(), events::message)
1907    }
1908}
1909
1910impl NativeView {
1911    /// Its prop `name` (any JSON value), as JS's `nativeComponent` passes it;
1912    /// a bound one is passed again when it changes.
1913    pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1914        let name: Arc<str> = name.into();
1915        self.bind_prop(value, move |value| {
1916            Prop::ComponentProp(name.clone(), Some(value))
1917        })
1918    }
1919
1920    /// Binds its prop `name` to an animated value: the platform hands the
1921    /// value (a number or a color) to the component on every frame it
1922    /// changes, with no engine work per frame (JS: an animated value given
1923    /// to a `nativeComponent` prop). A value set with [`Self::prop`] under
1924    /// that name waits until the binding goes.
1925    pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1926        if let Some(node) = value.animated_node().live() {
1927            set(
1928                &mut self.0,
1929                Prop::ComponentPropBinding(name.into(), Some(node.id())),
1930            );
1931            self.0.attrs.rare_mut().bound.push(node);
1932        }
1933        self
1934    }
1935
1936    /// It emitted an event.
1937    pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1938        self.listen(
1939            EventKind::NativeEvent,
1940            listener.into_listener(),
1941            events::native,
1942        )
1943    }
1944}
1945
1946/// A number in a drawing: a constant, or an animated value the canvas reads
1947/// while it draws (it draws again natively as the value moves).
1948#[derive(Debug, Clone, PartialEq)]
1949pub struct CanvasArg(pub(crate) CanvasArgKind);
1950
1951#[derive(Debug, Clone, PartialEq)]
1952pub(crate) enum CanvasArgKind {
1953    Const(f32),
1954    Node(super::LiveNode),
1955}
1956
1957impl From<f32> for CanvasArg {
1958    fn from(n: f32) -> Self {
1959        Self(CanvasArgKind::Const(n))
1960    }
1961}
1962
1963/// A length (coordinates, sizes, line widths, radii).
1964impl From<Points> for CanvasArg {
1965    fn from(n: Points) -> Self {
1966        Self(CanvasArgKind::Const(n.0))
1967    }
1968}
1969
1970/// An angle (arcs, rotations).
1971impl From<Radians> for CanvasArg {
1972    fn from(n: Radians) -> Self {
1973        Self(CanvasArgKind::Const(n.0))
1974    }
1975}
1976
1977/// An animated value whose owner is gone counts as 0.
1978impl<A: super::Animated> From<&A> for CanvasArg {
1979    fn from(a: &A) -> Self {
1980        Self(match a.animated_node().live() {
1981            Some(node) => CanvasArgKind::Node(node),
1982            None => CanvasArgKind::Const(0.0),
1983        })
1984    }
1985}
1986
1987/// What a drawing fills or strokes with (`fillStyle` / `strokeStyle`): a
1988/// color, a gradient ([`CanvasGradient::linear`], `radial`, `conic`), or a
1989/// animated value interpolating colors
1990/// ([`super::AnimatedNode::interpolate_colors`]), read as it moves.
1991#[derive(Debug, Clone, PartialEq)]
1992pub struct CanvasPaint(CanvasPaintKind);
1993
1994#[derive(Debug, Clone, PartialEq)]
1995enum CanvasPaintKind {
1996    Color(Color),
1997    Gradient(Arc<CanvasGradient>),
1998    Node(super::LiveNode),
1999}
2000
2001impl From<Color> for CanvasPaint {
2002    fn from(color: Color) -> Self {
2003        Self(CanvasPaintKind::Color(color))
2004    }
2005}
2006
2007impl From<Hsla> for CanvasPaint {
2008    fn from(color: Hsla) -> Self {
2009        Color::from(color).into()
2010    }
2011}
2012
2013impl From<Rgba> for CanvasPaint {
2014    fn from(color: Rgba) -> Self {
2015        Color::from(color).into()
2016    }
2017}
2018
2019impl From<CanvasGradient> for CanvasPaint {
2020    fn from(gradient: CanvasGradient) -> Self {
2021        Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
2022    }
2023}
2024
2025impl From<Arc<CanvasGradient>> for CanvasPaint {
2026    fn from(gradient: Arc<CanvasGradient>) -> Self {
2027        Self(CanvasPaintKind::Gradient(gradient))
2028    }
2029}
2030
2031/// An animated value whose owner is gone paints nothing (transparent).
2032impl<A: super::Animated> From<&A> for CanvasPaint {
2033    fn from(a: &A) -> Self {
2034        Self(match a.animated_node().live() {
2035            Some(node) => CanvasPaintKind::Node(node),
2036            None => CanvasPaintKind::Color(Color::TRANSPARENT),
2037        })
2038    }
2039}
2040
2041/// Records a [`Drawing`] with the HTML Canvas 2D operations (Rust names):
2042/// `Painter::new().fill_color(red).fill_rect(px(0.0), px(0.0), w, h).finish()`.
2043/// Coordinates are points from the canvas's top left. Numbers and paints
2044/// may be animated values (the canvas draws again natively as they move);
2045/// operations without a method here are built by hand with
2046/// [`Painter::num`], [`Painter::paint`] and [`Painter::op`]. Text is
2047/// measured with [`super::measure_text`].
2048#[derive(Debug, Clone, Default)]
2049pub struct Painter {
2050    drawing: Drawing,
2051    /// The nodes of the animated values the drawing reads, held with it.
2052    nodes: Vec<super::LiveNode>,
2053}
2054
2055impl Painter {
2056    /// An empty drawing.
2057    pub fn new() -> Self {
2058        Self::default()
2059    }
2060
2061    /// The drawing.
2062    pub fn finish(self) -> Drawing {
2063        self.drawing
2064    }
2065
2066    /// Renders the drawing offscreen into an image of `size` points, as a
2067    /// canvas of that size draws it on screen (TS: `OffscreenCanvas`'s
2068    /// `convertToBlob`), with `options`' scale (default: the screen's) and
2069    /// format (default: PNG). To await in a task: the encoded bytes, or why
2070    /// not: `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` where the platform renders
2071    /// none (`nsh test`'s headless runs among them), a `RangeError` for a
2072    /// size or scale that is not a positive number, `ERR_NSH_QUOTA_EXCEEDED`
2073    /// for an image over 16384 pixels a side or 64 megapixels or past 16
2074    /// renders at once, `ETIMEDOUT` when the platform has not answered in
2075    /// 30 seconds.
2076    pub fn render(
2077        self,
2078        size: Size<Points>,
2079        options: crate::canvas::render::RenderOptions,
2080    ) -> crate::element::Answer<Result<Vec<u8>, crate::element::JsError>> {
2081        crate::element::ambient::render_canvas(crate::canvas::render::RenderRequest {
2082            drawing: self.drawing,
2083            size,
2084            scale: options.scale,
2085            format: options.format,
2086        })
2087    }
2088
2089    /// `value` as a number of this drawing, for an operation built by hand
2090    /// ([`Self::op`]): an animated value becomes a slot the canvas reads while
2091    /// it draws, kept alive with the drawing.
2092    pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
2093        match value.into().0 {
2094            CanvasArgKind::Const(n) => Num::Const(n),
2095            CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
2096        }
2097    }
2098
2099    /// `paint` as a paint of this drawing, for an operation built by hand
2100    /// ([`Self::op`]).
2101    pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
2102        match paint.into().0 {
2103            CanvasPaintKind::Color(color) => Paint::Color(color),
2104            CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
2105            CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
2106        }
2107    }
2108
2109    fn slot(&mut self, node: super::LiveNode) -> u16 {
2110        let slot = self.drawing.slot(node.id());
2111        self.nodes.push(node);
2112        slot
2113    }
2114
2115    /// Adds `node`: a part of the drawing that assistive technologies and
2116    /// UI tests see as an element of its own ([`crate::canvas::CanvasNode`]).
2117    pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
2118        self.drawing.nodes.push(node);
2119        self
2120    }
2121
2122    /// Records `op` (one built by hand: its numbers and paints from
2123    /// [`Self::num`] and [`Self::paint`]).
2124    pub fn op(mut self, op: CanvasOp) -> Self {
2125        self.drawing.ops.push(op);
2126        self
2127    }
2128
2129    fn path(self, op: PathOp) -> Self {
2130        self.op(CanvasOp::Path(op))
2131    }
2132
2133    /// Whether `point` (in the canvas, as a touch's location) is inside the
2134    /// current path by `rule`, with the transform, as recorded so far (TS:
2135    /// `cx.isPointInPath(x, y, rule)`). Answered from the geometry here,
2136    /// with no platform round trip; a number given as an animated value
2137    /// counts as 0, as in TS. To find what is under a tap, build the
2138    /// canvas's painter in a function the press handler calls too.
2139    pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
2140        crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
2141    }
2142
2143    /// Whether `point` is on the stroke of the current path with the line
2144    /// width and cap recorded so far (TS: `cx.isPointInStroke(x, y)`;
2145    /// round joins, no dashes). See [`Self::is_point_in_path`].
2146    pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
2147        crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
2148    }
2149
2150    /// Whether `point` is inside `path` by `rule`, with the transform
2151    /// recorded so far (TS: `cx.isPointInPath(path2d, x, y, rule)`): the
2152    /// shape [`Self::fill_path`] drew under a tap. See
2153    /// [`Self::is_point_in_path`].
2154    pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
2155        crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
2156    }
2157
2158    /// Whether `point` is on the stroke of `path` with the transform, line
2159    /// width and cap recorded so far (TS: `cx.isPointInStroke(path2d, x,
2160    /// y)`). See [`Self::is_point_in_path`].
2161    pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
2162        crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
2163    }
2164
2165    /// Saves the state (styles, transform, clip).
2166    pub fn save(self) -> Self {
2167        self.op(CanvasOp::Save)
2168    }
2169
2170    /// Restores the state saved last.
2171    pub fn restore(self) -> Self {
2172        self.op(CanvasOp::Restore)
2173    }
2174
2175    /// Moves the origin.
2176    pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2177        let (x, y) = (self.num(x), self.num(y));
2178        self.op(CanvasOp::Translate(x, y))
2179    }
2180
2181    /// Scales the axes.
2182    pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2183        let (x, y) = (self.num(x), self.num(y));
2184        self.op(CanvasOp::Scale(x, y))
2185    }
2186
2187    /// Rotates the axes, clockwise (a [`Radians`], or an animated value of
2188    /// radians).
2189    pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
2190        let a = self.num(angle);
2191        self.op(CanvasOp::Rotate(a))
2192    }
2193
2194    /// Multiplies the transform by the matrix `[a c e; b d f]`
2195    /// (`transform`).
2196    pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2197        let m = m.map(|n| self.num(n));
2198        self.op(CanvasOp::Transform(m))
2199    }
2200
2201    /// Replaces the transform with the matrix `[a c e; b d f]`
2202    /// (`setTransform`).
2203    pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
2204        let m = m.map(|n| self.num(n));
2205        self.op(CanvasOp::SetTransform(m))
2206    }
2207
2208    /// Back to no transform (`resetTransform`).
2209    pub fn reset_transform(self) -> Self {
2210        self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
2211    }
2212
2213    /// Starts a new path.
2214    pub fn begin_path(self) -> Self {
2215        self.op(CanvasOp::BeginPath)
2216    }
2217
2218    /// Starts a subpath at (`x`, `y`).
2219    pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2220        let (x, y) = (self.num(x), self.num(y));
2221        self.path(PathOp::MoveTo(x, y))
2222    }
2223
2224    /// A straight line to (`x`, `y`).
2225    pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2226        let (x, y) = (self.num(x), self.num(y));
2227        self.path(PathOp::LineTo(x, y))
2228    }
2229
2230    /// A quadratic Bézier curve to `to` (`quadraticCurveTo`).
2231    pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
2232        let c = |v: Points| Num::Const(v.0);
2233        self.path(PathOp::QuadTo([
2234            c(control.x),
2235            c(control.y),
2236            c(to.x),
2237            c(to.y),
2238        ]))
2239    }
2240
2241    /// A cubic Bézier curve to `to` (`bezierCurveTo`).
2242    pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
2243        let c = |v: Points| Num::Const(v.0);
2244        self.path(PathOp::CubicTo([
2245            c(c1.x),
2246            c(c1.y),
2247            c(c2.x),
2248            c(c2.y),
2249            c(to.x),
2250            c(to.y),
2251        ]))
2252    }
2253
2254    /// A circular arc around (`x`, `y`); angles clockwise from the x axis
2255    /// ([`Radians`], or animated values of radians).
2256    pub fn arc(
2257        self,
2258        x: impl Into<CanvasArg>,
2259        y: impl Into<CanvasArg>,
2260        radius: impl Into<CanvasArg>,
2261        start: impl Into<CanvasArg>,
2262        end: impl Into<CanvasArg>,
2263    ) -> Self {
2264        self.arc_in(x, y, radius, start, end, false)
2265    }
2266
2267    /// [`Self::arc`] drawn counterclockwise.
2268    pub fn arc_counterclockwise(
2269        self,
2270        x: impl Into<CanvasArg>,
2271        y: impl Into<CanvasArg>,
2272        radius: impl Into<CanvasArg>,
2273        start: impl Into<CanvasArg>,
2274        end: impl Into<CanvasArg>,
2275    ) -> Self {
2276        self.arc_in(x, y, radius, start, end, true)
2277    }
2278
2279    fn arc_in(
2280        mut self,
2281        x: impl Into<CanvasArg>,
2282        y: impl Into<CanvasArg>,
2283        radius: impl Into<CanvasArg>,
2284        start: impl Into<CanvasArg>,
2285        end: impl Into<CanvasArg>,
2286        ccw: bool,
2287    ) -> Self {
2288        let (x, y, radius, start, end) = (
2289            self.num(x),
2290            self.num(y),
2291            self.num(radius),
2292            self.num(start),
2293            self.num(end),
2294        );
2295        self.path(PathOp::Arc {
2296            x,
2297            y,
2298            radius,
2299            start,
2300            end,
2301            ccw,
2302        })
2303    }
2304
2305    /// An arc of `radius` tangent to the lines to `p1` and on to `p2`
2306    /// (`arcTo`): a rounded corner.
2307    pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
2308        let c = |v: Points| Num::Const(v.0);
2309        self.path(PathOp::ArcTo([
2310            c(p1.x),
2311            c(p1.y),
2312            c(p2.x),
2313            c(p2.y),
2314            c(radius),
2315        ]))
2316    }
2317
2318    /// An elliptical arc around `center` with radii `radii` turned by
2319    /// `rotation`; angles clockwise (`counterclockwise` draws the other
2320    /// way).
2321    pub fn ellipse(
2322        self,
2323        center: Point<Points>,
2324        radii: Size<Points>,
2325        rotation: Radians,
2326        start: Radians,
2327        end: Radians,
2328        counterclockwise: bool,
2329    ) -> Self {
2330        let c = Num::Const;
2331        self.path(PathOp::Ellipse {
2332            geometry: [
2333                c(center.x.0),
2334                c(center.y.0),
2335                c(radii.width.0),
2336                c(radii.height.0),
2337                c(rotation.0),
2338            ],
2339            start: c(start.0),
2340            end: c(end.0),
2341            ccw: counterclockwise,
2342        })
2343    }
2344
2345    /// A rectangle subpath.
2346    pub fn rect(self, rect: Bounds<Points>) -> Self {
2347        self.path(PathOp::Rect(nums(rect)))
2348    }
2349
2350    /// A rectangle subpath with round corners (one radius for all).
2351    pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
2352        self.round_rect_corners(rect, Corners::all(radius))
2353    }
2354
2355    /// A rectangle subpath with round corners.
2356    pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
2357        let c = |v: Points| Num::Const(v.0);
2358        self.path(PathOp::RoundRect(
2359            nums(rect),
2360            [
2361                c(radii.top_left),
2362                c(radii.top_right),
2363                c(radii.bottom_right),
2364                c(radii.bottom_left),
2365            ],
2366        ))
2367    }
2368
2369    /// A straight line back to the subpath's start.
2370    pub fn close_path(self) -> Self {
2371        self.path(PathOp::Close)
2372    }
2373
2374    /// Fills the current path.
2375    pub fn fill(self) -> Self {
2376        self.fill_with(FillRule::NonZero)
2377    }
2378
2379    /// Fills the current path by `rule`.
2380    pub fn fill_with(self, rule: FillRule) -> Self {
2381        self.op(CanvasOp::Fill(None, rule))
2382    }
2383
2384    /// Fills `path` (TS: `fill(path2d)`; parse SVG data once with
2385    /// [`crate::canvas::svg_path`]).
2386    pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
2387        self.op(CanvasOp::Fill(Some(path.clone()), rule))
2388    }
2389
2390    /// Fills SVG path data (parsed now: [`Self::fill_path`] reuses a
2391    /// parsed path).
2392    pub fn fill_svg(self, data: &str) -> Self {
2393        self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
2394    }
2395
2396    /// Strokes the current path.
2397    pub fn stroke(self) -> Self {
2398        self.op(CanvasOp::Stroke(None))
2399    }
2400
2401    /// Strokes `path` (TS: `stroke(path2d)`).
2402    pub fn stroke_path(self, path: &Path) -> Self {
2403        self.op(CanvasOp::Stroke(Some(path.clone())))
2404    }
2405
2406    /// Strokes SVG path data (parsed now).
2407    pub fn stroke_svg(self, data: &str) -> Self {
2408        self.stroke_path(&crate::canvas::svg_path(data))
2409    }
2410
2411    /// Clips to the current path.
2412    pub fn clip(self) -> Self {
2413        self.clip_with(FillRule::NonZero)
2414    }
2415
2416    /// Clips to the current path by `rule`.
2417    pub fn clip_with(self, rule: FillRule) -> Self {
2418        self.op(CanvasOp::Clip(None, rule))
2419    }
2420
2421    /// Clips to `path` (TS: `clip(path2d)`).
2422    pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
2423        self.op(CanvasOp::Clip(Some(path.clone()), rule))
2424    }
2425
2426    /// Fills a rectangle (its numbers [`Points`], or animated values).
2427    pub fn fill_rect(
2428        mut self,
2429        x: impl Into<CanvasArg>,
2430        y: impl Into<CanvasArg>,
2431        w: impl Into<CanvasArg>,
2432        h: impl Into<CanvasArg>,
2433    ) -> Self {
2434        let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
2435        self.op(CanvasOp::FillRect([x, y, w, h]))
2436    }
2437
2438    /// Strokes a rectangle.
2439    pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
2440        self.op(CanvasOp::StrokeRect(nums(rect)))
2441    }
2442
2443    /// Makes a rectangle transparent.
2444    pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
2445        self.op(CanvasOp::ClearRect(nums(rect)))
2446    }
2447
2448    /// Fills with `color`.
2449    pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
2450        self.fill_style(color.into())
2451    }
2452
2453    /// Strokes with `color`.
2454    pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
2455        self.stroke_style(color.into())
2456    }
2457
2458    /// Fills with `paint`: a color, a gradient or an animated value of colors
2459    /// (`fillStyle`).
2460    pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2461        let paint = self.paint(paint);
2462        self.op(CanvasOp::FillStyle(paint))
2463    }
2464
2465    /// Fills with the canvas view's `fill` style (CSS's, inherited from the
2466    /// views around it; `currentColor` is its text color), or `initial`
2467    /// where nothing sets one: shapes a component draws take the app's
2468    /// `fill-*` classes, and follow them and the appearance without being
2469    /// drawn again ([`Drawing::view_paints`]).
2470    pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
2471        self.view_paint(
2472            ViewPaint::Fill(initial),
2473            CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
2474        )
2475    }
2476
2477    /// Strokes with the canvas view's `stroke` style, or `initial` where
2478    /// nothing sets one ([`Self::fill_style_from_view`]).
2479    pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
2480        self.view_paint(
2481            ViewPaint::Stroke(initial),
2482            CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
2483        )
2484    }
2485
2486    /// Strokes as wide as the canvas view's `strokeWidth` style (1 where
2487    /// nothing sets one, CSS's initial value).
2488    pub fn line_width_from_view(self) -> Self {
2489        self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
2490    }
2491
2492    /// Dashes strokes as the canvas view's `strokeDasharray` style does
2493    /// (solid where nothing sets one).
2494    pub fn line_dash_from_view(self) -> Self {
2495        self.view_paint(
2496            ViewPaint::StrokeDasharray,
2497            CanvasOp::LineDash(Arc::from([])),
2498        )
2499    }
2500
2501    /// Fills the current path with the canvas view's background: its
2502    /// `backgroundColor` and its `backgroundImage` gradients (`bg-*`,
2503    /// `bg-linear-*` classes, the appearance's colors), positioned over
2504    /// `area` (this drawing's coordinates) as over a box of that size. The
2505    /// view then draws no background of its own: the background shows only
2506    /// where the path fills, as CSS's `clip-path` shows a box's
2507    /// ([`ViewPaint::Background`]). The canvas's state is kept around the
2508    /// fill.
2509    pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
2510        self.view_paint(
2511            ViewPaint::Background {
2512                area,
2513                rule: FillRule::NonZero,
2514            },
2515            CanvasOp::Fill(None, FillRule::NonZero),
2516        )
2517    }
2518
2519    fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
2520        let at = self.drawing.ops.len() as u32;
2521        self.drawing.view_paints.push((at, view));
2522        self.op(placeholder)
2523    }
2524
2525    /// Strokes with `paint` (`strokeStyle`).
2526    pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
2527        let paint = self.paint(paint);
2528        self.op(CanvasOp::StrokeStyle(paint))
2529    }
2530
2531    /// The stroke width.
2532    pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
2533        let w = self.num(width);
2534        self.op(CanvasOp::LineWidth(w))
2535    }
2536
2537    /// How strokes end.
2538    pub fn line_cap(self, cap: LineCap) -> Self {
2539        self.op(CanvasOp::LineCap(cap))
2540    }
2541
2542    /// How stroke segments join.
2543    pub fn line_join(self, join: LineJoin) -> Self {
2544        self.op(CanvasOp::LineJoin(join))
2545    }
2546
2547    /// How far mitered joins reach, in line widths (`miterLimit`; at least
2548    /// 1).
2549    pub fn miter_limit(self, limit: f32) -> Self {
2550        self.op(CanvasOp::MiterLimit(limit.max(1.0)))
2551    }
2552
2553    /// Dashes: lengths of dashes and gaps.
2554    pub fn line_dash(self, segments: &[Points]) -> Self {
2555        self.op(CanvasOp::LineDash(segments.into()))
2556    }
2557
2558    /// Where the dashes start along the line (`lineDashOffset`; an animated
2559    /// value marches them).
2560    pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
2561        let o = self.num(offset);
2562        self.op(CanvasOp::LineDashOffset(o))
2563    }
2564
2565    /// The opacity of what is drawn next.
2566    pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
2567        let a = self.num(alpha);
2568        self.op(CanvasOp::GlobalAlpha(a))
2569    }
2570
2571    /// How what is drawn next combines with the canvas.
2572    pub fn composite(self, composite: Composite) -> Self {
2573        self.op(CanvasOp::Composite(composite))
2574    }
2575
2576    /// Shadows of what is drawn next.
2577    pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
2578        self.op(CanvasOp::ShadowColor(Color::from(color.into())))
2579            .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
2580            .op(CanvasOp::ShadowOffset(offset))
2581    }
2582
2583    /// The font (CSS `font` shorthand: `"600 14px Inter"`); an invalid one
2584    /// keeps the previous font, as in HTML.
2585    pub fn font(self, font: &str) -> Self {
2586        match CanvasFont::parse(font) {
2587            Some(font) => self.op(CanvasOp::Font(font)),
2588            None => self,
2589        }
2590    }
2591
2592    /// The number forms of text (TS: `fontVariantNumeric`): with
2593    /// [`crate::style::FontVariant::TABULAR_NUMS`] figures have equal widths, so changing
2594    /// values do not jitter; `FontVariant::default()` keeps the font's.
2595    pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
2596        self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
2597            numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
2598        )))
2599    }
2600
2601    /// Where text sits relative to its x.
2602    pub fn text_align(self, align: CanvasTextAlign) -> Self {
2603        self.op(CanvasOp::TextAlign(align))
2604    }
2605
2606    /// Where text sits relative to its y.
2607    pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
2608        self.op(CanvasOp::TextBaseline(baseline))
2609    }
2610
2611    /// Fills `text` at (`x`, `y`).
2612    pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2613        self.text(text, x, y, None, false)
2614    }
2615
2616    /// Fills `text` at (`x`, `y`), narrowed to fit `max_width`.
2617    pub fn fill_text_max_width(
2618        self,
2619        text: &str,
2620        x: impl Into<CanvasArg>,
2621        y: impl Into<CanvasArg>,
2622        max_width: Points,
2623    ) -> Self {
2624        self.text(text, x, y, Some(max_width), false)
2625    }
2626
2627    /// Strokes the outline of `text` at (`x`, `y`).
2628    pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
2629        self.text(text, x, y, None, true)
2630    }
2631
2632    /// Strokes the outline of `text` at (`x`, `y`), narrowed to fit
2633    /// `max_width`.
2634    pub fn stroke_text_max_width(
2635        self,
2636        text: &str,
2637        x: impl Into<CanvasArg>,
2638        y: impl Into<CanvasArg>,
2639        max_width: Points,
2640    ) -> Self {
2641        self.text(text, x, y, Some(max_width), true)
2642    }
2643
2644    fn text(
2645        mut self,
2646        text: &str,
2647        x: impl Into<CanvasArg>,
2648        y: impl Into<CanvasArg>,
2649        max_width: Option<Points>,
2650        stroke: bool,
2651    ) -> Self {
2652        let (text, x, y) = (text.into(), self.num(x), self.num(y));
2653        self.op(if stroke {
2654            CanvasOp::StrokeText {
2655                text,
2656                x,
2657                y,
2658                max_width,
2659            }
2660        } else {
2661            CanvasOp::FillText {
2662                text,
2663                x,
2664                y,
2665                max_width,
2666            }
2667        })
2668    }
2669
2670    /// Draws the image at `uri` (a URL or `asset:/path`) into `dest`.
2671    pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
2672        self.draw_image_part(uri, None, dest)
2673    }
2674
2675    /// Draws the part `source` of the image at `uri` (in the image's
2676    /// pixels; `None`: all of it) into `dest`.
2677    pub fn draw_image_part(
2678        self,
2679        uri: &str,
2680        source: Option<Bounds<ScaledPixels>>,
2681        dest: Bounds<Points>,
2682    ) -> Self {
2683        self.op(CanvasOp::DrawImage {
2684            image: CanvasImage { uri: uri.into() },
2685            source,
2686            dest: nums(dest),
2687        })
2688    }
2689}
2690
2691/// `[x, y, w, h]` of `rect`, as a recorded rectangle's numbers.
2692fn nums(rect: Bounds<Points>) -> [Num; 4] {
2693    [
2694        rect.origin.x,
2695        rect.origin.y,
2696        rect.size.width,
2697        rect.size.height,
2698    ]
2699    .map(|v| Num::Const(v.0))
2700}
2701
2702impl From<Drawing> for Painter {
2703    fn from(drawing: Drawing) -> Self {
2704        Self {
2705            drawing,
2706            nodes: Vec::new(),
2707        }
2708    }
2709}
2710
2711crate::static_reactive!(ScreenAnimation: ScreenAnimation);
2712crate::static_reactive!(HeaderTitleAlign: HeaderTitleAlign);
2713
2714/// A program where an optional one goes (`.transition_shader(wipe)`).
2715impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
2716    fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
2717        super::Reactive::Static(Some(self))
2718    }
2719}
2720
2721/// A backdrop where an optional one goes (`.macos_backdrop(backdrop)`).
2722impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
2723    fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
2724        super::Reactive::Static(Some(self))
2725    }
2726}
2727
2728/// A backdrop where an optional one goes (`.windows_backdrop(backdrop)`).
2729impl IntoReactive<Option<crate::WindowsBackdrop>> for crate::WindowsBackdrop {
2730    fn into_reactive(self) -> super::Reactive<Option<crate::WindowsBackdrop>> {
2731        super::Reactive::Static(Some(self))
2732    }
2733}
2734
2735#[cfg(test)]
2736mod tests {
2737    use super::*;
2738    use crate::{
2739        element::{
2740            AnimatedValue,
2741            reactive::{Runtime, create_root, signal},
2742        },
2743        shader::{ShaderUniforms, UniformValue},
2744    };
2745
2746    fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
2747        attrs
2748            .props
2749            .iter()
2750            .find_map(|p| match p {
2751                Prop::Uniforms(u) => Some(u.clone()),
2752                _ => None,
2753            })
2754            .unwrap_or_default()
2755    }
2756
2757    /// The animation nodes released since the last call.
2758    fn released(executor: &super::super::task::Executor) -> usize {
2759        executor
2760            .take_actions()
2761            .into_iter()
2762            .filter(|a| {
2763                matches!(
2764                    a,
2765                    super::super::task::Action::Animation(
2766                        crate::animation::AnimationOp::Release { .. }
2767                    )
2768                )
2769            })
2770            .count()
2771    }
2772
2773    fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
2774        u.0.iter()
2775            .find(|(n, _)| &**n == name)
2776            .map(|(_, v)| v.clone())
2777    }
2778
2779    #[test]
2780    fn screens_and_modals_take_a_transition_shader() {
2781        let runtime = Runtime::default();
2782        let _entered = runtime.enter();
2783        let source = "struct Uniforms { edge: f32 }\n\
2784            fn shade(uv: vec2f) -> vec4f {\n    \
2785            return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
2786        let shader = crate::shader::Shader::compile(source).expect("compiles");
2787        let wipe = crate::shader::TransitionShader::new(shader)
2788            .uniform("edge", 1.0_f32)
2789            .duration(std::time::Duration::from_millis(400));
2790        let expected = crate::shader::NavShaderSpec {
2791            source: source.into(),
2792            uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
2793            duration: Some(400.0),
2794        };
2795        let spec = |attrs: &super::super::builder::Attrs| {
2796            attrs.props.iter().find_map(|p| match p {
2797                Prop::TransitionShader(s) => Some(s.clone()),
2798                _ => None,
2799            })
2800        };
2801        let page = screen().transition_shader(wipe.clone()).0;
2802        assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
2803        let dialog = modal().transition_shader(wipe.clone()).0;
2804        assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
2805        // A binding goes back to the page's or the dialog's own animation.
2806        let on = signal(true);
2807        let bound = screen()
2808            .transition_shader(move || on.get().then(|| wipe.clone()))
2809            .0;
2810        assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
2811        on.set(false);
2812        assert_eq!(spec(&bound.resolved_attrs()), Some(None));
2813    }
2814
2815    #[test]
2816    fn uniform_takes_static_bound_and_animated_values() {
2817        let runtime = Runtime::default();
2818        let _entered = runtime.enter();
2819        let executor = std::rc::Rc::new(super::super::task::Executor::default());
2820        let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
2821        let speed = signal(1.0_f32);
2822        let view = shader()
2823            .uniform("center", [0.5_f32, 0.5])
2824            .uniform("wave", &wave)
2825            .uniform("speed", move || speed.get());
2826        let node = view.0;
2827
2828        // The static and animated ones are set at once; the animated one by
2829        // its node, which the element holds.
2830        let set = uniforms(&node.attrs);
2831        assert_eq!(
2832            value(&set, "center"),
2833            Some(UniformValue::List(vec![
2834                UniformValue::Number(0.5),
2835                UniformValue::Number(0.5)
2836            ]))
2837        );
2838        let id = wave.node().live().expect("live").id();
2839        assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
2840        assert_eq!(
2841            node.attrs.bound().len(),
2842            1,
2843            "the element holds the animated node"
2844        );
2845        assert_eq!(
2846            value(&set, "speed"),
2847            None,
2848            "a bound one is applied when resolved"
2849        );
2850
2851        // The bound one follows its signal.
2852        assert_eq!(
2853            value(&uniforms(&node.resolved_attrs()), "speed"),
2854            Some(UniformValue::Number(1.0))
2855        );
2856        speed.set(2.0);
2857        assert_eq!(
2858            value(&uniforms(&node.resolved_attrs()), "speed"),
2859            Some(UniformValue::Number(2.0))
2860        );
2861
2862        // The node outlives the owner of the handle it came from.
2863        value_owner.dispose();
2864        assert_eq!(released(&executor), 0, "the view keeps the animated node");
2865        drop(node);
2866        assert_eq!(released(&executor), 1, "and lets it go with the view");
2867    }
2868
2869    #[test]
2870    fn a_later_uniform_replaces_one_of_the_same_name() {
2871        let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
2872        let set = uniforms(&view.0.attrs);
2873        assert_eq!(set.0.len(), 1);
2874        assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
2875    }
2876
2877    #[test]
2878    fn web_view_url_scheme_builder_collects_schemes() {
2879        let web = web_view_html("<img src=\"a:1\">", None)
2880            .url_scheme("a", |request| request.fail())
2881            .url_scheme("b", |request| request.fail())
2882            // Replaces `a`'s handler.
2883            .url_scheme("A", |request| request.fail())
2884            // Not a scheme the app may serve: ignored.
2885            .url_scheme("https", |request| request.fail());
2886        let schemes: Vec<String> = web
2887            .0
2888            .attrs
2889            .props
2890            .iter()
2891            .find_map(|p| match p {
2892                Prop::Native(NativeProp::UrlSchemes(list)) => {
2893                    Some(list.iter().map(|s| s.scheme().to_owned()).collect())
2894                }
2895                _ => None,
2896            })
2897            .unwrap();
2898        assert_eq!(schemes, ["b", "a"]);
2899    }
2900}