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, NativeEvent, OverlayPosition, Selection, VideoInfo,
15        VideoProgress, WebNavigation,
16    },
17};
18use crate::{
19    AudioSession, AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, Hsla, JsonValue,
20    KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp,
21    OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType, Rgba,
22    ScreenAnimation, ScreenProp, ScrollProp, Size, StatusBarSetting, SubmitBehavior, Tag,
23    WebSource,
24    canvas::{
25        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
26        Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
27    },
28    geometry::{Bounds, Corners, Point, Radians, ScaledPixels},
29    js::host::HostProps,
30    overlay::{Align, OverlayAnchor, Placement},
31    style::SvgPaint,
32};
33
34/// Whether `a` and `b` set the same property (their values aside).
35pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
36    match (a, b) {
37        (Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
38        (Prop::ComponentPropBinding(a, _), Prop::ComponentPropBinding(b, _)) => a == b,
39        (Prop::RustProp(a, _), Prop::RustProp(b, _)) => a == b,
40        _ => HostProps::same_kind(a, b),
41    }
42}
43
44/// `prop`'s property at its default (what clearing it from JS sets), for
45/// the props elements set; `None` for those set once.
46pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
47    match prop {
48        Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
49        Prop::ComponentPropBinding(name, _) => Some(Prop::ComponentPropBinding(name.clone(), None)),
50        Prop::RustProp(name, _) => Some(Prop::RustProp(name, None)),
51        _ => HostProps::reset(prop),
52    }
53}
54
55/// Sets `prop` on `node`, replacing the value of the same property.
56pub(crate) fn set(node: &mut ElNode, prop: Prop) {
57    set_in(&mut node.attrs.props, prop);
58}
59
60crate::static_reactive!(Color: Color);
61crate::static_reactive!(Hsla: Hsla, Rgba, Color);
62crate::static_reactive!(crate::AccessibilityRole: crate::AccessibilityRole);
63crate::static_reactive!(AutoCapitalize: AutoCapitalize);
64crate::static_reactive!(AutoFill: AutoFill);
65crate::static_reactive!(crate::HeaderSystemItem: crate::HeaderSystemItem);
66crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
67crate::static_reactive!(KeyboardType: KeyboardType);
68crate::static_reactive!(ModalAnimation: ModalAnimation);
69crate::static_reactive!(ModalPresentation: ModalPresentation);
70crate::static_reactive!(ResizeMode: ResizeMode);
71crate::static_reactive!(ReturnKeyType: ReturnKeyType);
72crate::static_reactive!(SubmitBehavior: SubmitBehavior);
73crate::static_reactive!(PasteBehavior: PasteBehavior);
74crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
75crate::static_reactive!(JsonValue: JsonValue);
76crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
77crate::static_reactive!(Placement: Placement);
78crate::static_reactive!(Align: Align);
79
80/// Sets `prop` among `props`, replacing one of its kind.
81pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
82    match props.iter_mut().find(|p| same_kind(p, &prop)) {
83        Some(p) => *p = prop,
84        None => props.push(prop),
85    }
86}
87
88/// Sets the prop `prop` makes of `value`: now when it is static, else as a
89/// bound part.
90pub(crate) fn bind_prop<T: 'static>(
91    node: &mut ElNode,
92    value: impl IntoReactive<T>,
93    prop: impl Fn(T) -> Prop + 'static,
94) {
95    node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
96}
97
98/// Adds a typed listener of `kind`.
99fn listen<T: ?Sized + ToOwned + 'static>(
100    node: &mut ElNode,
101    kind: EventKind,
102    listener: Listener<T>,
103    decode: events::Decode<T>,
104) {
105    node.handlers.push((kind, events::typed(listener, decode)));
106}
107
108macro_rules! host_element {
109    ($(#[$doc:meta])* $name:ident) => {
110        $(#[$doc])*
111        #[derive(Clone)]
112        pub struct $name(ElNode);
113
114        impl Element for $name {
115            fn node(&mut self) -> &mut ElNode {
116                &mut self.0
117            }
118        }
119
120        impl IntoElement for $name {
121            fn into_element(self) -> AnyElement {
122                AnyElement(self.0)
123            }
124        }
125
126        impl Accessible for $name {}
127        impl Interactive for $name {}
128
129        impl super::builder::IntoTooltip for $name {
130            fn apply_tooltip(self, node: &mut ElNode) {
131                self.into_element().apply_tooltip(node);
132            }
133        }
134
135        // Not every element has props of its own and events.
136        #[allow(dead_code)]
137        impl $name {
138            fn set(mut self, prop: Prop) -> Self {
139                set(&mut self.0, prop);
140                self
141            }
142
143            fn bind_prop<T: 'static>(
144                mut self,
145                value: impl IntoReactive<T>,
146                prop: impl Fn(T) -> Prop + 'static,
147            ) -> Self {
148                bind_prop(&mut self.0, value, prop);
149                self
150            }
151
152            fn listen<T: ?Sized + ToOwned + 'static>(
153                mut self,
154                kind: EventKind,
155                listener: Listener<T>,
156                decode: events::Decode<T>,
157            ) -> Self {
158                listen(&mut self.0, kind, listener, decode);
159                self
160            }
161        }
162    };
163}
164
165host_element! {
166    /// A text field (`<input>`), made by [`input`]: one line, or several
167    /// with [`Input::multiline`]. Its text style comes from its styles.
168    Input
169}
170
171host_element! {
172    /// A scroll view (`<scroll>`), made by [`scroll`]: its children are its
173    /// content.
174    Scroll
175}
176
177host_element! {
178    /// A native navigation stack (`<stack>`, TS: `NavStack` of `nsh/base`),
179    /// made by `nsh_base::nav_stack`:
180    /// UINavigationController on iOS (swipe back, native header), a stack
181    /// with a toolbar and predictive back on Android. Its children are its
182    /// [`Screen`]s, bottom to top.
183    Stack
184}
185
186host_element! {
187    /// One page of a [`Stack`] (`<screen>`, TS: `NavPage` of `nsh/base`),
188    /// made by `nsh_base::nav_page`: its header options and its content (its
189    /// children).
190    Screen
191}
192
193host_element! {
194    /// A dialog (`<modal>`, TS: `Dialog` of `nsh/base`), made by
195    /// `nsh_base::dialog`: presented while it is in the view, over everything
196    /// else; its children are its content.
197    Modal
198}
199
200host_element! {
201    /// A bar over the keyboard (`<inputaccessory>`, TS: `InputAccessoryView`
202    /// of `nsh/ios`), made by [`input_accessory_view`]: its children are its
203    /// content.
204    InputAccessoryView
205}
206
207host_element! {
208    /// A view drawn with a [`Drawing`] (`<canvas>`), made by [`canvas`].
209    CanvasView
210}
211
212host_element! {
213    /// A web page (`<webview>`), made by [`web_view`].
214    WebView
215}
216
217host_element! {
218    /// A video player (`<video>`), made by [`video`].
219    Video
220}
221
222host_element! {
223    /// A native component the embedding app registered (`<native>`), made
224    /// by [`native`].
225    NativeView
226}
227
228host_element! {
229    /// Its children on top of the root view it is in (`<overlay>`, TS:
230    /// `Overlay` of `nsh`), made by [`overlay`]: the surface, or the dialog
231    /// around it; outside its parent's layout and clipping, while it stays
232    /// where it is for everything else (context, events, lifetime).
233    Overlay
234}
235
236impl ParentElement for Overlay {}
237impl ParentElement for Scroll {}
238impl ParentElement for Stack {}
239impl ParentElement for Screen {}
240impl ParentElement for Modal {}
241
242/// Android has no input accessories: there the bar keeps no content.
243impl ParentElement for InputAccessoryView {
244    fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
245        if !cfg!(target_os = "android") {
246            child.__push_into(&mut self.0.children);
247        }
248        self
249    }
250
251    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
252        if !cfg!(target_os = "android") {
253            self.0
254                .children
255                .extend(children.into_iter().map(|c| c.into_element().0));
256        }
257        self
258    }
259}
260
261/// An overlay: its children shown on top of the root view it is in (the
262/// surface, or the dialog around it), above what that root view shows and
263/// the overlays shown before it, while it is in the view (in a region:
264/// [`super::If`]). Without an anchor it is laid out as a `position: fixed`
265/// box of the root view (`.absolute().inset_0()` covers it); with one
266/// ([`Overlay::anchor`], [`Overlay::anchor_point`]) it goes on a side of it
267/// and follows it ([`crate::overlay`]).
268pub fn overlay() -> Overlay {
269    Overlay(ElNode::new(Tag::Overlay))
270}
271
272/// A text field.
273pub fn input() -> Input {
274    Input(ElNode::new(Tag::Input))
275}
276
277/// A vertical scroll view ([`Scroll::horizontal`] for a horizontal one).
278pub fn scroll() -> Scroll {
279    Scroll(ElNode::new(Tag::Scroll))
280}
281
282/// A native navigation stack of [`screen`]s: put a screen in to push it,
283/// leave it out to pop it. Give each screen a [`Element::key`] (its route)
284/// so the screens below keep their state.
285///
286/// The core's part of `nsh_base::nav_stack`, which apps use.
287#[doc(hidden)]
288pub fn stack() -> Stack {
289    Stack(ElNode::new(Tag::Stack))
290}
291
292/// A screen of a [`stack`]. What it shows reads its insets below the
293/// header ([`super::Scope::insets`]).
294///
295/// The core's part of `nsh_base::nav_page`, which apps use.
296#[doc(hidden)]
297pub fn screen() -> Screen {
298    let mut node = ElNode::new(Tag::Screen);
299    // Its insets come with this event.
300    node.handlers.push((EventKind::Insets, Listener::noop()));
301    Screen(node)
302}
303
304/// A modal presenting its children. Put it in the view to present it (in
305/// a region: [`super::If`]), leave it out to dismiss it.
306///
307/// The core's part of `nsh_base::dialog`, which apps use.
308#[doc(hidden)]
309pub fn modal() -> Modal {
310    let mut node = ElNode::new(Tag::Modal);
311    // Its insets (`Scope::insets` inside it) come with this event.
312    node.handlers.push((EventKind::Insets, Listener::noop()));
313    Modal(node)
314}
315
316/// A bar shown over the keyboard of the inputs whose
317/// [`Input::input_accessory`] is `native_id` (iOS's `inputAccessoryView`):
318/// as wide as the window and as tall as its content, moving with the
319/// keyboard natively. It takes no room where the view places it; on
320/// Android, which has no input accessories, it is an empty hidden view.
321pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
322    let tag = if cfg!(target_os = "android") {
323        Tag::View
324    } else {
325        Tag::InputAccessory
326    };
327    let mut node = ElNode::new(tag);
328    if cfg!(target_os = "android") {
329        node.style.keyword(crate::StyleKey::Display, "none");
330    } else {
331        set(&mut node, Prop::NativeId(Some(native_id.into())));
332    }
333    InputAccessoryView(node)
334}
335
336/// A canvas showing what `painter` recorded (animated values in it move
337/// natively). A closure draws in a binding: `canvas(move || draw(theme()))`
338/// draws again when what it read changes (a size kept from `on_layout`,
339/// the appearance).
340pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
341    let mut node = ElNode::new(Tag::Canvas);
342    node.bind_attr(painter, |attrs, painter: Painter| {
343        attrs.drawing = Some(Arc::new(painter.drawing));
344        attrs.bound = painter.nodes;
345    });
346    CanvasView(node)
347}
348
349crate::static_reactive!(Painter: Painter, Drawing);
350
351/// A web view loading `url` (a bound one loads again when it changes).
352pub fn web_view(url: impl IntoReactive<String>) -> WebView {
353    WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
354        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
355    })
356}
357
358/// A web view showing the page `html`, its relative links resolved against
359/// `base_url` (TS: `html` and `baseUrl`).
360pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
361    WebView(ElNode::new(Tag::WebView)).html(html, base_url)
362}
363
364/// A video playing the file or stream at `url` (a bound one plays the new
365/// one when it changes).
366pub fn video(url: impl IntoReactive<String>) -> Video {
367    Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
368        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
369    })
370}
371
372/// The embedder's native component registered as `name`.
373pub fn native(name: &str) -> NativeView {
374    NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
375}
376
377impl Input {
378    /// The text, when the component controls it (update it from
379    /// [`Self::on_change`]).
380    pub fn value(self, text: impl IntoReactive<String>) -> Self {
381        self.bind_prop(text, |text: String| Prop::Value(text))
382    }
383
384    /// The first text, when the input keeps its own.
385    pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
386        self.bind_prop(text, |text: String| Prop::DefaultValue(text))
387    }
388
389    /// Shown while it is empty.
390    pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
391        self.bind_prop(text, |text: String| Prop::Placeholder(text))
392    }
393
394    /// The placeholder's color (`cx.color(theme.muted_foreground)`).
395    pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
396        self.bind_prop(color, |color: Hsla| {
397            Prop::PlaceholderColor(Some(color.into()))
398        })
399    }
400
401    /// The caret's and the selection's color.
402    pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
403        self.bind_prop(color, |color: Hsla| {
404            Prop::SelectionColor(Some(color.into()))
405        })
406    }
407
408    /// Hides what is typed (passwords; TS: `masked`).
409    pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
410        self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
411    }
412
413    /// The software keyboard's layout.
414    pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
415        self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
416    }
417
418    /// The software keyboard's light or dark look (iOS; TS:
419    /// `ios={{ keyboardAppearance }}`).
420    pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
421        self.bind_prop(appearance, |appearance: KeyboardAppearance| {
422            Prop::KeyboardAppearance(appearance)
423        })
424    }
425
426    /// The return key's label.
427    pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
428        self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
429    }
430
431    /// Automatic capitals.
432    pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
433        self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
434    }
435
436    /// Spelling correction (default on).
437    pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
438        self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
439    }
440
441    /// What it holds, for autofill and suggestions.
442    pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
443        self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
444    }
445
446    /// Several lines, growing with the text (return adds a line).
447    pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
448        self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
449    }
450
451    /// At most `length` characters.
452    pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
453        self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
454    }
455
456    /// The text can be selected and copied but not changed.
457    pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
458        self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
459    }
460
461    /// What return does (`submitBehavior`; default: submit and unfocus for
462    /// one line, a line break for several).
463    pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
464        self.bind_prop(behavior, |behavior: SubmitBehavior| {
465            Prop::SubmitBehavior(Some(behavior))
466        })
467    }
468
469    /// What a paste does (`pasteBehavior`; default: insert its text).
470    /// [`Self::on_paste`] hears what was pasted either way.
471    pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
472        self.bind_prop(behavior, Prop::PasteBehavior)
473    }
474
475    /// The user pasted: the text, the files with their bytes (a
476    /// screenshot) and local files' URLs, before the text it inserts is
477    /// reported.
478    pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
479        self.listen(EventKind::Paste, listener.into_listener(), events::paste)
480    }
481
482    /// Focused when it appears.
483    pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
484        self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
485    }
486
487    /// The caret is drawn (default yes; TS: `caret`).
488    pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
489        self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
490    }
491
492    /// Shows the input accessory with this `nativeID` over the keyboard
493    /// ([`input_accessory_view`]; iOS).
494    pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
495        self.bind_prop(native_id, |id: String| {
496            Prop::InputAccessoryViewId(Some(id.into()))
497        })
498    }
499
500    /// Selects `(start, end)` (UTF-16 units; a caret when equal) when the
501    /// input is made and whenever the value changes (TS: the controlled
502    /// `selectedRange`); the user moves it on from there
503    /// ([`Self::on_selection_change`]).
504    pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
505        self.bind_prop(range, |(start, end): (u32, u32)| {
506            Prop::Selection(start, end)
507        })
508    }
509
510    /// The text changed (the new text).
511    pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
512        self.listen(
513            EventKind::ChangeText,
514            listener.into_listener(),
515            events::text,
516        )
517    }
518
519    /// The return (enter) key was pressed (the text).
520    pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
521        self.listen(
522            EventKind::SubmitEditing,
523            listener.into_listener(),
524            events::text,
525        )
526    }
527
528    /// The selection or caret moved.
529    pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
530        self.listen(
531            EventKind::SelectionChange,
532            listener.into_listener(),
533            events::selection,
534        )
535    }
536
537    /// The caret moved: with the selection, or as the text scrolled or
538    /// wrapped again ([`CaretEvent`]: where it is, in the input and in the
539    /// root view).
540    pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
541        self.listen(
542            EventKind::CaretMove,
543            listener.into_listener(),
544            events::caret,
545        )
546    }
547
548    /// A key was pressed: the character, `Backspace` or `Enter`.
549    pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
550        self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
551    }
552
553    /// An input method's composition started, changed or ended (the text
554    /// being composed, empty once it ends): the text is the input's only
555    /// once committed, reported by [`Self::on_change`] first.
556    pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
557        self.listen(
558            EventKind::CompositionChange,
559            listener.into_listener(),
560            events::composition,
561        )
562    }
563
564    /// The text's size changed (multiline inputs growing).
565    pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
566        self.listen(
567            EventKind::ContentSizeChange,
568            listener.into_listener(),
569            events::size,
570        )
571    }
572}
573
574impl Scroll {
575    /// Scrolls horizontally.
576    pub fn horizontal(self) -> Self {
577        self.set(Prop::Horizontal(true))
578    }
579
580    /// Whether the scroll indicator shows (default yes).
581    pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
582        self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows))
583    }
584
585    /// Pinch zoom between `min` and `max`.
586    pub fn zoom_range(self, min: f32, max: f32) -> Self {
587        self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
588            .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
589    }
590
591    /// The zoom.
592    pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
593        self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
594    }
595
596    /// Pinches may go past the zoom limits and spring back (default yes;
597    /// TS: `bouncesZoom`).
598    pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
599        self.bind_prop(bounces, |bounces: bool| {
600            Prop::Scroll(ScrollProp::BouncesZoom(bounces))
601        })
602    }
603
604    /// The user can pinch to zoom (default yes; TS: `zoomable`).
605    pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
606        self.bind_prop(enabled, |enabled: bool| {
607            Prop::Scroll(ScrollProp::Pinch(enabled))
608        })
609    }
610
611    /// Content smaller than the view sits in its center (zoomed images).
612    pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
613        self.bind_prop(center, |center: bool| {
614            Prop::Scroll(ScrollProp::CenterContent(center))
615        })
616    }
617}
618
619impl super::Scrollable for Scroll {}
620
621impl Screen {
622    fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
623        let mut node = ElNode::new(Tag::HeaderItem);
624        node.key = Some(key.into());
625        set(&mut node, Prop::HeaderSlot(slot));
626        node.children.push(item.into_element().0);
627        self.0.children.push(node);
628        self
629    }
630
631    /// The header's title.
632    pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
633        self.bind_prop(title, |t| {
634            Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
635        })
636    }
637
638    /// Whether the header shows (default true).
639    pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
640        self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
641    }
642
643    /// A large title (iOS); the content scrolls under the header.
644    pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
645        self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
646    }
647
648    /// The content extends under the header.
649    pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
650        self.bind_prop(transparent, |v| {
651            Prop::Screen(ScreenProp::HeaderTransparent(v))
652        })
653    }
654
655    /// The header's colors: `backgroundColor`, `color` (the title's) and
656    /// `tintColor` (the buttons'), as [`super::Style::from_decls`] makes
657    /// them (TS: `headerStyle`); a style of typed styles applies as
658    /// [`Self::header_style_with`]'s do.
659    pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
660        let style = match style.into_reactive() {
661            // Its bound parts are read in the binding, which follows them.
662            super::Reactive::Static(s) if s.1.is_bound() => {
663                super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
664            }
665            style => style,
666        };
667        self.0.bind_attr(style, |a, s: super::Style| {
668            set_in(&mut a.props, Prop::HeaderStyle(s.0));
669            if !s.1.is_empty() {
670                let typed = s.1.resolved();
671                let list = (!typed.is_empty()).then(|| Arc::new(typed.lower()));
672                set_in(&mut a.props, Prop::HeaderClassList(list));
673            }
674        });
675        self
676    }
677
678    /// The header's colors as typed styles: the background
679    /// ([`super::Styled::bg`]), the title's color
680    /// ([`super::Styled::text_color`]) and the buttons'
681    /// ([`super::Styled::tint_color`]), theme colors following the
682    /// appearance natively (TS: `headerClass`). `f` runs again when what it
683    /// reads changes. [`Self::header_style`] wins over it, key by key.
684    pub fn header_style_with(
685        self,
686        f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
687    ) -> Self {
688        let list = move || {
689            let style = f(super::StyleRefinement::default()).resolved();
690            (!style.is_empty()).then(|| Arc::new(style.lower()))
691        };
692        self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
693            Prop::HeaderClassList(list)
694        })
695    }
696
697    /// The label of the back button leading back to this screen (iOS).
698    pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
699        self.bind_prop(title, |t| {
700            Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
701        })
702    }
703
704    /// The trailing header button is UIKit's own, drawn instead of the
705    /// `header_right` view (iOS; a press on it presses that view's first
706    /// pressable view).
707    pub fn header_right_system_item(
708        self,
709        item: impl IntoReactive<crate::HeaderSystemItem>,
710    ) -> Self {
711        self.bind_prop(item, |item| {
712            Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
713        })
714    }
715
716    /// Whether the back button shows (default true).
717    pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
718        self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
719    }
720
721    /// The interactive back gesture pops (iOS swipe back, Android
722    /// predictive back); the back buttons pop either way (default true).
723    pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
724        self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
725    }
726
727    /// The back buttons and the swipe back pop the screen (default true);
728    /// false keeps it, reporting [`Self::on_back_press`] instead. Decided
729    /// natively when the system asks, so set it before the user acts.
730    pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
731        self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
732    }
733
734    /// How the screen enters and leaves.
735    pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
736        self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
737    }
738
739    /// What the status bar shows while the screen is up (iOS and Android;
740    /// TS: `statusBar`): over the screens below it and the app's default,
741    /// field by field, as a view controller's `preferredStatusBarStyle`.
742    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
743        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
744    }
745
746    /// An element at the header's start (instead of the back button).
747    pub fn header_left(self, item: impl IntoElement) -> Self {
748        self.header_item(HeaderSlot::Left, "header-left", item)
749    }
750
751    /// An element at the header's end.
752    pub fn header_right(self, item: impl IntoElement) -> Self {
753        self.header_item(HeaderSlot::Right, "header-right", item)
754    }
755
756    /// An element replacing the title.
757    pub fn header_title(self, item: impl IntoElement) -> Self {
758        self.header_item(HeaderSlot::Title, "header-title", item)
759    }
760
761    /// The app's header on platforms without a system header (desktops,
762    /// the web): placed at the top of the screen, as wide as it and as tall
763    /// as it lays out, with the content below it (TS: `header`).
764    pub fn header(self, item: impl IntoElement) -> Self {
765        self.header_item(HeaderSlot::Header, "header", item)
766    }
767
768    /// The user popped the screen natively (back button, swipe): leave it
769    /// out of the view (its region).
770    pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
771        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
772    }
773
774    /// The user pressed back on the screen (every back press, whether or
775    /// not [`Self::pop_on_back`] let it pop).
776    pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
777        self.listen(
778            EventKind::BackRequest,
779            listener.into_listener(),
780            events::unit,
781        )
782    }
783}
784
785impl Overlay {
786    /// Places it against the element carrying `anchor` (rendered before
787    /// it), following it as it moves: on the [`Self::placement`] side, on
788    /// the other when only that one has room, kept inside the safe area.
789    pub fn anchor(self, anchor: &super::ElementRef) -> Self {
790        let anchor = *anchor;
791        self.bind_prop(
792            move || match anchor.node() {
793                Some(id) => OverlayAnchor::Node(id),
794                None => OverlayAnchor::None,
795            },
796            |a| Prop::Overlay(OverlayProp::Anchor(a)),
797        )
798    }
799
800    /// Places it against what the element carrying `anchor` draws: the box
801    /// around its children, so a trigger in a wrapper its parent stretches
802    /// is placed against what shows ([`OverlayAnchor::Content`]).
803    pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
804        let anchor = *anchor;
805        self.bind_prop(
806            move || match anchor.node() {
807                Some(id) => OverlayAnchor::Content(id),
808                None => OverlayAnchor::None,
809            },
810            |a| Prop::Overlay(OverlayProp::Anchor(a)),
811        )
812    }
813
814    /// Places it against a point of the root view (a touch's `page`: a
815    /// menu where the pointer is).
816    pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
817        self.bind_prop(point, |p| {
818            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
819        })
820    }
821
822    /// Places it against a box of the root view: an input's caret
823    /// ([`CaretEvent::page_bounds`]), where suggestions for what is being
824    /// typed open.
825    pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
826        self.bind_prop(bounds, |b| {
827            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
828        })
829    }
830
831    /// The side of the anchor it goes on (default below).
832    pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
833        self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
834    }
835
836    /// How it lines up with the anchor along that side (default centered).
837    pub fn align(self, align: impl IntoReactive<Align>) -> Self {
838        self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
839    }
840
841    /// The gap between the anchor and it.
842    pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
843        self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
844    }
845
846    /// The distance it keeps from the edges of the safe area.
847    pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
848        self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
849    }
850
851    /// A press went down outside it, its anchor and the overlays inside it
852    /// (where, in the root view). Closing is the listener's: leave it out
853    /// of the view.
854    pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
855        self.listen(
856            EventKind::PressOutside,
857            listener.into_listener(),
858            events::page_point,
859        )
860    }
861
862    /// Escape or the Android back button, while it is the top overlay
863    /// listening (it takes them from those below, the pages and
864    /// [`super::on_back_press`]).
865    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
866        self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
867    }
868
869    /// Makes it a hint (a tooltip): shown once the pointer rested on its
870    /// anchor (its parent without one) for `delay`, until the pointer
871    /// leaves or presses the anchor, on the desktops only; it is placed
872    /// against the anchor and should not take the pointer
873    /// ([`Interactive::pointer_events`] none). [`Self::hint_open`] decides
874    /// instead of the pointer.
875    pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
876        self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
877    }
878
879    /// A hint shown (`Some(true)`) or hidden (`Some(false)`) whatever the
880    /// pointer does: its owner follows [`Self::on_hint_show`] /
881    /// [`Self::on_hint_hide`] (a `Tooltip` controlled by the app). `None`:
882    /// the pointer decides.
883    pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
884        self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
885    }
886
887    /// The pointer rested on a hint's anchor for its delay: it asks to
888    /// show (and shows, unless [`Self::hint_open`] decides).
889    pub fn on_hint_show<M>(self, listener: impl IntoListener<(), M>) -> Self {
890        self.listen(EventKind::Show, listener.into_listener(), events::unit)
891    }
892
893    /// The pointer left or pressed a hint's anchor, or the hint left the
894    /// view, after it asked to show: it asks to hide.
895    pub fn on_hint_hide<M>(self, listener: impl IntoListener<(), M>) -> Self {
896        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
897    }
898
899    /// The core placed it against its anchor: the side it went on, its
900    /// frame and the room on that side.
901    pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
902        self.listen(
903            EventKind::Position,
904            listener.into_listener(),
905            events::overlay_position,
906        )
907    }
908}
909
910impl Modal {
911    /// How it comes in (default: slides up).
912    pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
913        self.bind_prop(animation, |animation: ModalAnimation| {
914            Prop::Modal(ModalProp::Animation(animation))
915        })
916    }
917
918    /// Full screen, or a sheet (iOS).
919    pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
920        self.bind_prop(presentation, |presentation: ModalPresentation| {
921            Prop::Modal(ModalProp::Presentation(presentation))
922        })
923    }
924
925    /// What the status bar shows while it is presented (iOS and Android;
926    /// TS: `statusBar`): over what is below it, field by field.
927    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
928        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
929    }
930
931    /// Under the status bar (Android).
932    pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
933        self.bind_prop(translucent, |translucent: bool| {
934            Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
935        })
936    }
937
938    /// The orientations it allows while it is presented (iOS; default:
939    /// those of what presents it).
940    pub fn supported_orientations(
941        self,
942        orientations: impl IntoIterator<Item = Orientation>,
943    ) -> Self {
944        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
945        self.set(Prop::Modal(ModalProp::Orientations(bits)))
946    }
947
948    /// Escape and the Android back button close it natively (default
949    /// true); either way they report [`Self::on_cancel`].
950    pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
951        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
952    }
953
954    /// A press on a backdrop the platform presents itself (a native
955    /// sheet's) closes it (default true); a backdrop the app renders is
956    /// the app's to handle.
957    pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
958        self.bind_prop(close, |v: bool| {
959            Prop::Modal(ModalProp::CloseOnBackdropPress(v))
960        })
961    }
962
963    /// Swiping a sheet down closes it natively (default true).
964    pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
965        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
966    }
967
968    /// The user tried to close it (Escape or back, a backdrop press, a
969    /// swipe down), whether or not it closed: leave it out of the view
970    /// (its region) to close it.
971    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
972        self.listen(
973            EventKind::RequestClose,
974            listener.into_listener(),
975            events::unit,
976        )
977    }
978
979    /// It finished appearing.
980    pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
981        self.listen(EventKind::Show, listener.into_listener(), events::unit)
982    }
983
984    /// The user or the system closed it.
985    pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
986        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
987    }
988}
989
990/// An orientation of the screen ([`Modal::supported_orientations`]).
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum Orientation {
993    /// Upright.
994    Portrait,
995    /// Upside down.
996    PortraitUpsideDown,
997    /// Either landscape.
998    Landscape,
999    /// Landscape, the top on the left.
1000    LandscapeLeft,
1001    /// Landscape, the top on the right.
1002    LandscapeRight,
1003}
1004
1005impl Orientation {
1006    fn bits(self) -> u8 {
1007        use crate::ModalConfig as M;
1008        match self {
1009            Orientation::Portrait => M::PORTRAIT,
1010            Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
1011            Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
1012            Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
1013            Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
1014        }
1015    }
1016}
1017
1018impl WebView {
1019    /// Loads `html` (relative links against `base_url`) instead of a URL;
1020    /// a bound page loads again when it changes.
1021    pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
1022        let base_url: Option<Arc<str>> = base_url.map(Into::into);
1023        self.bind_prop(html, move |html: String| {
1024            Prop::Native(NativeProp::Source(WebSource::Html {
1025                html: html.into(),
1026                base_url: base_url.clone(),
1027            }))
1028        })
1029    }
1030
1031    /// Runs after each page loads.
1032    pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
1033        self.bind_prop(script, |script: String| {
1034            Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
1035        })
1036    }
1037
1038    /// Runs before each page's own scripts.
1039    pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
1040        self.bind_prop(script, |script: String| {
1041            Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
1042        })
1043    }
1044
1045    /// The user agent it sends.
1046    pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
1047        self.bind_prop(agent, |agent: String| {
1048            Prop::Native(NativeProp::UserAgent(Some(agent.into())))
1049        })
1050    }
1051
1052    /// Scrolls (default yes).
1053    pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
1054        self.bind_prop(enabled, |enabled: bool| {
1055            Prop::Native(NativeProp::Scrollable(enabled))
1056        })
1057    }
1058
1059    /// Runs the pages' JavaScript (default yes).
1060    pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
1061        self.bind_prop(enabled, |enabled: bool| {
1062            Prop::Native(NativeProp::JavaScriptEnabled(enabled))
1063        })
1064    }
1065
1066    /// Swipes go back and forward (iOS).
1067    pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
1068        self.bind_prop(enabled, |enabled: bool| {
1069            Prop::Native(NativeProp::BackForwardGestures(enabled))
1070        })
1071    }
1072
1073    /// A page started loading.
1074    pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1075        self.listen(
1076            EventKind::LoadStart,
1077            listener.into_listener(),
1078            events::navigation,
1079        )
1080    }
1081
1082    /// A page loaded.
1083    pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
1084        self.listen(
1085            EventKind::Load,
1086            listener.into_listener(),
1087            events::navigation,
1088        )
1089    }
1090
1091    /// A page failed to load (the message).
1092    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1093        self.listen(EventKind::Error, listener.into_listener(), events::message)
1094    }
1095
1096    /// The page called `window.nsh.postMessage(data)`.
1097    pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
1098        self.listen(EventKind::Message, listener.into_listener(), events::data)
1099    }
1100
1101    /// It navigated.
1102    pub fn on_navigation_state_change<M>(
1103        self,
1104        listener: impl IntoListener<WebNavigation, M>,
1105    ) -> Self {
1106        self.listen(
1107            EventKind::NavigationStateChange,
1108            listener.into_listener(),
1109            events::navigation,
1110        )
1111    }
1112}
1113
1114impl Video {
1115    /// Paused.
1116    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
1117        self.bind_prop(paused, |paused: bool| {
1118            Prop::Native(NativeProp::Paused(paused))
1119        })
1120    }
1121
1122    /// Without sound.
1123    pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
1124        self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
1125    }
1126
1127    /// 0..1.
1128    pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
1129        self.bind_prop(volume, |volume: f32| {
1130            Prop::Native(NativeProp::Volume(volume))
1131        })
1132    }
1133
1134    /// Playback speed.
1135    pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
1136        self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
1137    }
1138
1139    /// Starts over at the end.
1140    pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
1141        self.bind_prop(repeat, |repeat: bool| {
1142            Prop::Native(NativeProp::Repeat(repeat))
1143        })
1144    }
1145
1146    /// How the picture fits (default: contain).
1147    pub fn resize_mode(self, mode: impl IntoReactive<ResizeMode>) -> Self {
1148        self.bind_prop(mode, |mode: ResizeMode| {
1149            Prop::Native(NativeProp::VideoResizeMode(mode))
1150        })
1151    }
1152
1153    /// The platform's playback controls.
1154    pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
1155        self.bind_prop(controls, |controls: bool| {
1156            Prop::Native(NativeProp::Controls(controls))
1157        })
1158    }
1159
1160    /// Milliseconds between [`Self::on_progress`] events (default 250).
1161    pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
1162        self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
1163    }
1164
1165    /// What its sound does to the rest of the device's audio while it
1166    /// plays (default: the app's audio settings).
1167    pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
1168        self.bind_prop(session, |session: AudioSession| {
1169            Prop::Native(NativeProp::AudioSession(session))
1170        })
1171    }
1172
1173    /// It started loading.
1174    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1175        self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
1176    }
1177
1178    /// It loaded: length and size.
1179    pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
1180        self.listen(EventKind::Load, listener.into_listener(), events::video)
1181    }
1182
1183    /// It played on.
1184    pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
1185        self.listen(
1186            EventKind::Progress,
1187            listener.into_listener(),
1188            events::progress,
1189        )
1190    }
1191
1192    /// It played to its end.
1193    pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1194        self.listen(EventKind::End, listener.into_listener(), events::unit)
1195    }
1196
1197    /// It started (`true`) or stopped buffering.
1198    pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
1199        self.listen(
1200            EventKind::Buffer,
1201            listener.into_listener(),
1202            events::buffering,
1203        )
1204    }
1205
1206    /// It failed (the message).
1207    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1208        self.listen(EventKind::Error, listener.into_listener(), events::message)
1209    }
1210}
1211
1212impl NativeView {
1213    /// Its prop `name` (any JSON value), as JS's `nativeComponent` passes it;
1214    /// a bound one is passed again when it changes.
1215    pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
1216        let name: Arc<str> = name.into();
1217        self.bind_prop(value, move |value| {
1218            Prop::ComponentProp(name.clone(), Some(value))
1219        })
1220    }
1221
1222    /// Binds its prop `name` to an animated value: the platform hands the
1223    /// value (a number or a color) to the component on every frame it
1224    /// changes, with no engine work per frame (JS: an animated value given
1225    /// to a `nativeComponent` prop). A value set with [`Self::prop`] under
1226    /// that name waits until the binding goes.
1227    pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
1228        if let Some(node) = value.animated_node().live() {
1229            set(
1230                &mut self.0,
1231                Prop::ComponentPropBinding(name.into(), Some(node.id())),
1232            );
1233            self.0.attrs.bound.push(node);
1234        }
1235        self
1236    }
1237
1238    /// It emitted an event.
1239    pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
1240        self.listen(
1241            EventKind::NativeEvent,
1242            listener.into_listener(),
1243            events::native,
1244        )
1245    }
1246}
1247
1248/// A number in a drawing: a constant, or an animated value the canvas reads
1249/// while it draws (it draws again natively as the value moves).
1250#[derive(Debug, Clone, PartialEq)]
1251pub struct CanvasArg(pub(crate) CanvasArgKind);
1252
1253#[derive(Debug, Clone, PartialEq)]
1254pub(crate) enum CanvasArgKind {
1255    Const(f32),
1256    Node(super::LiveNode),
1257}
1258
1259impl From<f32> for CanvasArg {
1260    fn from(n: f32) -> Self {
1261        Self(CanvasArgKind::Const(n))
1262    }
1263}
1264
1265/// A length (coordinates, sizes, line widths, radii).
1266impl From<Points> for CanvasArg {
1267    fn from(n: Points) -> Self {
1268        Self(CanvasArgKind::Const(n.0))
1269    }
1270}
1271
1272/// An angle (arcs, rotations).
1273impl From<Radians> for CanvasArg {
1274    fn from(n: Radians) -> Self {
1275        Self(CanvasArgKind::Const(n.0))
1276    }
1277}
1278
1279/// An animated value whose owner is gone counts as 0.
1280impl<A: super::Animated> From<&A> for CanvasArg {
1281    fn from(a: &A) -> Self {
1282        Self(match a.animated_node().live() {
1283            Some(node) => CanvasArgKind::Node(node),
1284            None => CanvasArgKind::Const(0.0),
1285        })
1286    }
1287}
1288
1289/// What a drawing fills or strokes with (`fillStyle` / `strokeStyle`): a
1290/// color, a gradient ([`CanvasGradient::linear`], `radial`, `conic`), or a
1291/// animated value interpolating colors
1292/// ([`super::AnimatedNode::interpolate_colors`]), read as it moves.
1293#[derive(Debug, Clone, PartialEq)]
1294pub struct CanvasPaint(CanvasPaintKind);
1295
1296#[derive(Debug, Clone, PartialEq)]
1297enum CanvasPaintKind {
1298    Color(Color),
1299    Gradient(Arc<CanvasGradient>),
1300    Node(super::LiveNode),
1301}
1302
1303impl From<Color> for CanvasPaint {
1304    fn from(color: Color) -> Self {
1305        Self(CanvasPaintKind::Color(color))
1306    }
1307}
1308
1309impl From<Hsla> for CanvasPaint {
1310    fn from(color: Hsla) -> Self {
1311        Color::from(color).into()
1312    }
1313}
1314
1315impl From<Rgba> for CanvasPaint {
1316    fn from(color: Rgba) -> Self {
1317        Color::from(color).into()
1318    }
1319}
1320
1321impl From<CanvasGradient> for CanvasPaint {
1322    fn from(gradient: CanvasGradient) -> Self {
1323        Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
1324    }
1325}
1326
1327impl From<Arc<CanvasGradient>> for CanvasPaint {
1328    fn from(gradient: Arc<CanvasGradient>) -> Self {
1329        Self(CanvasPaintKind::Gradient(gradient))
1330    }
1331}
1332
1333/// An animated value whose owner is gone paints nothing (transparent).
1334impl<A: super::Animated> From<&A> for CanvasPaint {
1335    fn from(a: &A) -> Self {
1336        Self(match a.animated_node().live() {
1337            Some(node) => CanvasPaintKind::Node(node),
1338            None => CanvasPaintKind::Color(Color::TRANSPARENT),
1339        })
1340    }
1341}
1342
1343/// Records a [`Drawing`] with the HTML Canvas 2D operations (Rust names):
1344/// `Painter::new().fill_color(red).fill_rect(px(0.0), px(0.0), w, h).finish()`.
1345/// Coordinates are points from the canvas's top left. Numbers and paints
1346/// may be animated values (the canvas draws again natively as they move);
1347/// operations without a method here are built by hand with
1348/// [`Painter::num`], [`Painter::paint`] and [`Painter::op`]. Text is
1349/// measured with [`super::ambient::measure_text`].
1350#[derive(Debug, Clone, Default)]
1351pub struct Painter {
1352    drawing: Drawing,
1353    /// The nodes of the animated values the drawing reads, held with it.
1354    nodes: Vec<super::LiveNode>,
1355}
1356
1357impl Painter {
1358    /// An empty drawing.
1359    pub fn new() -> Self {
1360        Self::default()
1361    }
1362
1363    /// The drawing.
1364    pub fn finish(self) -> Drawing {
1365        self.drawing
1366    }
1367
1368    /// `value` as a number of this drawing, for an operation built by hand
1369    /// ([`Self::op`]): an animated value becomes a slot the canvas reads while
1370    /// it draws, kept alive with the drawing.
1371    pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
1372        match value.into().0 {
1373            CanvasArgKind::Const(n) => Num::Const(n),
1374            CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
1375        }
1376    }
1377
1378    /// `paint` as a paint of this drawing, for an operation built by hand
1379    /// ([`Self::op`]).
1380    pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
1381        match paint.into().0 {
1382            CanvasPaintKind::Color(color) => Paint::Color(color),
1383            CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
1384            CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
1385        }
1386    }
1387
1388    fn slot(&mut self, node: super::LiveNode) -> u16 {
1389        let slot = self.drawing.slot(node.id());
1390        self.nodes.push(node);
1391        slot
1392    }
1393
1394    /// Adds `node`: a part of the drawing that assistive technologies and
1395    /// UI tests see as an element of its own ([`crate::canvas::CanvasNode`]).
1396    pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
1397        self.drawing.nodes.push(node);
1398        self
1399    }
1400
1401    /// Records `op` (one built by hand: its numbers and paints from
1402    /// [`Self::num`] and [`Self::paint`]).
1403    pub fn op(mut self, op: CanvasOp) -> Self {
1404        self.drawing.ops.push(op);
1405        self
1406    }
1407
1408    fn path(self, op: PathOp) -> Self {
1409        self.op(CanvasOp::Path(op))
1410    }
1411
1412    /// Whether `point` (in the canvas, as a touch's location) is inside the
1413    /// current path by `rule`, with the transform, as recorded so far (TS:
1414    /// `cx.isPointInPath(x, y, rule)`). Answered from the geometry here,
1415    /// with no platform round trip; a number given as an animated value
1416    /// counts as 0, as in TS. To find what is under a tap, build the
1417    /// canvas's painter in a function the press handler calls too.
1418    pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
1419        crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
1420    }
1421
1422    /// Whether `point` is on the stroke of the current path with the line
1423    /// width and cap recorded so far (TS: `cx.isPointInStroke(x, y)`;
1424    /// round joins, no dashes). See [`Self::is_point_in_path`].
1425    pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
1426        crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
1427    }
1428
1429    /// Whether `point` is inside `path` by `rule`, with the transform
1430    /// recorded so far (TS: `cx.isPointInPath(path2d, x, y, rule)`): the
1431    /// shape [`Self::fill_path`] drew under a tap. See
1432    /// [`Self::is_point_in_path`].
1433    pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
1434        crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
1435    }
1436
1437    /// Whether `point` is on the stroke of `path` with the transform, line
1438    /// width and cap recorded so far (TS: `cx.isPointInStroke(path2d, x,
1439    /// y)`). See [`Self::is_point_in_path`].
1440    pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
1441        crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
1442    }
1443
1444    /// Saves the state (styles, transform, clip).
1445    pub fn save(self) -> Self {
1446        self.op(CanvasOp::Save)
1447    }
1448
1449    /// Restores the state saved last.
1450    pub fn restore(self) -> Self {
1451        self.op(CanvasOp::Restore)
1452    }
1453
1454    /// Moves the origin.
1455    pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1456        let (x, y) = (self.num(x), self.num(y));
1457        self.op(CanvasOp::Translate(x, y))
1458    }
1459
1460    /// Scales the axes.
1461    pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1462        let (x, y) = (self.num(x), self.num(y));
1463        self.op(CanvasOp::Scale(x, y))
1464    }
1465
1466    /// Rotates the axes, clockwise (a [`Radians`], or an animated value of
1467    /// radians).
1468    pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
1469        let a = self.num(angle);
1470        self.op(CanvasOp::Rotate(a))
1471    }
1472
1473    /// Multiplies the transform by the matrix `[a c e; b d f]`
1474    /// (`transform`).
1475    pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1476        let m = m.map(|n| self.num(n));
1477        self.op(CanvasOp::Transform(m))
1478    }
1479
1480    /// Replaces the transform with the matrix `[a c e; b d f]`
1481    /// (`setTransform`).
1482    pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
1483        let m = m.map(|n| self.num(n));
1484        self.op(CanvasOp::SetTransform(m))
1485    }
1486
1487    /// Back to no transform (`resetTransform`).
1488    pub fn reset_transform(self) -> Self {
1489        self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
1490    }
1491
1492    /// Starts a new path.
1493    pub fn begin_path(self) -> Self {
1494        self.op(CanvasOp::BeginPath)
1495    }
1496
1497    /// Starts a subpath at (`x`, `y`).
1498    pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1499        let (x, y) = (self.num(x), self.num(y));
1500        self.path(PathOp::MoveTo(x, y))
1501    }
1502
1503    /// A straight line to (`x`, `y`).
1504    pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1505        let (x, y) = (self.num(x), self.num(y));
1506        self.path(PathOp::LineTo(x, y))
1507    }
1508
1509    /// A quadratic Bézier curve to `to` (`quadraticCurveTo`).
1510    pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
1511        let c = |v: Points| Num::Const(v.0);
1512        self.path(PathOp::QuadTo([
1513            c(control.x),
1514            c(control.y),
1515            c(to.x),
1516            c(to.y),
1517        ]))
1518    }
1519
1520    /// A cubic Bézier curve to `to` (`bezierCurveTo`).
1521    pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
1522        let c = |v: Points| Num::Const(v.0);
1523        self.path(PathOp::CubicTo([
1524            c(c1.x),
1525            c(c1.y),
1526            c(c2.x),
1527            c(c2.y),
1528            c(to.x),
1529            c(to.y),
1530        ]))
1531    }
1532
1533    /// A circular arc around (`x`, `y`); angles clockwise from the x axis
1534    /// ([`Radians`], or animated values of radians).
1535    pub fn arc(
1536        self,
1537        x: impl Into<CanvasArg>,
1538        y: impl Into<CanvasArg>,
1539        radius: impl Into<CanvasArg>,
1540        start: impl Into<CanvasArg>,
1541        end: impl Into<CanvasArg>,
1542    ) -> Self {
1543        self.arc_in(x, y, radius, start, end, false)
1544    }
1545
1546    /// [`Self::arc`] drawn counterclockwise.
1547    pub fn arc_counterclockwise(
1548        self,
1549        x: impl Into<CanvasArg>,
1550        y: impl Into<CanvasArg>,
1551        radius: impl Into<CanvasArg>,
1552        start: impl Into<CanvasArg>,
1553        end: impl Into<CanvasArg>,
1554    ) -> Self {
1555        self.arc_in(x, y, radius, start, end, true)
1556    }
1557
1558    fn arc_in(
1559        mut self,
1560        x: impl Into<CanvasArg>,
1561        y: impl Into<CanvasArg>,
1562        radius: impl Into<CanvasArg>,
1563        start: impl Into<CanvasArg>,
1564        end: impl Into<CanvasArg>,
1565        ccw: bool,
1566    ) -> Self {
1567        let (x, y, radius, start, end) = (
1568            self.num(x),
1569            self.num(y),
1570            self.num(radius),
1571            self.num(start),
1572            self.num(end),
1573        );
1574        self.path(PathOp::Arc {
1575            x,
1576            y,
1577            radius,
1578            start,
1579            end,
1580            ccw,
1581        })
1582    }
1583
1584    /// An arc of `radius` tangent to the lines to `p1` and on to `p2`
1585    /// (`arcTo`): a rounded corner.
1586    pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
1587        let c = |v: Points| Num::Const(v.0);
1588        self.path(PathOp::ArcTo([
1589            c(p1.x),
1590            c(p1.y),
1591            c(p2.x),
1592            c(p2.y),
1593            c(radius),
1594        ]))
1595    }
1596
1597    /// An elliptical arc around `center` with radii `radii` turned by
1598    /// `rotation`; angles clockwise (`counterclockwise` draws the other
1599    /// way).
1600    pub fn ellipse(
1601        self,
1602        center: Point<Points>,
1603        radii: Size<Points>,
1604        rotation: Radians,
1605        start: Radians,
1606        end: Radians,
1607        counterclockwise: bool,
1608    ) -> Self {
1609        let c = Num::Const;
1610        self.path(PathOp::Ellipse {
1611            geometry: [
1612                c(center.x.0),
1613                c(center.y.0),
1614                c(radii.width.0),
1615                c(radii.height.0),
1616                c(rotation.0),
1617            ],
1618            start: c(start.0),
1619            end: c(end.0),
1620            ccw: counterclockwise,
1621        })
1622    }
1623
1624    /// A rectangle subpath.
1625    pub fn rect(self, rect: Bounds<Points>) -> Self {
1626        self.path(PathOp::Rect(nums(rect)))
1627    }
1628
1629    /// A rectangle subpath with round corners (one radius for all).
1630    pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
1631        self.round_rect_corners(rect, Corners::all(radius))
1632    }
1633
1634    /// A rectangle subpath with round corners.
1635    pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
1636        let c = |v: Points| Num::Const(v.0);
1637        self.path(PathOp::RoundRect(
1638            nums(rect),
1639            [
1640                c(radii.top_left),
1641                c(radii.top_right),
1642                c(radii.bottom_right),
1643                c(radii.bottom_left),
1644            ],
1645        ))
1646    }
1647
1648    /// A straight line back to the subpath's start.
1649    pub fn close_path(self) -> Self {
1650        self.path(PathOp::Close)
1651    }
1652
1653    /// Fills the current path.
1654    pub fn fill(self) -> Self {
1655        self.fill_with(FillRule::NonZero)
1656    }
1657
1658    /// Fills the current path by `rule`.
1659    pub fn fill_with(self, rule: FillRule) -> Self {
1660        self.op(CanvasOp::Fill(None, rule))
1661    }
1662
1663    /// Fills `path` (TS: `fill(path2d)`; parse SVG data once with
1664    /// [`crate::canvas::svg_path`]).
1665    pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
1666        self.op(CanvasOp::Fill(Some(path.clone()), rule))
1667    }
1668
1669    /// Fills SVG path data (parsed now: [`Self::fill_path`] reuses a
1670    /// parsed path).
1671    pub fn fill_svg(self, data: &str) -> Self {
1672        self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
1673    }
1674
1675    /// Strokes the current path.
1676    pub fn stroke(self) -> Self {
1677        self.op(CanvasOp::Stroke(None))
1678    }
1679
1680    /// Strokes `path` (TS: `stroke(path2d)`).
1681    pub fn stroke_path(self, path: &Path) -> Self {
1682        self.op(CanvasOp::Stroke(Some(path.clone())))
1683    }
1684
1685    /// Strokes SVG path data (parsed now).
1686    pub fn stroke_svg(self, data: &str) -> Self {
1687        self.stroke_path(&crate::canvas::svg_path(data))
1688    }
1689
1690    /// Clips to the current path.
1691    pub fn clip(self) -> Self {
1692        self.clip_with(FillRule::NonZero)
1693    }
1694
1695    /// Clips to the current path by `rule`.
1696    pub fn clip_with(self, rule: FillRule) -> Self {
1697        self.op(CanvasOp::Clip(None, rule))
1698    }
1699
1700    /// Clips to `path` (TS: `clip(path2d)`).
1701    pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
1702        self.op(CanvasOp::Clip(Some(path.clone()), rule))
1703    }
1704
1705    /// Fills a rectangle (its numbers [`Points`], or animated values).
1706    pub fn fill_rect(
1707        mut self,
1708        x: impl Into<CanvasArg>,
1709        y: impl Into<CanvasArg>,
1710        w: impl Into<CanvasArg>,
1711        h: impl Into<CanvasArg>,
1712    ) -> Self {
1713        let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
1714        self.op(CanvasOp::FillRect([x, y, w, h]))
1715    }
1716
1717    /// Strokes a rectangle.
1718    pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
1719        self.op(CanvasOp::StrokeRect(nums(rect)))
1720    }
1721
1722    /// Makes a rectangle transparent.
1723    pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
1724        self.op(CanvasOp::ClearRect(nums(rect)))
1725    }
1726
1727    /// Fills with `color`.
1728    pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
1729        self.fill_style(color.into())
1730    }
1731
1732    /// Strokes with `color`.
1733    pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
1734        self.stroke_style(color.into())
1735    }
1736
1737    /// Fills with `paint`: a color, a gradient or an animated value of colors
1738    /// (`fillStyle`).
1739    pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
1740        let paint = self.paint(paint);
1741        self.op(CanvasOp::FillStyle(paint))
1742    }
1743
1744    /// Fills with the canvas view's `fill` style (CSS's, inherited from the
1745    /// views around it; `currentColor` is its text color), or `initial`
1746    /// where nothing sets one: shapes a component draws take the app's
1747    /// `fill-*` classes, and follow them and the appearance without being
1748    /// drawn again ([`Drawing::view_paints`]).
1749    pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
1750        self.view_paint(
1751            ViewPaint::Fill(initial),
1752            CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
1753        )
1754    }
1755
1756    /// Strokes with the canvas view's `stroke` style, or `initial` where
1757    /// nothing sets one ([`Self::fill_style_from_view`]).
1758    pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
1759        self.view_paint(
1760            ViewPaint::Stroke(initial),
1761            CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
1762        )
1763    }
1764
1765    /// Strokes as wide as the canvas view's `strokeWidth` style (1 where
1766    /// nothing sets one, CSS's initial value).
1767    pub fn line_width_from_view(self) -> Self {
1768        self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
1769    }
1770
1771    /// Dashes strokes as the canvas view's `strokeDasharray` style does
1772    /// (solid where nothing sets one).
1773    pub fn line_dash_from_view(self) -> Self {
1774        self.view_paint(
1775            ViewPaint::StrokeDasharray,
1776            CanvasOp::LineDash(Arc::from([])),
1777        )
1778    }
1779
1780    /// Fills the current path with the canvas view's background: its
1781    /// `backgroundColor` and its `backgroundImage` gradients (`bg-*`,
1782    /// `bg-linear-*` classes, the appearance's colors), positioned over
1783    /// `area` (this drawing's coordinates) as over a box of that size. The
1784    /// view then draws no background of its own: the background shows only
1785    /// where the path fills, as CSS's `clip-path` shows a box's
1786    /// ([`ViewPaint::Background`]). The canvas's state is kept around the
1787    /// fill.
1788    pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
1789        self.view_paint(
1790            ViewPaint::Background {
1791                area,
1792                rule: FillRule::NonZero,
1793            },
1794            CanvasOp::Fill(None, FillRule::NonZero),
1795        )
1796    }
1797
1798    fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
1799        let at = self.drawing.ops.len() as u32;
1800        self.drawing.view_paints.push((at, view));
1801        self.op(placeholder)
1802    }
1803
1804    /// Strokes with `paint` (`strokeStyle`).
1805    pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
1806        let paint = self.paint(paint);
1807        self.op(CanvasOp::StrokeStyle(paint))
1808    }
1809
1810    /// The stroke width.
1811    pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
1812        let w = self.num(width);
1813        self.op(CanvasOp::LineWidth(w))
1814    }
1815
1816    /// How strokes end.
1817    pub fn line_cap(self, cap: LineCap) -> Self {
1818        self.op(CanvasOp::LineCap(cap))
1819    }
1820
1821    /// How stroke segments join.
1822    pub fn line_join(self, join: LineJoin) -> Self {
1823        self.op(CanvasOp::LineJoin(join))
1824    }
1825
1826    /// How far mitered joins reach, in line widths (`miterLimit`; at least
1827    /// 1).
1828    pub fn miter_limit(self, limit: f32) -> Self {
1829        self.op(CanvasOp::MiterLimit(limit.max(1.0)))
1830    }
1831
1832    /// Dashes: lengths of dashes and gaps.
1833    pub fn line_dash(self, segments: &[Points]) -> Self {
1834        self.op(CanvasOp::LineDash(segments.into()))
1835    }
1836
1837    /// Where the dashes start along the line (`lineDashOffset`; an animated
1838    /// value marches them).
1839    pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
1840        let o = self.num(offset);
1841        self.op(CanvasOp::LineDashOffset(o))
1842    }
1843
1844    /// The opacity of what is drawn next.
1845    pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
1846        let a = self.num(alpha);
1847        self.op(CanvasOp::GlobalAlpha(a))
1848    }
1849
1850    /// How what is drawn next combines with the canvas.
1851    pub fn composite(self, composite: Composite) -> Self {
1852        self.op(CanvasOp::Composite(composite))
1853    }
1854
1855    /// Shadows of what is drawn next.
1856    pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
1857        self.op(CanvasOp::ShadowColor(Color::from(color.into())))
1858            .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
1859            .op(CanvasOp::ShadowOffset(offset))
1860    }
1861
1862    /// The font (CSS `font` shorthand: `"600 14px Inter"`); an invalid one
1863    /// keeps the previous font, as in HTML.
1864    pub fn font(self, font: &str) -> Self {
1865        match CanvasFont::parse(font) {
1866            Some(font) => self.op(CanvasOp::Font(font)),
1867            None => self,
1868        }
1869    }
1870
1871    /// The number forms of text (TS: `fontVariantNumeric`): with
1872    /// [`crate::style::FontVariant::TABULAR_NUMS`] figures have equal widths, so changing
1873    /// values do not jitter; `FontVariant::default()` keeps the font's.
1874    pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
1875        self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
1876            numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
1877        )))
1878    }
1879
1880    /// Where text sits relative to its x.
1881    pub fn text_align(self, align: CanvasTextAlign) -> Self {
1882        self.op(CanvasOp::TextAlign(align))
1883    }
1884
1885    /// Where text sits relative to its y.
1886    pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
1887        self.op(CanvasOp::TextBaseline(baseline))
1888    }
1889
1890    /// Fills `text` at (`x`, `y`).
1891    pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1892        self.text(text, x, y, None, false)
1893    }
1894
1895    /// Fills `text` at (`x`, `y`), narrowed to fit `max_width`.
1896    pub fn fill_text_max_width(
1897        self,
1898        text: &str,
1899        x: impl Into<CanvasArg>,
1900        y: impl Into<CanvasArg>,
1901        max_width: Points,
1902    ) -> Self {
1903        self.text(text, x, y, Some(max_width), false)
1904    }
1905
1906    /// Strokes the outline of `text` at (`x`, `y`).
1907    pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
1908        self.text(text, x, y, None, true)
1909    }
1910
1911    /// Strokes the outline of `text` at (`x`, `y`), narrowed to fit
1912    /// `max_width`.
1913    pub fn stroke_text_max_width(
1914        self,
1915        text: &str,
1916        x: impl Into<CanvasArg>,
1917        y: impl Into<CanvasArg>,
1918        max_width: Points,
1919    ) -> Self {
1920        self.text(text, x, y, Some(max_width), true)
1921    }
1922
1923    fn text(
1924        mut self,
1925        text: &str,
1926        x: impl Into<CanvasArg>,
1927        y: impl Into<CanvasArg>,
1928        max_width: Option<Points>,
1929        stroke: bool,
1930    ) -> Self {
1931        let (text, x, y) = (text.into(), self.num(x), self.num(y));
1932        self.op(if stroke {
1933            CanvasOp::StrokeText {
1934                text,
1935                x,
1936                y,
1937                max_width,
1938            }
1939        } else {
1940            CanvasOp::FillText {
1941                text,
1942                x,
1943                y,
1944                max_width,
1945            }
1946        })
1947    }
1948
1949    /// Draws the image at `uri` (a URL or `asset:/path`) into `dest`.
1950    pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
1951        self.draw_image_part(uri, None, dest)
1952    }
1953
1954    /// Draws the part `source` of the image at `uri` (in the image's
1955    /// pixels; `None`: all of it) into `dest`.
1956    pub fn draw_image_part(
1957        self,
1958        uri: &str,
1959        source: Option<Bounds<ScaledPixels>>,
1960        dest: Bounds<Points>,
1961    ) -> Self {
1962        self.op(CanvasOp::DrawImage {
1963            image: CanvasImage { uri: uri.into() },
1964            source,
1965            dest: nums(dest),
1966        })
1967    }
1968}
1969
1970/// `[x, y, w, h]` of `rect`, as a recorded rectangle's numbers.
1971fn nums(rect: Bounds<Points>) -> [Num; 4] {
1972    [
1973        rect.origin.x,
1974        rect.origin.y,
1975        rect.size.width,
1976        rect.size.height,
1977    ]
1978    .map(|v| Num::Const(v.0))
1979}
1980
1981impl From<Drawing> for Painter {
1982    fn from(drawing: Drawing) -> Self {
1983        Self {
1984            drawing,
1985            nodes: Vec::new(),
1986        }
1987    }
1988}
1989
1990crate::static_reactive!(ScreenAnimation: ScreenAnimation);