Skip to main content

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