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