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