Skip to main content

nsh_core/element/
builder.rs

1//! The elements a view is made of ([`view`], [`text`], [`image`], other
2//! components, slots and children).
3
4use std::{any::Any, fmt, marker::PhantomData, rc::Rc, sync::Arc};
5
6use super::{
7    Component, ComponentSpec, Event, IntoReactive, JsValue, PropError, Reactive, SharedString,
8    component::AnyInstance,
9    events::{self, GestureEvent, PanEvent},
10    style::{StyleRefinement, Styled, Variant},
11};
12use crate::{
13    AccessibilityProp, AccessibilityRole, AccessibilityState, AccessibilityValue, Bounds,
14    ContextMenuEvent, EdgeInsets, EventKind, EventPayload, HoverEvent, Hsla, ImageSource,
15    ListContentStyle, NativeProp, NodeId, PointerEvents, Points, Prop, Size, Tag, TouchEvent,
16    geometry::Radians, style::Color,
17};
18
19/// A handler of `E` on an element: a closure (`move |e: &E| ..`) that
20/// writes the signals it captured. It runs under the owner current when it
21/// was made (the component, region or row whose view made it), so what it
22/// makes (signals, animated values, element refs, tasks) is that owner's
23/// and goes with it; once that owner is disposed it no longer runs.
24pub struct Listener<E: ?Sized> {
25    f: Rc<dyn Fn(&E)>,
26    owner: super::Owner,
27}
28
29impl<E: ?Sized + 'static> Listener<E> {
30    /// A listener that does nothing (the element still listens).
31    pub(crate) fn noop() -> Self {
32        Self::new(Rc::new(|_| {}))
33    }
34
35    fn new(f: Rc<dyn Fn(&E)>) -> Self {
36        Self {
37            f,
38            owner: super::Owner::current_or_detached(),
39        }
40    }
41
42    /// Calls it with `event`, under its owner; not once that owner is
43    /// disposed: the view it was made for is gone.
44    pub(crate) fn call(&self, event: &E) {
45        if self.owner == super::Owner::detached() {
46            (self.f)(event);
47        } else if self.owner.is_live() {
48            self.owner.scope(|| (self.f)(event));
49        }
50    }
51
52    /// A listener of `F` that runs `f` with this one's closure, under its
53    /// owner.
54    pub(crate) fn wrap<F: ?Sized>(self, f: impl Fn(&dyn Fn(&E), &F) + 'static) -> Listener<F> {
55        let inner = self.f;
56        Listener {
57            f: Rc::new(move |event: &F| f(&*inner, event)),
58            owner: self.owner,
59        }
60    }
61}
62
63impl<E: 'static> Listener<E> {
64    /// This listener for events of another type, turned into `E` by `f`.
65    pub fn map<F: ?Sized + 'static>(self, f: impl Fn(&F) -> E + 'static) -> Listener<F> {
66        self.wrap(move |inner, event: &F| inner(&f(event)))
67    }
68}
69
70/// A closure as a listener.
71impl<E: ?Sized + 'static, F: Fn(&E) + 'static> From<F> for Listener<E> {
72    fn from(f: F) -> Self {
73        Self::new(Rc::new(f))
74    }
75}
76
77/// What a listener method takes (`on_press`, `on_change`,
78/// `on_event`, ...): a closure of the event, `move |text: &str| ..`; for an
79/// event without data also one without arguments, `move || ..` (or
80/// `move |_: &()| ..`); or a [`Listener`]. `M` tells them apart: it is
81/// inferred, never written. (One conversion could not take both closures:
82/// a type may implement `Fn()` and `Fn(&())`.)
83#[diagnostic::on_unimplemented(
84    message = "`{Self}` is not a listener of `{E}`",
85    label = "not a listener of `{E}`",
86    note = "a listener is a closure `move |event: &{E}| ..` (`move || ..` for an event without data) or a `Listener<{E}>`"
87)]
88pub trait IntoListener<E: ?Sized, M> {
89    /// As the listener.
90    fn into_listener(self) -> Listener<E>;
91}
92
93/// How a closure of the event is a listener ([`IntoListener`]).
94#[doc(hidden)]
95pub struct OfEvent(());
96
97/// How a closure without arguments is a listener of an event without data
98/// ([`IntoListener`]).
99#[doc(hidden)]
100pub struct WithoutEvent(());
101
102impl<E: ?Sized> IntoListener<E, ()> for Listener<E> {
103    fn into_listener(self) -> Listener<E> {
104        self
105    }
106}
107
108impl<E: ?Sized + 'static, F: Fn(&E) + 'static> IntoListener<E, OfEvent> for F {
109    fn into_listener(self) -> Listener<E> {
110        Listener::new(Rc::new(self))
111    }
112}
113
114impl<F: Fn() + 'static> IntoListener<(), WithoutEvent> for F {
115    fn into_listener(self) -> Listener<()> {
116        Listener::new(Rc::new(move |_: &()| self()))
117    }
118}
119
120impl<E: ?Sized> Clone for Listener<E> {
121    fn clone(&self) -> Self {
122        Self {
123            f: self.f.clone(),
124            owner: self.owner,
125        }
126    }
127}
128
129/// An event a component emitted, with its type erased: what JS hears of
130/// it and the event, for Rust listeners.
131pub(crate) trait AnyEvent: super::EventToJs {
132    fn as_any(&self) -> &dyn Any;
133}
134
135impl<E: Event> super::EventToJs for E {
136    fn name(&self) -> &'static str {
137        Event::name(self)
138    }
139
140    fn data_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
141        Event::data_js(self, host)
142    }
143
144    fn spread(&self) -> bool {
145        Event::spread(self)
146    }
147}
148
149impl<E: Event> AnyEvent for E {
150    fn as_any(&self) -> &dyn Any {
151        self
152    }
153}
154
155/// The props of an element the core diffs field by field (opaque).
156#[doc(hidden)]
157#[derive(Debug, Clone, Default, PartialEq)]
158pub struct Attrs {
159    pub(crate) disabled: bool,
160    pub(crate) accessible: Option<bool>,
161    pub(crate) label: Option<SharedString>,
162    pub(crate) hint: Option<SharedString>,
163    pub(crate) role: AccessibilityRole,
164    pub(crate) state: AccessibilityState,
165    pub(crate) value: Option<AccessibilityValue>,
166    pub(crate) pointer_events: PointerEvents,
167    pub(crate) number_of_lines: u32,
168    pub(crate) src: Option<super::ImageSrc>,
169    pub(crate) inset_padding: Option<EdgeInsets>,
170    pub(crate) inset_margin: Option<EdgeInsets>,
171    /// An inline style (a `Style` prop), over the styles.
172    pub(crate) inline: Option<Arc<crate::StylePatch>>,
173    /// The props of host elements (inputs, scroll views, ...), one per
174    /// property ([`super::host`]).
175    pub(crate) props: Vec<Prop>,
176    /// A canvas's drawing.
177    pub(crate) drawing: Option<Arc<crate::canvas::Drawing>>,
178    /// What the ref the view put on the element names (not a prop): held
179    /// while the element is, however long the ref's owner lives.
180    pub(crate) element_ref: Option<super::element_ref::RefTarget>,
181    /// Style properties bound to native animation nodes (held while
182    /// bound).
183    pub(crate) animated: Vec<(crate::StyleDecl, super::LiveNode)>,
184    /// Animated nodes host props read (drags, scroll offsets), held.
185    pub(crate) bound: Vec<super::LiveNode>,
186    /// Tailwind classes the app gave through a prop (a component's part),
187    /// after the element's own styles.
188    pub(crate) class: Option<SharedString>,
189    /// The view is a selectable view ([`crate::selection`]).
190    pub(crate) selectable_view: bool,
191    /// The states it shows as its control's part
192    /// ([`Interactive::project_checked`]).
193    pub(crate) projected_states: u8,
194    /// Where a JS renderer's content goes (the element is its
195    /// placeholder: [`super::Renderer::render`]).
196    pub(crate) render: Option<super::renderer::RenderAt>,
197}
198
199impl Attrs {
200    /// The props of the fields that differ from `old`, in a fixed order.
201    pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
202        use AccessibilityProp as A;
203        if self.disabled != old.disabled {
204            out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
205        }
206        if self.accessible != old.accessible {
207            out.push(Prop::Accessibility(A::Accessible(self.accessible)));
208        }
209        if self.label != old.label {
210            out.push(Prop::Accessibility(A::Label(
211                self.label.as_ref().map(SharedString::to_arc),
212            )));
213        }
214        if self.hint != old.hint {
215            out.push(Prop::Accessibility(A::Hint(
216                self.hint.as_ref().map(SharedString::to_arc),
217            )));
218        }
219        if self.role != old.role {
220            out.push(Prop::Accessibility(A::Role(self.role)));
221        }
222        if self.state != old.state {
223            out.push(Prop::Accessibility(A::State(self.state)));
224        }
225        if self.value != old.value {
226            out.push(Prop::Accessibility(A::Value(self.value.clone())));
227        }
228        if self.pointer_events != old.pointer_events {
229            out.push(Prop::PointerEvents(self.pointer_events));
230        }
231        if self.number_of_lines != old.number_of_lines {
232            out.push(Prop::NumberOfLines(self.number_of_lines));
233        }
234        if self.src != old.src {
235            out.push(Prop::Source(self.src.as_ref().map(|src| ImageSource {
236                uri: src.uri.to_arc(),
237                size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
238                scales: src.scales,
239                data: None,
240            })));
241        }
242        if self.inset_padding != old.inset_padding {
243            out.push(Prop::InsetPadding(self.inset_padding.unwrap_or_default()));
244        }
245        if self.inset_margin != old.inset_margin {
246            out.push(Prop::InsetMargin(self.inset_margin.unwrap_or_default()));
247        }
248        if self.selectable_view != old.selectable_view {
249            out.push(Prop::SelectableView(self.selectable_view));
250        }
251        if self.projected_states != old.projected_states {
252            out.push(Prop::ProjectedStates(self.projected_states));
253        }
254        // Host props: the ones no longer set go back to their defaults,
255        // then the new and changed ones.
256        for prop in &old.props {
257            if !self.props.iter().any(|p| super::host::same_kind(p, prop))
258                && let Some(reset) = super::host::reset(prop)
259            {
260                out.push(reset);
261            }
262        }
263        for prop in &self.props {
264            if !old.props.contains(prop) {
265                out.push(prop.clone());
266            }
267        }
268    }
269}
270
271/// A nested component's props, with their type erased.
272pub(crate) trait AnyProps {
273    fn as_any(&self) -> &dyn Any;
274    fn as_any_mut(&mut self) -> &mut dyn Any;
275    fn clone_box(&self) -> Box<dyn AnyProps>;
276}
277
278impl<P: Clone + 'static> AnyProps for P {
279    fn as_any(&self) -> &dyn Any {
280        self
281    }
282
283    fn as_any_mut(&mut self) -> &mut dyn Any {
284        self
285    }
286
287    fn clone_box(&self) -> Box<dyn AnyProps> {
288        Box::new(self.clone())
289    }
290}
291
292/// A nested component of a view.
293pub(crate) struct ComponentEl {
294    pub(crate) name: &'static str,
295    /// Makes an instance: a component a view makes need not be registered
296    /// (the registry is what JS can make by name).
297    pub(crate) make: fn() -> Box<dyn AnyInstance>,
298    /// Its spec (made once per type and kept by the core).
299    pub(crate) spec: fn() -> ComponentSpec,
300    pub(crate) props: Box<dyn AnyProps>,
301    /// The handlers of its events in the view that has it, in order.
302    pub(crate) on_event: Vec<Listener<dyn Any>>,
303}
304
305impl Clone for ComponentEl {
306    fn clone(&self) -> Self {
307        Self {
308            name: self.name,
309            make: self.make,
310            spec: self.spec,
311            props: self.props.clone_box(),
312            on_event: self.on_event.clone(),
313        }
314    }
315}
316
317/// Places one piece of the app's content: a JSX child, or a list row.
318pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
319
320/// Where a JSX child or a list row is among its siblings (what a TS row
321/// knows from its index and the data's length). `Copy`: a handle of two
322/// signals, so a binding that reads it (`move || at.is_last()`) runs again
323/// when a list cell shows another row or the rows come and go, and the
324/// cell's content stays.
325#[derive(Clone, Copy)]
326pub struct Position {
327    index: super::reactive::Node,
328    count: super::reactive::Node,
329}
330
331impl Position {
332    /// The position read from signals (or memos) of the index and the
333    /// count.
334    pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
335        Self { index, count }
336    }
337
338    /// A position that does not change (signals of the current owner).
339    pub(crate) fn fixed(index: usize, count: usize) -> Self {
340        Self::of(super::signal(index).node(), super::signal(count).node())
341    }
342
343    /// Its index, subscribing the running computation.
344    #[track_caller]
345    pub fn index(&self) -> usize {
346        self.index.with("a position", |i: &usize| *i)
347    }
348
349    /// How many there are, subscribing the running computation.
350    #[track_caller]
351    pub fn count(&self) -> usize {
352        self.count.with("a position", |n: &usize| *n)
353    }
354
355    /// The first one.
356    #[track_caller]
357    pub fn is_first(&self) -> bool {
358        self.index() == 0
359    }
360
361    /// The last one.
362    #[track_caller]
363    pub fn is_last(&self) -> bool {
364        self.index() + 1 == self.count()
365    }
366}
367
368impl fmt::Debug for Position {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        let (index, count) = super::untracked(|| (self.index(), self.count()));
371        write!(f, "Position({index} of {count})")
372    }
373}
374
375/// How a list is laid out (each set field is sent to the list); set with
376/// [`super::ListLayout`]'s methods.
377#[doc(hidden)]
378#[derive(Debug, Clone, Copy, Default, PartialEq)]
379pub struct ListConfig {
380    pub(crate) estimated: Option<f32>,
381    pub(crate) columns: Option<u32>,
382    pub(crate) horizontal: Option<bool>,
383    pub(crate) inverted: Option<bool>,
384    pub(crate) scrollbar_visible: Option<bool>,
385    pub(crate) content: Option<ListContentStyle>,
386    pub(crate) follow_end: Option<f32>,
387    pub(crate) viewport: Option<crate::ListViewport>,
388}
389
390impl ListConfig {
391    /// The props of the fields that differ from `old`.
392    pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
393        if self.estimated != old.estimated {
394            out.push(Prop::EstimatedItemSize(Points(
395                self.estimated.unwrap_or(50.0),
396            )));
397        }
398        if self.columns != old.columns {
399            out.push(Prop::Columns(self.columns.unwrap_or(1)));
400        }
401        if self.horizontal != old.horizontal {
402            out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
403        }
404        if self.inverted != old.inverted {
405            out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
406        }
407        if self.scrollbar_visible != old.scrollbar_visible {
408            out.push(Prop::Scrollbar(self.scrollbar_visible.unwrap_or(true)));
409        }
410        if self.content != old.content {
411            out.push(Prop::ListContent(self.content.unwrap_or_default()));
412        }
413        if self.follow_end != old.follow_end {
414            out.push(Prop::FollowEnd(self.follow_end.map(Points)));
415        }
416        if self.viewport != old.viewport {
417            out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
418        }
419    }
420}
421
422/// A list slot as a view places it.
423#[derive(Clone)]
424pub(crate) struct ListEl {
425    pub(crate) name: &'static str,
426    pub(crate) config: ListConfig,
427    pub(crate) row: PlaceFn,
428}
429
430/// What an element is beyond its tag.
431#[derive(Clone)]
432pub(crate) enum ElKind {
433    Plain,
434    /// Where slot `name` goes (a view placing it).
435    Slot(&'static str),
436    /// What a view fills a nested component's slot `name` with: its
437    /// children, placed as they are where the nested view places the slot.
438    Fill(&'static str),
439    /// Where the nested view places what a view filled slot `name` with
440    /// (no node of its own).
441    Filled(&'static str),
442    /// Where the JSX children go (a list row's content, in a row).
443    Children,
444    /// One JSX child (in [`ParentElement::children_each`]).
445    JsChild(NodeId),
446    /// Every JSX child, each placed by the function.
447    EachChild(PlaceFn),
448    /// The glue's list of an [`Items`] prop.
449    List(Box<ListEl>),
450    /// A list of the component's own rows ([`super::virtual_list`]).
451    VirtualList(Box<super::virtual_list::VirtualListEl>),
452    /// A piece of a text's content among its spans (a raw text node, as
453    /// JS's strings in a `<text>`).
454    Raw,
455    Component(ComponentEl),
456    /// Elements that change ([`super::dynamic`], [`super::If`],
457    /// [`super::Each`]): a region of its parent's children, reconciled on
458    /// its own.
459    Region(super::flow::Region),
460    /// In a region: the element of this key stays as it is (an `Each` row
461    /// that was there before).
462    Keep,
463}
464
465/// An element as the core expands it (opaque).
466#[doc(hidden)]
467#[derive(Clone)]
468pub struct ElNode {
469    pub(crate) tag: Tag,
470    pub(crate) key: Option<SharedString>,
471    /// A text's content.
472    pub(crate) text: Option<SharedString>,
473    pub(crate) attrs: Attrs,
474    pub(crate) style: StyleRefinement,
475    pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
476    /// Its part in the touch responder's negotiation.
477    pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
478    pub(crate) children: Vec<ElNode>,
479    pub(crate) kind: ElKind,
480    /// A text's content when it is bound (read in a binding).
481    pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
482    /// Bound props: each sets the fields it binds on the static ones.
483    pub(crate) bound_attrs: Vec<BoundAttrs>,
484    /// A list's bound layout: each sets the fields it binds.
485    pub(crate) bound_list: Vec<BoundListConfig>,
486}
487
488/// A bound part of a list's layout.
489#[doc(hidden)]
490pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
491
492crate::static_reactive!(AccessibilityState: AccessibilityState);
493crate::static_reactive!(EdgeInsets: EdgeInsets);
494crate::static_reactive!(Style: Style);
495crate::static_reactive!(PointerEvents: PointerEvents);
496
497/// A bound part of an element's props.
498pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
499
500impl ElNode {
501    /// Applies `value` to the props with `apply`: now when it is static,
502    /// else as a bound part.
503    pub(crate) fn bind_attr<T: 'static>(
504        &mut self,
505        value: impl IntoReactive<T>,
506        apply: impl Fn(&mut Attrs, T) + 'static,
507    ) {
508        match value.into_reactive() {
509            Reactive::Static(v) => apply(&mut self.attrs, v),
510            Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
511        }
512    }
513
514    /// Whether it has bound parts (text, props or styles).
515    pub(crate) fn is_bound(&self) -> bool {
516        self.bound_text.is_some()
517            || !self.bound_attrs.is_empty()
518            || self.style.is_bound()
519            || !self.bound_list.is_empty()
520    }
521
522    /// The props now: the static ones with the bound parts applied (read in
523    /// the running computation, which subscribes to them).
524    pub(crate) fn resolved_attrs(&self) -> Attrs {
525        let mut attrs = self.attrs.clone();
526        for part in &self.bound_attrs {
527            part(&mut attrs);
528        }
529        attrs
530    }
531
532    /// Turns the bound parts into static ones, read once, untracked: how a
533    /// nested component's element and a slot's node take them.
534    pub(crate) fn resolve_once(&mut self) {
535        if !self.is_bound() {
536            return;
537        }
538        super::untracked(|| {
539            if let Some(text) = self.bound_text.take() {
540                self.text = Some(text());
541            }
542            if !self.bound_attrs.is_empty() {
543                self.attrs = self.resolved_attrs();
544                self.bound_attrs.clear();
545            }
546            if self.style.is_bound() {
547                self.style = self.style.resolved();
548            }
549            let parts = std::mem::take(&mut self.bound_list);
550            if let Some(config) = self.list_config() {
551                for part in &parts {
552                    part(config);
553                }
554            }
555        });
556    }
557
558    /// A list's layout (of a list element or a virtual list).
559    pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
560        match &mut self.kind {
561            ElKind::List(list) => Some(&mut list.config),
562            ElKind::VirtualList(list) => Some(&mut list.config),
563            _ => None,
564        }
565    }
566
567    /// What a component that is not registered renders.
568    pub(crate) fn empty_view() -> Self {
569        Self::new(Tag::View)
570    }
571
572    pub(crate) fn new(tag: Tag) -> Self {
573        Self {
574            tag,
575            key: None,
576            text: None,
577            attrs: Attrs::default(),
578            style: StyleRefinement::default(),
579            handlers: Vec::new(),
580            responder: None,
581            children: Vec::new(),
582            kind: ElKind::Plain,
583            bound_text: None,
584            bound_attrs: Vec::new(),
585            bound_list: Vec::new(),
586        }
587    }
588}
589
590/// Any element, its type erased.
591pub struct AnyElement(pub(crate) ElNode);
592
593/// What can be a child: elements, and strings (as texts).
594pub trait IntoElement {
595    /// As an element.
596    fn into_element(self) -> AnyElement;
597}
598
599impl IntoElement for AnyElement {
600    fn into_element(self) -> AnyElement {
601        self
602    }
603}
604
605impl IntoElement for SharedString {
606    fn into_element(self) -> AnyElement {
607        text(self).into_element()
608    }
609}
610
611impl IntoElement for &'static str {
612    fn into_element(self) -> AnyElement {
613        text(self).into_element()
614    }
615}
616
617impl IntoElement for String {
618    fn into_element(self) -> AnyElement {
619        text(self).into_element()
620    }
621}
622
623/// What `.child(..)` takes ([`ParentElement::child`]): an element, or
624/// what holds elements (an `Option`, a `Vec`, an array or an iterator of
625/// them: `rows.iter().map(|r| row(r))`). `M` tells the two apart: it is
626/// inferred, never written. (One blanket conversion could not take both: a
627/// type may be an element and hold elements.)
628#[diagnostic::on_unimplemented(
629    message = "`{Self}` is not an element",
630    label = "not an element",
631    note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
632)]
633pub trait IntoChild<M> {
634    /// Adds what it is to `out`.
635    #[doc(hidden)]
636    fn __push_into(self, out: &mut Vec<ElNode>);
637}
638
639/// How an element is a child ([`IntoChild`]).
640#[doc(hidden)]
641pub struct OneChild(());
642
643/// How what holds elements is children ([`IntoChild`]).
644#[doc(hidden)]
645pub struct ManyChildren(());
646
647impl<T: IntoElement> IntoChild<OneChild> for T {
648    fn __push_into(self, out: &mut Vec<ElNode>) {
649        out.push(self.into_element().0);
650    }
651}
652
653impl<I: IntoIterator> IntoChild<ManyChildren> for I
654where
655    I::Item: IntoElement,
656{
657    fn __push_into(self, out: &mut Vec<ElNode>) {
658        out.extend(self.into_iter().map(|c| c.into_element().0));
659    }
660}
661
662/// Conditional building, as GPUI's `FluentBuilder` (`gpui::prelude`): decided
663/// once, as the element is made. What must follow a signal is a region
664/// ([`super::when`], [`super::dynamic`]).
665pub trait FluentBuilder: Sized {
666    /// `then(self)` when `condition` holds.
667    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
668        if condition { then(self) } else { self }
669    }
670
671    /// `then(self, value)` when `option` has one.
672    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
673        match option {
674            Some(v) => then(self, v),
675            None => self,
676        }
677    }
678
679    /// `f(self)`.
680    fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
681        f(self)
682    }
683}
684
685impl<T: Element> FluentBuilder for T {}
686
687/// An element: what every element can do. Its other abilities are the
688/// traits it implements ([`Styled`], [`Accessible`], [`Interactive`],
689/// [`ParentElement`]).
690pub trait Element: IntoElement + Sized {
691    #[doc(hidden)]
692    fn node(&mut self) -> &mut ElNode;
693
694    /// Identifies the element among its siblings when they are made again
695    /// (a region's, a list cell's row; where their order changes).
696    fn key(mut self, key: impl Into<SharedString>) -> Self {
697        self.node().key = Some(key.into());
698        self
699    }
700
701    /// Binds `opacity` to an animated value (it moves natively).
702    fn bind_opacity(self, value: &impl super::Animated) -> Self {
703        self.bind(crate::animation::AnimationProp::Opacity, value)
704    }
705
706    /// Binds the background color to a node of colors
707    /// ([`super::AnimatedNode::interpolate_colors`]).
708    fn bind_background(self, value: &impl super::Animated) -> Self {
709        self.bind(crate::animation::AnimationProp::BackgroundColor, value)
710    }
711
712    /// Binds the color of every border side to a node of colors.
713    fn bind_border_color(self, value: &impl super::Animated) -> Self {
714        self.bind(crate::animation::AnimationProp::BorderColor, value)
715    }
716
717    /// Binds a text's color (the whole text) to a node of colors.
718    fn bind_color(self, value: &impl super::Animated) -> Self {
719        self.bind(crate::animation::AnimationProp::Color, value)
720    }
721
722    /// Binds the shadow's color to a node of colors (TS: `shadowColor`).
723    fn bind_shadow_color(self, value: &impl super::Animated) -> Self {
724        self.bind(crate::animation::AnimationProp::ShadowColor, value)
725    }
726
727    /// Binds the shadow's opacity, 0..1 (TS: `shadowOpacity`).
728    fn bind_shadow_opacity(self, value: &impl super::Animated) -> Self {
729        self.bind(crate::animation::AnimationProp::ShadowOpacity, value)
730    }
731
732    /// Binds the shadow's blur radius, in points (TS: `shadowRadius`).
733    fn bind_shadow_radius(self, value: &impl super::Animated) -> Self {
734        self.bind(crate::animation::AnimationProp::ShadowRadius, value)
735    }
736
737    /// Binds `prop` (anything but a transform step or a canvas argument)
738    /// to an animated value (nothing once the value's owner is gone).
739    fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
740        if let Some(node) = value.animated_node().live() {
741            let decl = crate::StyleDecl::Animated(prop, node.id());
742            self.node().attrs.animated.push((decl, node));
743        }
744        self
745    }
746
747    /// A sticky view ([`super::Styled::sticky`]) sticks this animated value
748    /// from the top of the scroll view's viewport, following it (below a
749    /// header that moves: `header.add(8.0)`; TS: `top` set to an animated
750    /// value).
751    fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
752        self.bind(crate::animation::AnimationProp::StickyTop, value)
753    }
754
755    /// The same as [`Self::bind_sticky_top`] in a horizontal scroll view.
756    fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
757        self.bind(crate::animation::AnimationProp::StickyLeft, value)
758    }
759
760    /// Appends a transform step driven by an animated value, after the styles'
761    /// transforms.
762    fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
763        if let Some(node) = value.animated_node().live() {
764            let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
765            self.node().attrs.animated.push((decl, node));
766        }
767        self
768    }
769
770    /// Binds a motion's channels: its opacity, and its transform after the
771    /// styles' transforms (translations, then rotations, then the scales,
772    /// `scale` folded into `scale_x` and `scale_y`: 7 steps of a view's 8).
773    fn bind_motion(self, motion: &super::Motion) -> Self {
774        use crate::animation::MotionChannel::*;
775        let mut this = self.bind_opacity(&motion.value(Opacity));
776        for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
777            if let Some(kind) = channel.transform() {
778                this = this.bind_transform(kind, &motion.value(channel));
779            }
780        }
781        let scale = motion.value(Scale);
782        this.bind_transform(
783            crate::TransformKind::ScaleX,
784            &scale.mul(&motion.value(ScaleX)),
785        )
786        .bind_transform(
787            crate::TransformKind::ScaleY,
788            &scale.mul(&motion.value(ScaleY)),
789        )
790    }
791
792    /// Moves it right by an animated value (points).
793    fn bind_translate_x(self, value: &impl super::Animated) -> Self {
794        self.bind_transform(crate::TransformKind::TranslateX, value)
795    }
796
797    /// Moves it down by an animated value (points).
798    fn bind_translate_y(self, value: &impl super::Animated) -> Self {
799        self.bind_transform(crate::TransformKind::TranslateY, value)
800    }
801
802    /// Scales it by an animated value.
803    fn bind_scale(self, value: &impl super::Animated) -> Self {
804        self.bind_transform(crate::TransformKind::Scale, value)
805    }
806
807    /// Rotates it by an animated value (degrees, clockwise).
808    fn bind_rotate(self, value: &impl super::Animated) -> Self {
809        self.bind_transform(crate::TransformKind::Rotate, value)
810    }
811
812    /// Puts `handle` on this element: its commands (`focus`, `scroll_to`)
813    /// go here (nothing once the ref's owner is gone).
814    fn element_ref(mut self, handle: &super::ElementRef) -> Self {
815        self.node().attrs.element_ref = handle.target();
816        self
817    }
818
819    /// Padding added to the element's own (from styles): insets of system
820    /// UI, a keyboard.
821    fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
822        self.node()
823            .bind_attr(insets, |a, insets| a.inset_padding = Some(insets));
824        self
825    }
826
827    /// Margin added to the element's own.
828    fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
829        self.node()
830            .bind_attr(insets, |a, insets| a.inset_margin = Some(insets));
831        self
832    }
833
834    /// An inline style the app passed (a prop of type `Style`, React
835    /// Native's names), over the element's styles.
836    fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
837        Style::apply(self.node(), style, Variant::default(), |a, patch| {
838            a.inline = patch
839        });
840        self
841    }
842
843    /// Makes the texts in the view select together, as a browser page's
844    /// do (TSX `<View selectable>`): a selection runs from text to text,
845    /// across views and `TextView`s; texts that are not selectable stay
846    /// out of it ([`crate::selection`]).
847    fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
848        self.node()
849            .bind_attr(area, |a, area| a.selectable_view = area);
850        self
851    }
852
853    /// Tailwind classes the app passed (a prop naming the classes of one
854    /// of the component's parts: `classes={{ heading: "text-2xl" }}`),
855    /// after the element's own styles, as the app's `class` on a
856    /// component's root is: at equal rank they win.
857    fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
858        self.node().bind_attr(class, |a, class| a.class = class);
859        self
860    }
861}
862
863/// An inline style: a prop typed `StyleProp<ViewStyle>` in TypeScript (an
864/// object, an array of them, or nothing), decoded when JS sets it as a host
865/// element's `style` is (transforms, shadow offsets, native animated
866/// values included), and applied with [`Element::inline_style`]. Rust
867/// makes one with the typed styles (`From<StyleRefinement>`: what a style
868/// prop's setter does with its closure, `.selected_style(|s| s.bg(..))`),
869/// theme colors following the appearance and bound parts their signals,
870/// as in `.active(|s| ..)`; or from declarations ([`Style::from_decls`],
871/// [`Style::with`]).
872/// Its native animated values are node ids, valid while the style is the
873/// prop's current value (JS keeps the values alive with it, as a host
874/// element's `style` does); a component that keeps an older `Style`
875/// beyond that may hold ids of values JS has collected.
876#[derive(Debug, Clone, Default, PartialEq)]
877pub struct Style(
878    pub(crate) Option<Arc<crate::StylePatch>>,
879    /// The typed styles it was made of (Rust's), applied as the element's
880    /// own are.
881    pub(crate) StyleRefinement,
882);
883
884impl Style {
885    /// A style of `decls`, applied in order; one that does not apply (a
886    /// value of the wrong type or format) is left out and logged, as on a
887    /// host element.
888    pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
889        let mut style = crate::Style::default();
890        let mut patch = crate::StylePatch::default();
891        for decl in decls {
892            let key = match &decl {
893                crate::StyleDecl::Set(key, _) => Some(*key),
894                _ => None,
895            };
896            if patch.push(&mut style, decl).is_err()
897                && let Some(key) = key
898            {
899                log::warn!("invalid value for style `{}`", key.name());
900            }
901        }
902        Self(Some(Arc::new(patch)), StyleRefinement::default())
903    }
904
905    /// This style with property `key` set to `value` after the rest
906    /// (`Style::default().with(StyleKey::Flex, PatchValue::Number(1.0))`).
907    pub fn with(self, key: crate::StyleKey, value: crate::PatchValue) -> Self {
908        let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
909        let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
910        style.1 = self.1;
911        style
912    }
913
914    /// Its declarations, in order (not its typed styles').
915    pub fn decls(&self) -> &[crate::StyleDecl] {
916        self.0.as_deref().map_or(&[], crate::StylePatch::decls)
917    }
918
919    /// Applies it to `node` in `variant`: the declarations with `attr`, the
920    /// typed styles as part of the node's own. A bound style adds its
921    /// typed styles as a bound part only when it has some as the element
922    /// is made (they are set with the element; JS's styles have none), so
923    /// a style prop left unset costs what a style of declarations does.
924    pub(crate) fn apply(
925        node: &mut ElNode,
926        style: impl IntoReactive<Style>,
927        variant: Variant,
928        attr: impl Fn(&mut Attrs, Option<Arc<crate::StylePatch>>) + 'static,
929    ) {
930        match style.into_reactive() {
931            Reactive::Static(Style(patch, typed)) => {
932                attr(&mut node.attrs, patch);
933                if !typed.is_empty() {
934                    node.style.extend_as(variant, typed);
935                }
936            }
937            Reactive::Bound(f) => {
938                let typed = super::untracked(|| !f().1.is_empty());
939                let patch = f.clone();
940                node.bind_attr(move || patch().0, attr);
941                if typed {
942                    // Resolved here: the bound parts of what it adds would
943                    // not run in this resolution.
944                    node.style
945                        .bind(move |s| s.extend_as(variant, f().1.resolved()));
946                }
947            }
948        }
949    }
950}
951
952impl From<crate::StylePatch> for Style {
953    fn from(patch: crate::StylePatch) -> Self {
954        Self(Some(Arc::new(patch)), StyleRefinement::default())
955    }
956}
957
958impl From<StyleRefinement> for Style {
959    fn from(style: StyleRefinement) -> Self {
960        Self(None, style)
961    }
962}
963
964impl JsValue for Style {
965    fn ts_type(_types: &mut super::TsTypes) -> String {
966        "StyleProp<ViewStyle>".into()
967    }
968
969    /// Decoded as a host element's `style` is ([`super::JsHost::style`]);
970    /// what it does not take is logged, as there.
971    fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
972        if value.is_nullish() {
973            return Ok(Self::default());
974        }
975        Ok(Self::from(value.host().style(value.raw())?))
976    }
977
978    /// A style is JS's to give, not to get back.
979    fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
980        Err(PropError("a style does not convert back to JS".to_owned()))
981    }
982}
983
984impl<T: Element> Styled for T {
985    fn style(&mut self) -> &mut StyleRefinement {
986        &mut self.node().style
987    }
988}
989
990/// Elements with children.
991pub trait ParentElement: Element {
992    /// Adds a child: an element, or the elements an `Option`, a `Vec`, an
993    /// array or an iterator holds.
994    fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
995        child.__push_into(&mut self.node().children);
996        self
997    }
998
999    /// Adds children (an `Option` adds one or none).
1000    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1001        self.node()
1002            .children
1003            .extend(children.into_iter().map(|c| c.into_element().0));
1004        self
1005    }
1006
1007    /// Places slot `slot` here when the app passed it, as `place` styles it
1008    /// (the closure gets the slot's own node).
1009    fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1010        if let Some(slot) = slot {
1011            let mut node = ElNode::new(Tag::View);
1012            node.kind = ElKind::Slot(slot.name);
1013            self.node().children.push(place(SlotElement(node)).0);
1014        }
1015        self
1016    }
1017
1018    /// Places the app's JSX children here one by one: `place(child, at)`
1019    /// wraps each (runs again when the children change).
1020    fn children_each<R: IntoElement>(
1021        mut self,
1022        children: impl Into<Children>,
1023        place: impl Fn(Child, Position) -> R + 'static,
1024    ) -> Self {
1025        let _ = children.into();
1026        let mut node = ElNode::new(Tag::View);
1027        node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1028        self.node().children.push(node);
1029        self
1030    }
1031
1032    /// Places the app's virtualized list of `items` here: `config` lays
1033    /// the list out (size, columns, padding), `row(content, at)` wraps
1034    /// each row the app renders, once per cell (`at` follows the row the
1035    /// cell shows and the number of rows). Only rows near the viewport
1036    /// exist; the core recycles them.
1037    fn list<R: IntoElement>(
1038        mut self,
1039        items: Items,
1040        config: impl FnOnce(ListElement) -> ListElement,
1041        row: impl Fn(Child, Position) -> R + 'static,
1042    ) -> Self {
1043        let mut node = ElNode::new(Tag::List);
1044        node.kind = ElKind::List(Box::new(ListEl {
1045            name: items.name,
1046            config: ListConfig::default(),
1047            row: Rc::new(move |content, at| row(content, at).into_element()),
1048        }));
1049        self.node().children.push(config(ListElement(node)).0);
1050        self
1051    }
1052}
1053
1054/// Elements with an accessibility description.
1055pub trait Accessible: Element {
1056    /// Whether assistive technologies see it as one element.
1057    fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1058        self.node()
1059            .bind_attr(accessible, |a, accessible| a.accessible = Some(accessible));
1060        self
1061    }
1062
1063    /// What screen readers say.
1064    fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1065        self.node()
1066            .bind_attr(label, |a, label| a.label = Some(label));
1067        self
1068    }
1069
1070    /// What screen readers say, while it is set (`None`: what its
1071    /// content says).
1072    fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1073        self.node().bind_attr(label, |a, label| a.label = label);
1074        self
1075    }
1076
1077    /// What happens when activated, for screen readers.
1078    fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1079        self.node().bind_attr(hint, |a, hint| a.hint = Some(hint));
1080        self
1081    }
1082
1083    /// What it is (a button, a header, ...).
1084    fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1085        self.node().bind_attr(role, |a, role| a.role = role);
1086        self
1087    }
1088
1089    /// Its state for screen readers (`disabled` follows
1090    /// [`Interactive::disabled`]).
1091    fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1092        self.node().bind_attr(state, |a, state| {
1093            a.state = AccessibilityState {
1094                disabled: a.state.disabled,
1095                ..state
1096            };
1097        });
1098        self
1099    }
1100
1101    /// Its value for screen readers, for a range (a progress bar, a
1102    /// slider: `min`, `max` and `now`) or as a text; `None` has none (an
1103    /// indeterminate progress bar keeps its range and leaves out `now`).
1104    fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1105        self.node().bind_attr(value, |a, value| a.value = value);
1106        self
1107    }
1108
1109    /// The actions assistive technologies offer on it (TS:
1110    /// `accessibilityActions`): `increment` and `decrement` for an
1111    /// adjustable element, `activate`, `longpress`, or the app's own with
1112    /// a label; [`Interactive::on_accessibility_action`] hears them.
1113    fn accessibility_actions(mut self, actions: Vec<crate::AccessibilityActionDef>) -> Self {
1114        super::host::set(
1115            self.node(),
1116            Prop::Accessibility(AccessibilityProp::Actions(actions)),
1117        );
1118        self
1119    }
1120}
1121
1122/// What an element's tooltip can be ([`Interactive::tooltip`]): an
1123/// element, shown as it is (`nsh_base`'s `Tooltip` is the tooltip itself).
1124pub trait IntoTooltip {
1125    #[doc(hidden)]
1126    fn apply_tooltip(self, node: &mut ElNode);
1127}
1128
1129impl IntoTooltip for AnyElement {
1130    fn apply_tooltip(self, node: &mut ElNode) {
1131        // A hint overlay inside the element, as the core makes for JS's.
1132        let mut hint = ElNode::new(Tag::Overlay);
1133        hint.key = Some("tooltip".into());
1134        hint.attrs.pointer_events = PointerEvents::None;
1135        let gap = Points(4.0);
1136        for prop in [
1137            crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1138            crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1139            crate::OverlayProp::Offset(gap),
1140            crate::OverlayProp::Margin(gap),
1141        ] {
1142            super::host::set(&mut hint, Prop::Overlay(prop));
1143        }
1144        hint.children.push(self.0);
1145        node.children.push(hint);
1146    }
1147}
1148
1149impl<C: Component> IntoTooltip for ComponentElement<C> {
1150    fn apply_tooltip(self, node: &mut ElNode) {
1151        self.into_element().apply_tooltip(node);
1152    }
1153}
1154
1155/// Makes `hint`, an element whose root is a hint overlay
1156/// ([`super::Overlay::hint`]: `nsh_base`'s `Tooltip`), the tooltip of
1157/// `node` as it is, with no overlay of the core's around it (its
1158/// [`IntoTooltip`]).
1159#[doc(hidden)]
1160pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1161    let mut hint = hint.0;
1162    hint.key = Some("tooltip".into());
1163    node.children.push(hint);
1164}
1165
1166/// Elements that take touches.
1167pub trait Interactive: Element {
1168    /// A hint about it, shown above it on the desktops while the pointer
1169    /// rests on it (after half a second), until the pointer leaves or
1170    /// presses it; never on touch screens, and it never takes the pointer.
1171    /// The element is shown as it is; `nsh_base`'s `Tooltip` is the tooltip
1172    /// itself, with its own placement, delay and reports.
1173    fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1174        tooltip.apply_tooltip(self.node());
1175        self
1176    }
1177
1178    /// A local file drag entered this desktop drop destination.
1179    fn on_file_drag_enter<M>(self, listener: impl IntoListener<(), M>) -> Self {
1180        self.on(
1181            EventKind::FileDragEnter,
1182            events::typed(listener.into_listener(), events::unit),
1183        )
1184    }
1185
1186    /// A local file drag left this desktop drop destination.
1187    fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1188        self.on(
1189            EventKind::FileDragLeave,
1190            events::typed(listener.into_listener(), events::unit),
1191        )
1192    }
1193
1194    /// Local files or directories were dropped on this desktop destination.
1195    fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1196        self.on(
1197            EventKind::FileDrop,
1198            events::typed(listener.into_listener(), events::file_drop),
1199        )
1200    }
1201
1202    /// The mouse came over it or an element inside it (never on touches).
1203    fn on_hover_in<M>(self, listener: impl IntoListener<(), M>) -> Self {
1204        self.on(
1205            EventKind::HoverIn,
1206            events::typed(listener.into_listener(), events::unit),
1207        )
1208    }
1209
1210    /// The mouse left it and the elements inside it, or the window.
1211    fn on_hover_out<M>(self, listener: impl IntoListener<(), M>) -> Self {
1212        self.on(
1213            EventKind::HoverOut,
1214            events::typed(listener.into_listener(), events::unit),
1215        )
1216    }
1217
1218    /// The mouse moved over it (or an element inside it) with no button
1219    /// down: where, in it and in its root view, at most once per frame.
1220    fn on_hover_move<M>(self, listener: impl IntoListener<HoverEvent, M>) -> Self {
1221        self.on(
1222            EventKind::HoverMove,
1223            events::typed(listener.into_listener(), events::hover),
1224        )
1225    }
1226
1227    /// The mouse moved inside it, including while dragging: local coordinates
1228    /// in points, at most once per frame (desktops and web).
1229    fn on_mouse_move<M>(self, listener: impl IntoListener<crate::Point<crate::Points>, M>) -> Self {
1230        self.on(
1231            EventKind::MouseMove,
1232            events::typed(listener.into_listener(), events::mouse_position),
1233        )
1234    }
1235
1236    /// The secondary button was pressed over it (a right click,
1237    /// Control-click on Apple platforms): where, to open a menu at
1238    /// (`page_x`, `page_y`). The nearest element that listens hears it;
1239    /// a text input or selectable text nearer shows its own menu instead.
1240    fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1241        self.on(
1242            EventKind::ContextMenu,
1243            events::typed(listener.into_listener(), events::context_menu),
1244        )
1245    }
1246
1247    /// It took the keyboard focus: an input, or a view that takes presses
1248    /// reached by Tab (or `focus()`) on the platforms that move the focus
1249    /// between pressables.
1250    fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1251        self.on(
1252            EventKind::Focus,
1253            events::typed(listener.into_listener(), events::unit),
1254        )
1255    }
1256
1257    /// It lost the keyboard focus.
1258    fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1259        self.on(
1260            EventKind::Blur,
1261            events::typed(listener.into_listener(), events::unit),
1262        )
1263    }
1264
1265    /// Handles presses.
1266    fn on_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1267        self.on(
1268            EventKind::Press,
1269            events::typed(listener.into_listener(), events::unit),
1270        )
1271    }
1272
1273    /// Handles presses held for about half a second.
1274    fn on_long_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1275        self.on(
1276            EventKind::LongPress,
1277            events::typed(listener.into_listener(), events::unit),
1278        )
1279    }
1280
1281    /// A finger went down on the element.
1282    fn on_press_down<M>(self, listener: impl IntoListener<(), M>) -> Self {
1283        self.on(
1284            EventKind::PressDown,
1285            events::typed(listener.into_listener(), events::unit),
1286        )
1287    }
1288
1289    /// The press ended, inside or outside the element.
1290    fn on_press_up<M>(self, listener: impl IntoListener<(), M>) -> Self {
1291        self.on(
1292            EventKind::PressUp,
1293            events::typed(listener.into_listener(), events::unit),
1294        )
1295    }
1296
1297    /// Its frame changed (relative to its parent).
1298    fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1299        self.on(
1300            EventKind::Layout,
1301            events::typed(listener.into_listener(), events::layout),
1302        )
1303    }
1304
1305    /// Touches on it or inside it, every phase (custom gestures): the
1306    /// elements around the finger hear them from it outwards. To have them
1307    /// alone, claim them ([`Interactive::claim_touches`]).
1308    fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1309        self.on(
1310            EventKind::Touch,
1311            events::typed(listener.into_listener(), events::touch),
1312        )
1313    }
1314
1315    /// Claims the touches of a gesture as `claim` says (TS:
1316    /// `onStartShouldSetResponder`, `PanResponder`): as the responder it
1317    /// hears them alone (`on_responder_*`), and native scroll views around
1318    /// it stop taking them over. Several claims may be given.
1319    fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1320        if let Some(pan) = claim.pan {
1321            super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1322        }
1323        super::responder::of(self.node()).claims.push(claim);
1324        self
1325    }
1326
1327    /// As the responder, refuses to hand the touches over to an element
1328    /// around it that claims them (TS: `onResponderTerminationRequest`
1329    /// returning false); a native scroll view that started dragging first
1330    /// still takes them.
1331    fn keep_touches(mut self, keep: bool) -> Self {
1332        super::responder::of(self.node()).keep = keep;
1333        self
1334    }
1335
1336    /// It became the responder (TS: `onResponderGrant`).
1337    fn on_responder_grant<M>(
1338        mut self,
1339        listener: impl IntoListener<super::ResponderEvent, M>,
1340    ) -> Self {
1341        super::responder::of(self.node()).grant = Some(listener.into_listener());
1342        self
1343    }
1344
1345    /// It claimed the touches, but the responder kept them (TS:
1346    /// `onResponderReject`).
1347    fn on_responder_reject<M>(
1348        mut self,
1349        listener: impl IntoListener<super::ResponderEvent, M>,
1350    ) -> Self {
1351        super::responder::of(self.node()).reject = Some(listener.into_listener());
1352        self
1353    }
1354
1355    /// As the responder, a finger went down (the first one too, after the
1356    /// grant; TS: `onResponderStart`).
1357    fn on_responder_start<M>(
1358        mut self,
1359        listener: impl IntoListener<super::ResponderEvent, M>,
1360    ) -> Self {
1361        super::responder::of(self.node()).start = Some(listener.into_listener());
1362        self
1363    }
1364
1365    /// As the responder, the fingers moved (TS: `onResponderMove`).
1366    fn on_responder_move<M>(
1367        mut self,
1368        listener: impl IntoListener<super::ResponderEvent, M>,
1369    ) -> Self {
1370        super::responder::of(self.node()).moved = Some(listener.into_listener());
1371        self
1372    }
1373
1374    /// As the responder, a finger lifted (TS: `onResponderEnd`).
1375    fn on_responder_end<M>(
1376        mut self,
1377        listener: impl IntoListener<super::ResponderEvent, M>,
1378    ) -> Self {
1379        super::responder::of(self.node()).end = Some(listener.into_listener());
1380        self
1381    }
1382
1383    /// The last finger lifted: it is no longer the responder (TS:
1384    /// `onResponderRelease`).
1385    fn on_responder_release<M>(
1386        mut self,
1387        listener: impl IntoListener<super::ResponderEvent, M>,
1388    ) -> Self {
1389        super::responder::of(self.node()).release = Some(listener.into_listener());
1390        self
1391    }
1392
1393    /// Another element or a native gesture took the touches over, or the
1394    /// system cancelled them (TS: `onResponderTerminate`).
1395    fn on_responder_terminate<M>(
1396        mut self,
1397        listener: impl IntoListener<super::ResponderEvent, M>,
1398    ) -> Self {
1399        super::responder::of(self.node()).terminate = Some(listener.into_listener());
1400        self
1401    }
1402
1403    /// Drags move these values natively (by the drag's translation from
1404    /// where they were), with no engine work per frame; bind them to its
1405    /// transform to follow the finger. `on_pan_end` reports where they
1406    /// ended, to spring them on.
1407    fn pan_values(
1408        mut self,
1409        x: Option<&super::AnimatedValue>,
1410        y: Option<&super::AnimatedValue>,
1411    ) -> Self {
1412        let x = x.and_then(|v| v.node().live());
1413        let y = y.and_then(|v| v.node().live());
1414        let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
1415        super::host::set(self.node(), prop);
1416        let bound = &mut self.node().attrs.bound;
1417        bound.extend(x);
1418        bound.extend(y);
1419        self
1420    }
1421
1422    /// Enables native pans without replacing their values or listeners.
1423    /// A disabled pan leaves presses and scrolling to the content.
1424    fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
1425        super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
1426        self
1427    }
1428
1429    /// On iOS, a vertical pan shares descendant scroll views' touches and
1430    /// follows only the downward distance left after scrolling to the top.
1431    /// Other platforms keep their normal pan and scroll arbitration.
1432    fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
1433        super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
1434        self
1435    }
1436
1437    /// Two-finger pinches scale `scale` natively (multiplying the value it
1438    /// has when the pinch starts; TS: `pinch={{ scale }}`); bind it to its
1439    /// transform ([`Element::bind_scale`]). `on_pinch_start` /
1440    /// `on_pinch_end` report the pinches.
1441    fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
1442        if let Some(node) = scale.node().live() {
1443            super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
1444            self.node().attrs.bound.push(node);
1445        }
1446        self
1447    }
1448
1449    /// Two-finger rotations turn `angle` natively, in degrees (added to
1450    /// the value it has when the rotation starts; TS: `rotation={{ angle
1451    /// }}`); bind it to its transform ([`Element::bind_rotate`]).
1452    fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
1453        if let Some(node) = angle.node().live() {
1454            super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
1455            self.node().attrs.bound.push(node);
1456        }
1457        self
1458    }
1459
1460    /// A drag started on it (the platform recognizes it).
1461    fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1462        self.on(
1463            EventKind::PanStart,
1464            events::typed(listener.into_listener(), events::pan),
1465        )
1466    }
1467
1468    /// The drag ended, with its velocity.
1469    fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1470        self.on(
1471            EventKind::PanEnd,
1472            events::typed(listener.into_listener(), events::pan),
1473        )
1474    }
1475
1476    /// A pinch started (its scale).
1477    fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1478        self.on(
1479            EventKind::PinchStart,
1480            events::typed(listener.into_listener(), events::pinch),
1481        )
1482    }
1483
1484    /// The pinch ended.
1485    fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1486        self.on(
1487            EventKind::PinchEnd,
1488            events::typed(listener.into_listener(), events::pinch),
1489        )
1490    }
1491
1492    /// A two-finger rotation started (its angle).
1493    fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1494        self.on(
1495            EventKind::RotationStart,
1496            events::typed(listener.into_listener(), events::rotation),
1497        )
1498    }
1499
1500    /// The rotation ended.
1501    fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1502        self.on(
1503            EventKind::RotationEnd,
1504            events::typed(listener.into_listener(), events::rotation),
1505        )
1506    }
1507
1508    /// An assistive technology performed an action (its name).
1509    fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
1510        self.on(
1511            EventKind::AccessibilityAction,
1512            events::typed(listener.into_listener(), events::action),
1513        )
1514    }
1515
1516    /// Handles native event `kind` with its raw payload (the element
1517    /// listens to it).
1518    fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
1519        self.node().handlers.push((kind, listener.into_listener()));
1520        self
1521    }
1522
1523    /// Presses also count this far outside it.
1524    fn hit_slop(mut self, insets: EdgeInsets) -> Self {
1525        super::host::set(self.node(), Prop::HitSlop(insets));
1526        self
1527    }
1528
1529    /// How long a press must last to be a long press, in milliseconds.
1530    fn long_press_delay(mut self, ms: f32) -> Self {
1531        super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
1532        self
1533    }
1534
1535    /// The press ripple (Android).
1536    fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
1537        super::host::set(self.node(), Prop::Ripple(Some(ripple)));
1538        self
1539    }
1540
1541    /// The elevation shadow (Android).
1542    fn elevation(mut self, elevation: impl Into<Points>) -> Self {
1543        super::host::set(self.node(), Prop::Elevation(elevation.into()));
1544        self
1545    }
1546
1547    /// The system material of a backdrop blur (iOS).
1548    fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
1549        super::host::set(self.node(), Prop::BackdropMaterial(material));
1550        self
1551    }
1552
1553    /// The id UI tests find it by.
1554    fn test_id(mut self, id: &str) -> Self {
1555        super::host::set(self.node(), Prop::TestId(Some(id.into())));
1556        self
1557    }
1558
1559    /// Whether a desktop press drags the window and a double click follows
1560    /// the system's title-bar behavior. The nearest explicit value wins;
1561    /// inputs and press/touch handlers inside a drag region stay interactive.
1562    /// Set false on a child to exclude it from its parent's drag region.
1563    fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
1564        super::host::bind_prop(self.node(), enabled, |enabled| {
1565            Prop::WindowDrag(Some(enabled))
1566        });
1567        self
1568    }
1569
1570    /// Whether a view that takes presses is a stop of the keyboard focus
1571    /// (Tab; default true): false leaves it to the pointer, as a backdrop
1572    /// that closes a popover is.
1573    fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
1574        super::host::bind_prop(self.node(), focusable, |focusable| {
1575            Prop::Focusable(Some(focusable))
1576        });
1577        self
1578    }
1579
1580    /// The id inputs name an input accessory by (`nativeID`).
1581    fn native_id(mut self, id: &str) -> Self {
1582        super::host::set(self.node(), Prop::NativeId(Some(id.into())));
1583        self
1584    }
1585
1586    /// Styles while pressed (native: nothing runs).
1587    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1588        let s = f(StyleRefinement::default());
1589        self.style().extend_as(Variant::ACTIVE, s);
1590        self
1591    }
1592
1593    /// Styles while a pointer hovers it (iPad, Mac, mice).
1594    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1595        let s = f(StyleRefinement::default());
1596        self.style().extend_as(Variant::HOVER, s);
1597        self
1598    }
1599
1600    /// Styles while focused.
1601    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1602        let s = f(StyleRefinement::default());
1603        self.style().extend_as(Variant::FOCUS, s);
1604        self
1605    }
1606
1607    /// Styles while [`Interactive::disabled`] (Tailwind's `disabled:`).
1608    fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1609        let s = f(StyleRefinement::default());
1610        self.style().extend_as(Variant::DISABLED, s);
1611        self
1612    }
1613
1614    /// No presses nor press feedback; screen readers say it is disabled.
1615    fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1616        self.node().bind_attr(disabled, |a, disabled| {
1617            a.disabled = disabled;
1618            a.state.disabled = disabled;
1619        });
1620        self
1621    }
1622
1623    /// Which touches it and its children take.
1624    fn pointer_events(mut self, pointer_events: impl IntoReactive<PointerEvents>) -> Self {
1625        self.node()
1626            .bind_attr(pointer_events, |a, p| a.pointer_events = p);
1627        self
1628    }
1629
1630    /// An app's style while selected (`accessibility_state` `selected`;
1631    /// TS: a `Button`'s `selectedStyle`), as `selected:` classes apply.
1632    fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
1633        Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
1634            super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
1635        });
1636        self
1637    }
1638
1639    /// An app's style while checked (`accessibility_state` `checked`, not
1640    /// mixed: a checkbox's, a switch's, a radio's), as `checked:` classes
1641    /// apply.
1642    fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
1643        Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
1644            super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
1645        });
1646        self
1647    }
1648
1649    /// An app's style while indeterminate (`accessibility_state` `checked`
1650    /// mixed: a checkbox's `indeterminate`), as `indeterminate:` classes
1651    /// apply.
1652    fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
1653        Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
1654            super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
1655        });
1656        self
1657    }
1658
1659    /// Styles it as checked while `checked` holds (its `checked:` classes
1660    /// and [`Self::checked_style`]), as a part of a control that is: a
1661    /// switch's track and thumb, a checkbox's mark (`gpui-base`'s
1662    /// `SwitchThumb::new(checked)`). Screen readers hear it from the
1663    /// control alone, so the part is no second checkable element.
1664    fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
1665        self.node().bind_attr(checked, |a, checked| {
1666            project(a, crate::tailwind::state::CHECKED, checked)
1667        });
1668        self
1669    }
1670
1671    /// Styles it as indeterminate while `indeterminate` holds (its
1672    /// `indeterminate:` classes and [`Self::indeterminate_style`]), as a
1673    /// part of a control that is: a checkbox's indicator (`gpui-base`'s
1674    /// `CheckboxIndicator::state(CheckboxState::Indeterminate)`). Screen
1675    /// readers hear it from the control alone.
1676    fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
1677        self.node().bind_attr(indeterminate, |a, indeterminate| {
1678            project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
1679        });
1680        self
1681    }
1682
1683    /// Styles it as disabled while `disabled` holds (its `disabled:`
1684    /// classes and [`Self::disabled_style`]), as a part of a disabled
1685    /// control (`gpui-base`'s `SwitchThumb::disabled`). The control takes
1686    /// no presses and tells screen readers; the part keeps its own.
1687    fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1688        self.node().bind_attr(disabled, |a, disabled| {
1689            project(a, crate::tailwind::state::DISABLED, disabled)
1690        });
1691        self
1692    }
1693}
1694
1695/// Sets or clears `bit` of the states an element shows as a part.
1696fn project(a: &mut Attrs, bit: u8, on: bool) {
1697    if on {
1698        a.projected_states |= bit;
1699    } else {
1700        a.projected_states &= !bit;
1701    }
1702}
1703
1704macro_rules! element {
1705    ($(#[$doc:meta])* $name:ident) => {
1706        $(#[$doc])*
1707        #[derive(Clone)]
1708        pub struct $name(ElNode);
1709
1710        impl Element for $name {
1711            fn node(&mut self) -> &mut ElNode {
1712                &mut self.0
1713            }
1714        }
1715
1716        impl IntoElement for $name {
1717            fn into_element(self) -> AnyElement {
1718                AnyElement(self.0)
1719            }
1720        }
1721
1722        impl Accessible for $name {}
1723
1724        impl IntoTooltip for $name {
1725            fn apply_tooltip(self, node: &mut ElNode) {
1726                self.into_element().apply_tooltip(node);
1727            }
1728        }
1729    };
1730}
1731
1732element! {
1733    /// A view (`<view>`), made by [`view`].
1734    View
1735}
1736
1737element! {
1738    /// A text block (`<text>`), made by [`text`].
1739    Text
1740}
1741
1742element! {
1743    /// An image (`<image>`), made by [`image`].
1744    Image
1745}
1746
1747element! {
1748    /// A slot's node as a view places it ([`ParentElement::slot`]):
1749    /// style it like a view; its children are the app's.
1750    SlotElement
1751}
1752
1753element! {
1754    /// A list as a view lays it out ([`ParentElement::list`]).
1755    ListElement
1756}
1757
1758impl Interactive for View {}
1759impl ParentElement for View {}
1760impl Interactive for SlotElement {}
1761impl Interactive for Text {}
1762impl Interactive for Image {}
1763
1764/// A text's children are its spans, as nested `<text>`s in JS: texts with
1765/// styles and presses of their own (a link inside a sentence), strings,
1766/// and views and images placed inline, wrapping with the words. The core
1767/// merges them into one paragraph.
1768impl ParentElement for Text {
1769    fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1770        let at = self.0.children.len();
1771        child.__push_into(&mut self.0.children);
1772        for el in &mut self.0.children[at..] {
1773            *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
1774        }
1775        self
1776    }
1777
1778    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1779        self.0
1780            .children
1781            .extend(children.into_iter().map(|c| span(c.into_element().0)));
1782        self
1783    }
1784}
1785
1786/// A child of a text: a bare string (a text with nothing of its own) is a
1787/// piece of its content, anything else a span or an inline element.
1788fn span(mut el: ElNode) -> ElNode {
1789    if el.tag == Tag::Text
1790        && matches!(el.kind, ElKind::Plain)
1791        && el.key.is_none()
1792        && el.children.is_empty()
1793        && el.handlers.is_empty()
1794        && el.style.is_empty()
1795        && el.attrs == Attrs::default()
1796        && !el.is_bound()
1797    {
1798        el.kind = ElKind::Raw;
1799    }
1800    el
1801}
1802
1803impl Text {
1804    /// At most `lines` lines (0: no limit), the last one truncated.
1805    pub fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
1806        self.0
1807            .bind_attr(lines, |a, lines| a.number_of_lines = lines);
1808        self
1809    }
1810
1811    /// Where a truncated line is cut.
1812    pub fn ellipsize_mode(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
1813        super::host::bind_prop(&mut self.0, mode, Prop::EllipsizeMode);
1814        self
1815    }
1816
1817    /// The user can select and copy it.
1818    pub fn selectable(mut self, selectable: impl IntoReactive<bool>) -> Self {
1819        super::host::bind_prop(&mut self.0, selectable, |s| Prop::Selectable(Some(s)));
1820        self
1821    }
1822
1823    /// The highlight of its selection, when it is selectable.
1824    pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
1825        super::host::bind_prop(&mut self.0, color, |c: Hsla| {
1826            Prop::SelectionColor(Some(Color::from(c)))
1827        });
1828        self
1829    }
1830
1831    /// Shrinks the font, down to `min_scale` of it, to fit its lines.
1832    pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
1833        super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
1834        super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
1835        self
1836    }
1837
1838    /// Whether its fonts follow the system's text size (true by default;
1839    /// TS: `allowFontScaling`).
1840    pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
1841        super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
1842        self
1843    }
1844
1845    /// At most this multiple of its fonts' sizes with the system's text
1846    /// size (TS: `maxFontSizeMultiplier`; 0: no limit).
1847    pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
1848        super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
1849        self
1850    }
1851}
1852
1853impl Image {
1854    /// How it fits its box (default: cover).
1855    pub fn resize_mode(mut self, mode: impl IntoReactive<crate::ResizeMode>) -> Self {
1856        super::host::bind_prop(&mut self.0, mode, Prop::ResizeMode);
1857        self
1858    }
1859
1860    /// Shown until it loads (a URL, an `asset:/` URI or an
1861    /// [`super::ImageAsset`]).
1862    pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
1863        super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
1864            Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
1865                uri: src.uri.to_arc(),
1866                size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
1867                scales: src.scales,
1868                data: None,
1869            })))
1870        });
1871        self
1872    }
1873
1874    /// Draws its opaque pixels in `color` (a template image, an icon).
1875    pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
1876        Styled::tint_color(self, color)
1877    }
1878
1879    /// Blurs it.
1880    pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
1881        super::host::set(
1882            &mut self.0,
1883            Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
1884        );
1885        self
1886    }
1887
1888    /// Fades it in over `ms` milliseconds once loaded.
1889    pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
1890        super::host::bind_prop(&mut self.0, ms, |ms| {
1891            Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
1892        });
1893        self
1894    }
1895
1896    /// It loaded: its size in pixels.
1897    pub fn on_load<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
1898        self.on(
1899            EventKind::Load,
1900            events::typed(listener.into_listener(), events::size),
1901        )
1902    }
1903
1904    /// It failed to load (the message).
1905    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1906        self.on(
1907            EventKind::Error,
1908            events::typed(listener.into_listener(), events::message),
1909        )
1910    }
1911
1912    /// It started loading.
1913    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1914        self.on(
1915            EventKind::LoadStart,
1916            events::typed(listener.into_listener(), events::unit),
1917        )
1918    }
1919
1920    /// It finished loading, or failed.
1921    pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1922        self.on(
1923            EventKind::LoadEnd,
1924            events::typed(listener.into_listener(), events::unit),
1925        )
1926    }
1927
1928    /// Its download went on: bytes so far and in all (at most every 100
1929    /// ms; none for images already in memory).
1930    pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
1931        self.on(
1932            EventKind::Progress,
1933            events::typed(listener.into_listener(), events::image_progress),
1934        )
1935    }
1936}
1937
1938impl super::Scrollable for ListElement {}
1939
1940impl super::ListLayout for ListElement {
1941    fn config(&mut self) -> &mut ListConfig {
1942        match &mut self.0.kind {
1943            ElKind::List(list) => &mut list.config,
1944            _ => unreachable!("a ListElement is a list"),
1945        }
1946    }
1947
1948    fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
1949        &mut self.0.bound_list
1950    }
1951}
1952
1953/// A named slot (an `Option<Slot>` prop): `Some` while the app passes
1954/// content for it. Placed with [`ParentElement::slot`].
1955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1956pub struct Slot {
1957    name: &'static str,
1958}
1959
1960impl Slot {
1961    pub(crate) fn new(name: &'static str) -> Self {
1962        Self { name }
1963    }
1964
1965    /// Its name (its prop's, in JS).
1966    pub fn name(&self) -> &'static str {
1967        self.name
1968    }
1969
1970    /// The slot's node, to style and place (its children are the app's).
1971    pub fn element(self) -> SlotElement {
1972        let mut node = ElNode::new(Tag::View);
1973        node.kind = ElKind::Slot(self.name);
1974        SlotElement(node)
1975    }
1976}
1977
1978/// The app's virtualized rows (an `Items` prop): in JS the component takes
1979/// `each` and a row renderer like `List`. Placed with
1980/// [`ParentElement::list`].
1981#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1982pub struct Items {
1983    name: &'static str,
1984}
1985
1986impl Items {
1987    #[doc(hidden)]
1988    pub const fn __new(name: &'static str) -> Self {
1989        Self { name }
1990    }
1991}
1992
1993/// A piece of the app's content to place: one JSX child
1994/// ([`ParentElement::children_each`]) or a list row's content
1995/// ([`ParentElement::list`]).
1996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1997pub struct Child(ChildRef);
1998
1999#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2000enum ChildRef {
2001    Js(NodeId),
2002    Row,
2003}
2004
2005impl Child {
2006    pub(crate) fn js(id: NodeId) -> Self {
2007        Self(ChildRef::Js(id))
2008    }
2009
2010    pub(crate) fn row() -> Self {
2011        Self(ChildRef::Row)
2012    }
2013}
2014
2015impl IntoElement for Child {
2016    fn into_element(self) -> AnyElement {
2017        let mut node = ElNode::new(Tag::View);
2018        node.kind = match self.0 {
2019            ChildRef::Js(id) => ElKind::JsChild(id),
2020            ChildRef::Row => ElKind::Children,
2021        };
2022        AnyElement(node)
2023    }
2024}
2025
2026/// A view.
2027pub fn view() -> View {
2028    View(ElNode::new(Tag::View))
2029}
2030
2031/// A text block showing `content`, then its children (spans:
2032/// [`ParentElement`] for [`Text`]).
2033pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2034    let mut node = ElNode::new(Tag::Text);
2035    match content.into_reactive() {
2036        Reactive::Static(content) => node.text = Some(content),
2037        Reactive::Bound(content) => {
2038            node.text = Some(SharedString::default());
2039            node.bound_text = Some(content);
2040        }
2041    }
2042    Text(node)
2043}
2044
2045/// An image loading `src`: a URL, a file path or `asset:/` URI, or an
2046/// [`super::ImageAsset`] (`asset!("logo@2x.png")`), which lays out at its
2047/// natural size before it loads.
2048pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2049    let mut node = ElNode::new(Tag::Image);
2050    node.bind_attr(src, |a, src| a.src = Some(src));
2051    Image(node)
2052}
2053
2054/// The JSX children of a component (a `Children` prop): placed where the
2055/// view puts it, among the view's own children.
2056#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2057pub struct Children {
2058    present: bool,
2059}
2060
2061impl Children {
2062    pub(crate) fn new(present: bool) -> Self {
2063        Self { present }
2064    }
2065
2066    /// The app passed none.
2067    pub fn is_empty(&self) -> bool {
2068        !self.present
2069    }
2070}
2071
2072impl IntoElement for Children {
2073    fn into_element(self) -> AnyElement {
2074        let mut node = ElNode::new(Tag::View);
2075        node.kind = ElKind::Children;
2076        AnyElement(node)
2077    }
2078}
2079
2080/// Another component in a view ([`Component::element`]). Its styles go
2081/// after the component's own, like an app's classes, and so do its inline
2082/// style, animated values and insets ([`Element`]'s), on the component's
2083/// root; its state styles ([`Self::active`], [`Self::hover`],
2084/// [`Self::focus`], [`Self::disabled_style`], [`Styled::selected`],
2085/// [`Styled::checked`]) follow the states of that root, as an app's
2086/// `active:` / `hover:` classes on a TSX component do. It hears and is to
2087/// assistive technologies what the component says (its events and props):
2088/// it is not [`Interactive`] or [`Accessible`]. The element a
2089/// `#[component]`'s constructor makes (`button()`) wraps one
2090/// ([`ComponentBuilder`]).
2091pub struct ComponentElement<C: Component> {
2092    node: ElNode,
2093    _component: PhantomData<fn() -> C>,
2094}
2095
2096impl<C: Component> ComponentElement<C> {
2097    /// The element of `C` given `props`: what a component's constructor
2098    /// (`button()`) and [`Component::element`] start from.
2099    #[doc(hidden)]
2100    pub fn __new(props: C::Props) -> Self {
2101        Self::new(props)
2102    }
2103
2104    /// Its props, for the setters a `#[component]` makes on its element.
2105    #[doc(hidden)]
2106    pub fn __props_mut(&mut self) -> &mut C::Props {
2107        match &mut self.node.kind {
2108            ElKind::Component(c) => c
2109                .props
2110                .as_any_mut()
2111                .downcast_mut::<C::Props>()
2112                .expect("a component element holds its component's props"),
2113            _ => unreachable!("a component element is a component's"),
2114        }
2115    }
2116
2117    pub(crate) fn new(props: C::Props) -> Self {
2118        let mut node = ElNode::new(Tag::View);
2119        node.kind = ElKind::Component(ComponentEl {
2120            name: super::component::name_of::<C>(),
2121            make: super::component::make_instance::<C>,
2122            spec: ComponentSpec::of::<C>,
2123            props: Box::new(props),
2124            on_event: Vec::new(),
2125        });
2126        Self {
2127            node,
2128            _component: PhantomData,
2129        }
2130    }
2131
2132    /// Fills its slot `slot` (its prop's JS name: `header`) with `content`
2133    /// (in place of what filled it): the component's view places it as it
2134    /// is where it places the slot, with no node around it (a node of its
2135    /// own only where the view styles the slot).
2136    pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2137        self.node
2138            .children
2139            .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2140        let mut fill = ElNode::new(Tag::View);
2141        fill.kind = ElKind::Fill(slot);
2142        fill.children.push(content.into_element().0);
2143        self.node.children.push(fill);
2144        self
2145    }
2146
2147    /// Fills its `Items` prop with rows of this view (TS: `each` and the
2148    /// row renderer, `keyExtractor`, `header`, ...): the rows,
2149    /// their keys, header, footer, empty view, separators, sticky rows,
2150    /// viewability, the refresh and the end reached are `list`'s, rendered
2151    /// and handled by this component; the layout and the styles are the
2152    /// placing component's ([`ParentElement::list`]), so `list`'s own are
2153    /// left out.
2154    pub fn items(mut self, list: super::VirtualList) -> Self {
2155        match <C::Props as super::Props>::ITEMS {
2156            Some(name) => self.node.children.push(list.into_items(name)),
2157            None => {
2158                log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2159            }
2160        }
2161        self
2162    }
2163
2164    /// Styles while its root is pressed (Tailwind's `active:`; TS: an
2165    /// `active:` class or `activeStyle` given the component), applied
2166    /// natively. The root follows presses when it handles them (a
2167    /// [`Interactive::on_press`] of the component's view).
2168    pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2169        let s = f(StyleRefinement::default());
2170        self.node.style.extend_as(Variant::ACTIVE, s);
2171        self
2172    }
2173
2174    /// Styles while a pointer hovers its root (`hover:`).
2175    pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2176        let s = f(StyleRefinement::default());
2177        self.node.style.extend_as(Variant::HOVER, s);
2178        self
2179    }
2180
2181    /// Styles while its root has focus (`focus:`).
2182    pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2183        let s = f(StyleRefinement::default());
2184        self.node.style.extend_as(Variant::FOCUS, s);
2185        self
2186    }
2187
2188    /// Styles while its root is disabled (`disabled:`): the component's
2189    /// view disables it ([`Interactive::disabled`], a `disabled` prop).
2190    pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2191        let s = f(StyleRefinement::default());
2192        self.node.style.extend_as(Variant::DISABLED, s);
2193        self
2194    }
2195
2196    /// Puts `handle` on this component: its updates go to it.
2197    pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2198        self.node.attrs.element_ref = handle.element().target();
2199        self
2200    }
2201
2202    /// Handles its events (they then do not reach the app). Given several
2203    /// times, every listener hears them, in order. The element a
2204    /// `#[component]`'s constructor makes has a listener method per event
2205    /// instead (`.on_press(..)`: [`ComponentBuilder`]); this stays for
2206    /// components implemented by hand.
2207    pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
2208        let listener = listener.into_listener();
2209        if let ElKind::Component(c) = &mut self.node.kind {
2210            c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
2211                if let Some(event) = event.downcast_ref::<C::Event>() {
2212                    inner(event);
2213                }
2214            }));
2215        }
2216        self
2217    }
2218
2219    /// Handles the events `pick` picks, with the data it gives: the listener
2220    /// method of one event (`on_press`) that `#[derive(Event)]` generates
2221    /// calls it.
2222    #[doc(hidden)]
2223    pub fn __on_variant<T: ?Sized + 'static, M>(
2224        self,
2225        pick: fn(&C::Event) -> Option<&T>,
2226        listener: impl IntoListener<T, M>,
2227    ) -> Self {
2228        let listener = listener.into_listener();
2229        self.on_event(listener.wrap(move |inner, event: &C::Event| {
2230            if let Some(data) = pick(event) {
2231                inner(data);
2232            }
2233        }))
2234    }
2235}
2236
2237/// The element of a `#[component]`, as its constructor makes it: a
2238/// component is made and set up in Rust as a primitive is (`view()`),
2239/// as JSX does in TSX. `#[component] fn Picker` makes `picker()` (the
2240/// function's name in snake case), which returns a `PickerElement` with
2241/// each prop at its default and
2242///
2243/// - a setter per prop, named as its field (`.disabled(..)`): a value, a
2244///   signal, a memo or a prop of the field's type, or a closure returning
2245///   one (bound); an `Option<T>` prop takes a `T` (`.label("Pick one")`),
2246///   a slot the content to fill it with (`.header(text(..))`), the
2247///   children are its [`ParentElement::child`]ren;
2248/// - a listener method per event, named as its TSX handler in snake case
2249///   (`onSelect` is `.on_select(..)`): a unit variant's takes
2250///   `move || ..`, a one-field variant's `move |value: &T| ..`, a
2251///   named-field variant's the event itself;
2252/// - styles ([`Styled`]: they go on the component's root), with this
2253///   trait's for the root's states, and a
2254///   [`ComponentRef`](super::ComponentRef).
2255///
2256/// A prop's setter comes before an element method of the same name (a
2257/// component's `selected` prop before [`Styled::selected`], its `size`
2258/// before [`Styled::size`]; call those as `Styled::selected(element, ..)`).
2259///
2260/// ```
2261/// use nsh_core::prelude::*;
2262///
2263/// /// The props of [`Picker`].
2264/// #[derive(Clone, PartialEq, Props)]
2265/// pub struct PickerProps {
2266///     /// The options.
2267///     pub options: Prop<Vec<SharedString>>,
2268///     /// No presses.
2269///     #[prop(default)]
2270///     pub disabled: Prop<bool>,
2271///     /// What screen readers say.
2272///     pub label: Prop<Option<SharedString>>,
2273/// }
2274///
2275/// /// What a [`Picker`] reports.
2276/// #[derive(Event)]
2277/// pub enum PickerEvent {
2278///     /// Pressed.
2279///     Press,
2280///     /// An option was picked: its index.
2281///     Select(u32),
2282/// }
2283///
2284/// /// Picks an option.
2285/// #[component]
2286/// pub fn Picker(props: PickerProps, cx: Scope<PickerEvent>) -> impl IntoElement {
2287///     view()
2288///         .disabled(props.disabled)
2289///         .on_press(move || cx.emit(PickerEvent::Select(0)))
2290/// }
2291///
2292/// #[component]
2293/// pub fn Form() -> impl IntoElement {
2294///     let busy = signal(false);
2295///     let picked = signal(None::<u32>);
2296///     view().child(
2297///         picker()
2298///             .options(vec![SharedString::from("Tea"), "Coffee".into()])
2299///             .disabled(move || busy.get())
2300///             .label("Drink")
2301///             .on_press(move || log::info!("pressed"))
2302///             .on_select(move |&index: &u32| picked.set(Some(index)))
2303///             .px_4()
2304///             .active(|s| s.opacity(0.6)),
2305///     )
2306/// }
2307/// ```
2308pub trait ComponentBuilder: Element {
2309    /// Its component.
2310    type Component: Component;
2311
2312    /// The element it builds.
2313    #[doc(hidden)]
2314    fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
2315
2316    /// Styles while its root is pressed (Tailwind's `active:`; TS: an
2317    /// `active:` class or `activeStyle` given the component), applied
2318    /// natively. The root follows presses when it handles them (a
2319    /// [`Interactive::on_press`] of the component's view).
2320    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2321        let s = f(StyleRefinement::default());
2322        self.node().style.extend_as(Variant::ACTIVE, s);
2323        self
2324    }
2325
2326    /// Styles while a pointer hovers its root (`hover:`).
2327    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2328        let s = f(StyleRefinement::default());
2329        self.node().style.extend_as(Variant::HOVER, s);
2330        self
2331    }
2332
2333    /// Styles while its root has focus (`focus:`).
2334    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2335        let s = f(StyleRefinement::default());
2336        self.node().style.extend_as(Variant::FOCUS, s);
2337        self
2338    }
2339
2340    /// Styles while its root is disabled (`disabled:`): the component's
2341    /// view disables it ([`Interactive::disabled`], a `disabled` prop).
2342    fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2343        let s = f(StyleRefinement::default());
2344        self.node().style.extend_as(Variant::DISABLED, s);
2345        self
2346    }
2347
2348    /// Puts `handle` on this component: its updates go to it.
2349    fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
2350        self.__element().node.attrs.element_ref = handle.element().target();
2351        self
2352    }
2353}
2354
2355impl<C: Component> Element for ComponentElement<C> {
2356    fn node(&mut self) -> &mut ElNode {
2357        &mut self.node
2358    }
2359}
2360
2361/// The content of a nested component: `.child(..)` / `.children(..)` are
2362/// its `Children`, [`ComponentElement::fill`] its slots, placed where its
2363/// view places the app's.
2364impl<C: Component> ParentElement for ComponentElement<C> {}
2365
2366impl<C: Component> IntoElement for ComponentElement<C> {
2367    fn into_element(self) -> AnyElement {
2368        AnyElement(self.node)
2369    }
2370}