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