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    /// `on_pan_start` waits until that distance moves its values.
1745    /// Other platforms keep their normal pan and scroll arbitration.
1746    fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
1747        super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
1748        self
1749    }
1750
1751    /// Two-finger pinches scale `scale` natively (multiplying the value it
1752    /// has when the pinch starts; TS: `pinch={{ scale }}`); bind it to its
1753    /// transform ([`Element::bind_scale`]). `on_pinch_start` /
1754    /// `on_pinch_end` report the pinches.
1755    fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
1756        if let Some(node) = scale.node().live() {
1757            super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
1758            self.node().attrs.bound.push(node);
1759        }
1760        self
1761    }
1762
1763    /// Two-finger rotations turn `angle` natively, in degrees (added to
1764    /// the value it has when the rotation starts; TS: `rotation={{ angle
1765    /// }}`); bind it to its transform ([`Element::bind_rotate`]).
1766    fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
1767        if let Some(node) = angle.node().live() {
1768            super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
1769            self.node().attrs.bound.push(node);
1770        }
1771        self
1772    }
1773
1774    /// A drag started on it (the platform recognizes it).
1775    fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1776        self.on(
1777            EventKind::PanStart,
1778            events::typed(listener.into_listener(), events::pan),
1779        )
1780    }
1781
1782    /// The drag ended, with its velocity.
1783    fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1784        self.on(
1785            EventKind::PanEnd,
1786            events::typed(listener.into_listener(), events::pan),
1787        )
1788    }
1789
1790    /// A pinch started (its scale).
1791    fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1792        self.on(
1793            EventKind::PinchStart,
1794            events::typed(listener.into_listener(), events::pinch),
1795        )
1796    }
1797
1798    /// The pinch ended.
1799    fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1800        self.on(
1801            EventKind::PinchEnd,
1802            events::typed(listener.into_listener(), events::pinch),
1803        )
1804    }
1805
1806    /// A two-finger rotation started (its angle).
1807    fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1808        self.on(
1809            EventKind::RotationStart,
1810            events::typed(listener.into_listener(), events::rotation),
1811        )
1812    }
1813
1814    /// The rotation ended.
1815    fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1816        self.on(
1817            EventKind::RotationEnd,
1818            events::typed(listener.into_listener(), events::rotation),
1819        )
1820    }
1821
1822    /// An assistive technology performed an action (its name).
1823    fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
1824        self.on(
1825            EventKind::AccessibilityAction,
1826            events::typed(listener.into_listener(), events::action),
1827        )
1828    }
1829
1830    /// Handles native event `kind` with its raw payload (the element
1831    /// listens to it).
1832    fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
1833        self.node().handlers.push((kind, listener.into_listener()));
1834        self
1835    }
1836
1837    /// Presses also count this far outside it.
1838    fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1839        super::host::bind_prop(self.node(), insets, Prop::HitSlop);
1840        self
1841    }
1842
1843    /// Where the view goes as a link, carried to the platform as data
1844    /// ([`Prop::Href`]). `nsh-base`'s `Link` sets it from its `href`;
1845    /// apps use `Link`.
1846    #[doc(hidden)]
1847    fn __link_href(mut self, href: impl IntoReactive<Option<SharedString>>) -> Self {
1848        super::host::bind_prop(self.node(), href, |href: Option<SharedString>| {
1849            Prop::Href(href.map(|href| href.to_arc()))
1850        });
1851        self
1852    }
1853
1854    /// How long a press must last to be a long press, in milliseconds.
1855    fn long_press_delay(mut self, ms: f32) -> Self {
1856        super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
1857        self
1858    }
1859
1860    /// The press ripple (Android).
1861    fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
1862        super::host::set(self.node(), Prop::Ripple(Some(ripple)));
1863        self
1864    }
1865
1866    /// The elevation shadow (Android).
1867    fn elevation(mut self, elevation: impl Into<Points>) -> Self {
1868        super::host::set(self.node(), Prop::Elevation(elevation.into()));
1869        self
1870    }
1871
1872    /// The system material of a backdrop blur (iOS).
1873    fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
1874        super::host::set(self.node(), Prop::BackdropMaterial(material));
1875        self
1876    }
1877
1878    /// The native material the view draws with on macOS
1879    /// (`macos={{ backdrop }}`): an `NSVisualEffectView`, or none.
1880    fn macos_backdrop(mut self, backdrop: impl IntoReactive<Option<crate::MacOsBackdrop>>) -> Self {
1881        super::host::bind_prop(self.node(), backdrop, Prop::MacOsBackdrop);
1882        self
1883    }
1884
1885    /// The id UI tests find it by.
1886    fn test_id(mut self, id: &str) -> Self {
1887        super::host::set(self.node(), Prop::TestId(Some(id.into())));
1888        self
1889    }
1890
1891    /// The HTML element the web draws the view as (a paragraph, a
1892    /// landmark, a list), for search engines and readers of the page's
1893    /// markup, where `role` cannot say it: headings are
1894    /// `role(AccessibilityRole::Header)` with a level, links `Link`s. The
1895    /// other platforms ignore it.
1896    fn web_element(mut self, element: crate::WebElement) -> Self {
1897        super::host::set(self.node(), Prop::WebElement(Some(element)));
1898        self
1899    }
1900
1901    /// Whether a desktop press drags the window and a double click follows
1902    /// the system's title-bar behavior. The nearest explicit value wins;
1903    /// inputs and press/touch handlers inside a drag region stay interactive.
1904    /// On the native desktop backends (AppKit, Win32 and GTK), background
1905    /// clicks reach the app on release, including ancestor press handlers;
1906    /// dragging does not deliver a click.
1907    /// Set false on a child to exclude it from its parent's drag region.
1908    fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
1909        super::host::bind_prop(self.node(), enabled, |enabled| {
1910            Prop::WindowDrag(Some(enabled))
1911        });
1912        self
1913    }
1914
1915    /// Makes the view one of the system's window buttons in a title bar the
1916    /// app draws (TS: `desktop={{ windowControl }}`): the platform hit-tests
1917    /// it as that button (the snap layouts over a maximize button on
1918    /// Windows) and carries out its press.
1919    fn window_control(mut self, control: crate::desktop::WindowControl) -> Self {
1920        super::host::set(self.node(), Prop::WindowControl(Some(control)));
1921        self
1922    }
1923
1924    /// Pressing the view resizes a frameless window by `edge` (TS:
1925    /// `desktop={{ windowResize }}`).
1926    fn window_resize(mut self, edge: crate::desktop::ResizeEdge) -> Self {
1927        super::host::set(self.node(), Prop::WindowResize(Some(edge)));
1928        self
1929    }
1930
1931    /// Whether the view is a stop of the keyboard focus (Tab): true makes
1932    /// any view one, whether or not it takes presses (a component that
1933    /// takes its keys while focused, through `on_focus` / `on_blur` and the
1934    /// keymap, without taking the presses of a pressable around it); false
1935    /// leaves a view that takes presses to the pointer, as a backdrop that
1936    /// closes a popover is. Unset, the views that take presses are stops
1937    /// ([`crate::ViewProps::focus_stop`]).
1938    fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
1939        super::host::bind_prop(self.node(), focusable, |focusable| {
1940            Prop::Focusable(Some(focusable))
1941        });
1942        self
1943    }
1944
1945    /// `nativeID`: names the view for others: inputs find an input accessory
1946    /// by it, and the embedding app a scroll view it watches (`watchScroll`).
1947    fn native_id(mut self, id: &str) -> Self {
1948        super::host::set(self.node(), Prop::NativeId(Some(id.into())));
1949        self
1950    }
1951
1952    /// Styles while pressed (native: nothing runs).
1953    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1954        let s = f(StyleRefinement::default());
1955        self.style().extend_as(Variant::ACTIVE, s);
1956        self
1957    }
1958
1959    /// Styles while a pointer hovers it (iPad, Mac, mice).
1960    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1961        let s = f(StyleRefinement::default());
1962        self.style().extend_as(Variant::HOVER, s);
1963        self
1964    }
1965
1966    /// Styles while focused.
1967    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1968        let s = f(StyleRefinement::default());
1969        self.style().extend_as(Variant::FOCUS, s);
1970        self
1971    }
1972
1973    /// Styles while focused and showing it (Tailwind's `focus-visible:`;
1974    /// TS: `focusVisibleStyle`): the keyboard moved the focus there, or it
1975    /// is an input that edits. Focus a press gave shows [`Self::focus`]'s
1976    /// styles only: the ring for keyboard users goes here.
1977    fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1978        let s = f(StyleRefinement::default());
1979        self.style().extend_as(Variant::FOCUS_VISIBLE, s);
1980        self
1981    }
1982
1983    /// Styles while it or an element inside it is focused (Tailwind's
1984    /// `focus-within:`; TS: `focusWithinStyle`): a field's frame ringed
1985    /// while the input in it edits. An overlay's content is inside the
1986    /// element the overlay is in.
1987    fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1988        let s = f(StyleRefinement::default());
1989        self.style().extend_as(Variant::FOCUS_WITHIN, s);
1990        self
1991    }
1992
1993    /// Styles while [`Interactive::disabled`] (Tailwind's `disabled:`).
1994    fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1995        let s = f(StyleRefinement::default());
1996        self.style().extend_as(Variant::DISABLED, s);
1997        self
1998    }
1999
2000    /// No presses nor press feedback; screen readers say it is disabled.
2001    fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2002        self.node().bind_attr(disabled, |a, disabled| {
2003            a.disabled = disabled;
2004            a.state.disabled = disabled;
2005        });
2006        self
2007    }
2008
2009    /// An app's style while selected (`accessibility_state` `selected`;
2010    /// TS: a `Button`'s `selectedStyle`), as `selected:` classes apply.
2011    fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
2012        Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
2013            super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
2014        });
2015        self
2016    }
2017
2018    /// An app's style while checked (`accessibility_state` `checked`, not
2019    /// mixed: a checkbox's, a switch's, a radio's), as `checked:` classes
2020    /// apply.
2021    fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
2022        Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
2023            super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
2024        });
2025        self
2026    }
2027
2028    /// An app's style while indeterminate (`accessibility_state` `checked`
2029    /// mixed: a checkbox's `indeterminate`), as `indeterminate:` classes
2030    /// apply.
2031    fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
2032        Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
2033            super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
2034        });
2035        self
2036    }
2037
2038    /// An app's style while expanded (`accessibility_state` `expanded`: a
2039    /// `Popover`'s or `Menu`'s trigger while its popup is open), as
2040    /// `aria-expanded:` classes apply.
2041    fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
2042        Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
2043            super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
2044        });
2045        self
2046    }
2047
2048    /// An app's style while a toggle button is on (`accessibility_state`
2049    /// `pressed`, not mixed), as `aria-pressed:` classes apply. Not
2050    /// `.active(..)`, a press in progress.
2051    fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
2052        Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
2053            super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
2054        });
2055        self
2056    }
2057
2058    /// Styles it as checked while `checked` holds (its `checked:` classes
2059    /// and [`Self::checked_style`]), as a part of a control that is: a
2060    /// switch's track and thumb, a checkbox's mark (`gpui-base`'s
2061    /// `SwitchThumb::new(checked)`). Screen readers hear it from the
2062    /// control alone, so the part is no second checkable element.
2063    fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
2064        self.node().bind_attr(checked, |a, checked| {
2065            project(a, crate::tailwind::state::CHECKED, checked)
2066        });
2067        self
2068    }
2069
2070    /// Styles it as indeterminate while `indeterminate` holds (its
2071    /// `indeterminate:` classes and [`Self::indeterminate_style`]), as a
2072    /// part of a control that is: a checkbox's indicator (`gpui-base`'s
2073    /// `CheckboxIndicator::state(CheckboxState::Indeterminate)`). Screen
2074    /// readers hear it from the control alone.
2075    fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
2076        self.node().bind_attr(indeterminate, |a, indeterminate| {
2077            project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
2078        });
2079        self
2080    }
2081
2082    /// Styles it as disabled while `disabled` holds (its `disabled:`
2083    /// classes and [`Self::disabled_style`]), as a part of a disabled
2084    /// control (`gpui-base`'s `SwitchThumb::disabled`). The control takes
2085    /// no presses and tells screen readers; the part keeps its own.
2086    fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2087        self.node().bind_attr(disabled, |a, disabled| {
2088            project(a, crate::tailwind::state::DISABLED, disabled)
2089        });
2090        self
2091    }
2092
2093    /// Styles it as focused while `focused` holds (its `focus:` classes
2094    /// and focus styles), as the part the keyboard is on inside a control
2095    /// that keeps the focus itself: the cell of a one-time-code input that
2096    /// takes the next character, the highlighted option of a list (NSH
2097    /// has no active descendant). The platform's focus stays where it is.
2098    /// While the focus shows (the control's `focus-visible:`) the part
2099    /// shows it too, so `focus-visible:` on it is the cursor the keyboard
2100    /// moves and stays off after a press.
2101    fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
2102        self.node().bind_attr(focused, |a, focused| {
2103            project(a, crate::tailwind::state::FOCUSED, focused)
2104        });
2105        self
2106    }
2107
2108    /// Gives it the boolean `data-*` attribute `name` (without `data-`)
2109    /// while `on` holds, as Tailwind's `data-<name>:` variant reads it: its
2110    /// `data-<name>:` classes apply, and with `group` the
2111    /// `group-data-<name>:` classes inside it (a calendar's day at the
2112    /// start of a range: `project_data("range-start", ..)`). For what a
2113    /// component's part shows beyond the states screen readers hear; the
2114    /// attribute tells them nothing. A view whose classes read none of its
2115    /// attributes sends nothing when they change.
2116    fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
2117        self.node().bind_attr(on, move |a, on| {
2118            let at = a.projected_data.binary_search(&name);
2119            match (at, on) {
2120                (Err(i), true) => a.projected_data.insert(i, name),
2121                (Ok(i), false) => {
2122                    a.projected_data.remove(i);
2123                }
2124                _ => {}
2125            }
2126        });
2127        self
2128    }
2129}
2130
2131/// Sets or clears `bit` of the states an element shows as a part.
2132fn project(a: &mut Attrs, bit: u16, on: bool) {
2133    if on {
2134        a.projected_states |= bit;
2135    } else {
2136        a.projected_states &= !bit;
2137    }
2138}
2139
2140macro_rules! element {
2141    ($(#[$doc:meta])* $name:ident) => {
2142        $(#[$doc])*
2143        #[derive(Clone)]
2144        pub struct $name(ElNode);
2145
2146        impl Element for $name {
2147            fn node(&mut self) -> &mut ElNode {
2148                &mut self.0
2149            }
2150        }
2151
2152        impl IntoElement for $name {
2153            fn into_element(self) -> AnyElement {
2154                AnyElement(self.0)
2155            }
2156        }
2157
2158        impl Accessible for $name {}
2159
2160        impl IntoTooltip for $name {
2161            fn apply_tooltip(self, node: &mut ElNode) {
2162                self.into_element().apply_tooltip(node);
2163            }
2164        }
2165    };
2166}
2167
2168element! {
2169    /// A view (`<view>`), made by [`view`].
2170    View
2171}
2172
2173element! {
2174    /// A text block (`<text>`), made by [`text`].
2175    Text
2176}
2177
2178element! {
2179    /// An image (`<image>`), made by [`image`].
2180    Image
2181}
2182
2183element! {
2184    /// A slot's node as a view places it ([`ParentElement::slot`]):
2185    /// style it like a view; its children are the app's.
2186    SlotElement
2187}
2188
2189element! {
2190    /// A list as a view lays it out ([`ParentElement::list`]).
2191    ListElement
2192}
2193
2194impl Interactive for View {}
2195impl ParentElement for View {}
2196
2197impl View {
2198    /// Its frame follows the element carrying `target` (a tab list's
2199    /// indicator on the selected tab): along the main axis of its parent
2200    /// (vertical in a flex column, else horizontal) it spans that element's
2201    /// frame, inside its own margins on that axis, wherever the element is
2202    /// inside its parent; across it, its style places it (`bottom(px(0.))`
2203    /// and a height for an underline, top and bottom insets for a pill),
2204    /// so its style makes it [`Styled::absolute`]. The core places it after
2205    /// each layout, with no layout of its own and no JS: following another
2206    /// element changes its frame alone, and a layout that moves the element
2207    /// moves it in the same batch. While `target` is `None`, or no laid
2208    /// out element carries it, its style alone places it; hidden
2209    /// (`display: none`) and shown again, it is placed at once. A view
2210    /// that follows nothing costs no work after layout.
2211    pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2212        let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2213            t.and_then(|t| t.target()).map(super::FollowTarget)
2214        });
2215        super::host::bind_prop(&mut self.0, target, Prop::Follow);
2216        self
2217    }
2218
2219    /// How it moves when [`Self::follow`] names another element: natively,
2220    /// with `transition` as a layout animation of its own frame alone (the
2221    /// rest of that commit changes at once); `None` (the default) jumps.
2222    /// Following an element for the first time, and a layout that moves
2223    /// it, place it at once.
2224    pub fn follow_transition(
2225        mut self,
2226        transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2227    ) -> Self {
2228        super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2229        self
2230    }
2231}
2232impl Interactive for SlotElement {}
2233impl Interactive for Text {}
2234impl Interactive for Image {}
2235
2236/// A text's children are its spans, as nested `<text>`s in JS: texts with
2237/// styles and presses of their own (a link inside a sentence), strings,
2238/// and views and images placed inline, wrapping with the words. The core
2239/// merges them into one paragraph.
2240impl ParentElement for Text {
2241    fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2242        let at = self.0.children.len();
2243        child.__push_into(&mut self.0.children);
2244        for el in &mut self.0.children[at..] {
2245            *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2246        }
2247        self
2248    }
2249
2250    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2251        self.0
2252            .children
2253            .extend(children.into_iter().map(|c| span(c.into_element().0)));
2254        self
2255    }
2256}
2257
2258/// A child of a text: a bare string (a text with nothing of its own) is a
2259/// piece of its content, anything else a span or an inline element.
2260fn span(mut el: ElNode) -> ElNode {
2261    if el.tag == Tag::Text
2262        && matches!(el.kind, ElKind::Plain)
2263        && el.key.is_none()
2264        && el.children.is_empty()
2265        && el.handlers.is_empty()
2266        && el.style.is_empty()
2267        && el.attrs == Attrs::default()
2268        && !el.is_bound()
2269    {
2270        el.kind = ElKind::Raw;
2271    }
2272    el
2273}
2274
2275impl Text {
2276    /// The highlight of its selection, when it is selectable.
2277    pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2278        super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2279            Prop::SelectionColor(Some(Color::from(c)))
2280        });
2281        self
2282    }
2283
2284    /// Shrinks the font, down to `min_scale` of it, to fit its lines.
2285    pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2286        super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2287        super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2288        self
2289    }
2290
2291    /// Whether its fonts follow the system's text size (true by default;
2292    /// TS: `allowFontScaling`).
2293    pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2294        super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2295        self
2296    }
2297
2298    /// At most this multiple of its fonts' sizes with the system's text
2299    /// size (TS: `maxFontSizeMultiplier`; 0: no limit).
2300    pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2301        super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2302        self
2303    }
2304}
2305
2306impl Image {
2307    /// Shown until it loads (a URL, an `asset:/` URI or an
2308    /// [`super::ImageAsset`]).
2309    pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2310        super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2311            Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2312                uri: src.uri.to_arc(),
2313                size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2314                scales: src.scales,
2315                data: src.data,
2316            })))
2317        });
2318        self
2319    }
2320
2321    /// Draws its opaque pixels in `color` (a template image, an icon).
2322    pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2323        Styled::tint_color(self, color)
2324    }
2325
2326    /// Blurs it.
2327    pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2328        super::host::set(
2329            &mut self.0,
2330            Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2331        );
2332        self
2333    }
2334
2335    /// Fades it in over `ms` milliseconds once loaded.
2336    pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2337        super::host::bind_prop(&mut self.0, ms, |ms| {
2338            Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
2339        });
2340        self
2341    }
2342
2343    /// It loaded: its size in pixels.
2344    pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
2345        self.on(
2346            EventKind::Load,
2347            events::typed(listener.into_listener(), events::pixel_size),
2348        )
2349    }
2350
2351    /// It failed to load (the message).
2352    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
2353        self.on(
2354            EventKind::Error,
2355            events::typed(listener.into_listener(), events::message),
2356        )
2357    }
2358
2359    /// It started loading.
2360    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
2361        self.on(
2362            EventKind::LoadStart,
2363            events::typed(listener.into_listener(), events::unit),
2364        )
2365    }
2366
2367    /// It finished loading, or failed.
2368    pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
2369        self.on(
2370            EventKind::LoadEnd,
2371            events::typed(listener.into_listener(), events::unit),
2372        )
2373    }
2374
2375    /// Its download went on: bytes so far and in all (at most every 100
2376    /// ms; none for images already in memory).
2377    pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
2378        self.on(
2379            EventKind::Progress,
2380            events::typed(listener.into_listener(), events::image_progress),
2381        )
2382    }
2383}
2384
2385impl super::Scrollable for ListElement {}
2386
2387impl super::ListLayout for ListElement {
2388    fn config(&mut self) -> &mut ListConfig {
2389        match &mut self.0.kind {
2390            ElKind::List(list) => &mut list.config,
2391            _ => unreachable!("a ListElement is a list"),
2392        }
2393    }
2394
2395    fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
2396        &mut self.0.bound_list
2397    }
2398}
2399
2400/// A named slot (an `Option<Slot>` prop): `Some` while the app passes
2401/// content for it. Placed with [`ParentElement::slot`].
2402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2403pub struct Slot {
2404    name: &'static str,
2405}
2406
2407impl Slot {
2408    pub(crate) fn new(name: &'static str) -> Self {
2409        Self { name }
2410    }
2411
2412    /// Its name (its prop's, in JS).
2413    pub fn name(&self) -> &'static str {
2414        self.name
2415    }
2416
2417    /// The slot's node, to style and place (its children are the app's).
2418    pub fn element(self) -> SlotElement {
2419        let mut node = ElNode::new(Tag::View);
2420        node.kind = ElKind::Slot(self.name);
2421        SlotElement(node)
2422    }
2423}
2424
2425/// The app's virtualized rows (an `Items` prop): in JS the component takes
2426/// `each` and a row renderer like `List`. Placed with
2427/// [`ParentElement::list`].
2428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2429pub struct Items {
2430    name: &'static str,
2431}
2432
2433impl Items {
2434    #[doc(hidden)]
2435    pub const fn __new(name: &'static str) -> Self {
2436        Self { name }
2437    }
2438}
2439
2440/// A piece of the app's content to place: one JSX child
2441/// ([`ParentElement::children_each`]) or a list row's content
2442/// ([`ParentElement::list`]).
2443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2444pub struct Child(ChildRef);
2445
2446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2447enum ChildRef {
2448    Js(NodeId),
2449    Row,
2450}
2451
2452impl Child {
2453    pub(crate) fn js(id: NodeId) -> Self {
2454        Self(ChildRef::Js(id))
2455    }
2456
2457    pub(crate) fn row() -> Self {
2458        Self(ChildRef::Row)
2459    }
2460}
2461
2462impl IntoElement for Child {
2463    fn into_element(self) -> AnyElement {
2464        let mut node = ElNode::new(Tag::View);
2465        node.kind = match self.0 {
2466            ChildRef::Js(id) => ElKind::JsChild(id),
2467            ChildRef::Row => ElKind::Children,
2468        };
2469        AnyElement(node)
2470    }
2471}
2472
2473/// A view.
2474pub fn view() -> View {
2475    View(ElNode::new(Tag::View))
2476}
2477
2478/// A text block showing `content`, then its children (spans:
2479/// [`ParentElement`] for [`Text`]).
2480pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2481    let mut node = ElNode::new(Tag::Text);
2482    match content.into_reactive() {
2483        Reactive::Static(content) => node.text = Some(content),
2484        Reactive::Bound(content) => {
2485            node.text = Some(SharedString::default());
2486            node.bound_text = Some(content);
2487        }
2488    }
2489    Text(node)
2490}
2491
2492/// An image loading `src`: a URL, a file path or `asset:/` URI, or an
2493/// [`super::ImageAsset`] (`asset!("logo@2x.png")`), which lays out at its
2494/// natural size before it loads.
2495pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2496    let mut node = ElNode::new(Tag::Image);
2497    node.bind_attr(src, |a, src| a.src = Some(src));
2498    Image(node)
2499}
2500
2501/// The JSX children of a component (a `Children` prop): placed where the
2502/// view puts it, among the view's own children.
2503#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2504pub struct Children {
2505    present: bool,
2506}
2507
2508impl Children {
2509    pub(crate) fn new(present: bool) -> Self {
2510        Self { present }
2511    }
2512
2513    /// The app passed none.
2514    pub fn is_empty(&self) -> bool {
2515        !self.present
2516    }
2517}
2518
2519impl IntoElement for Children {
2520    fn into_element(self) -> AnyElement {
2521        let mut node = ElNode::new(Tag::View);
2522        node.kind = ElKind::Children;
2523        AnyElement(node)
2524    }
2525}
2526
2527/// Another component in a view ([`Component::element`]). Its styles go
2528/// after the component's own, like an app's classes, and so do its inline
2529/// style, animated values and insets ([`Element`]'s), on the component's
2530/// root, which also takes its [`Self::test_id`] over its own; its state
2531/// styles ([`Self::active`], [`Self::hover`], [`Self::focus`],
2532/// [`Self::disabled_style`], [`Styled::selected`], [`Styled::checked`])
2533/// follow the states of that root, as an app's `active:` / `hover:`
2534/// classes on a TSX component do. It hears and is to
2535/// assistive technologies what the component says (its events and props):
2536/// it is not [`Interactive`] or [`Accessible`]. The element a
2537/// `#[component]`'s constructor makes (`button()`) wraps one
2538/// ([`ComponentBuilder`]).
2539pub struct ComponentElement<C: Component> {
2540    node: ElNode,
2541    _component: PhantomData<fn() -> C>,
2542}
2543
2544impl<C: Component> ComponentElement<C> {
2545    /// The element of `C` given `props`: what a component's constructor
2546    /// (`button()`) and [`Component::element`] start from.
2547    #[doc(hidden)]
2548    pub fn __new(props: C::Props) -> Self {
2549        Self::new(props)
2550    }
2551
2552    /// Its props, for the setters a `#[component]` makes on its element.
2553    #[doc(hidden)]
2554    pub fn __props_mut(&mut self) -> &mut C::Props {
2555        match &mut self.node.kind {
2556            ElKind::Component(c) => c
2557                .props
2558                .as_any_mut()
2559                .downcast_mut::<C::Props>()
2560                .expect("a component element holds its component's props"),
2561            _ => unreachable!("a component element is a component's"),
2562        }
2563    }
2564
2565    pub(crate) fn new(props: C::Props) -> Self {
2566        let mut node = ElNode::new(Tag::View);
2567        node.kind = ElKind::Component(ComponentEl {
2568            name: super::component::name_of::<C>(),
2569            make: super::component::make_instance::<C>,
2570            spec: ComponentSpec::of::<C>,
2571            props: Box::new(props),
2572            on_event: Vec::new(),
2573        });
2574        Self {
2575            node,
2576            _component: PhantomData,
2577        }
2578    }
2579
2580    /// Fills its slot `slot` (its prop's JS name: `header`) with `content`
2581    /// (in place of what filled it): the component's view places it as it
2582    /// is where it places the slot, with no node around it (a node of its
2583    /// own only where the view styles the slot).
2584    pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2585        self.node
2586            .children
2587            .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2588        let mut fill = ElNode::new(Tag::View);
2589        fill.kind = ElKind::Fill(slot);
2590        fill.children.push(content.into_element().0);
2591        self.node.children.push(fill);
2592        self
2593    }
2594
2595    /// Fills its `Items` prop with rows of this view (TS: `each` and the
2596    /// row renderer, `keyExtractor`, `header`, ...): the rows,
2597    /// their keys, header, footer, empty view, separators, sticky rows,
2598    /// viewability, the refresh and the end reached are `list`'s, rendered
2599    /// and handled by this component; the layout and the styles are the
2600    /// placing component's ([`ParentElement::list`]), so `list`'s own are
2601    /// left out.
2602    pub fn items(mut self, list: super::VirtualList) -> Self {
2603        match <C::Props as super::Props>::ITEMS {
2604            Some(name) => self.node.children.push(list.into_items(name)),
2605            None => {
2606                log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2607            }
2608        }
2609        self
2610    }
2611
2612    /// Styles while its root is pressed (Tailwind's `active:`; TS: an
2613    /// `active:` class or `activeStyle` given the component), applied
2614    /// natively. The root follows presses when it handles them (a
2615    /// [`Interactive::on_press`] of the component's view).
2616    pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2617        let s = f(StyleRefinement::default());
2618        self.node.style.extend_as(Variant::ACTIVE, s);
2619        self
2620    }
2621
2622    /// Styles while a pointer hovers its root (`hover:`).
2623    pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2624        let s = f(StyleRefinement::default());
2625        self.node.style.extend_as(Variant::HOVER, s);
2626        self
2627    }
2628
2629    /// Styles while its root has focus (`focus:`).
2630    pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2631        let s = f(StyleRefinement::default());
2632        self.node.style.extend_as(Variant::FOCUS, s);
2633        self
2634    }
2635
2636    /// Styles while its root has focus and shows it (`focus-visible:`):
2637    /// the keyboard moved the focus there.
2638    pub fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2639        let s = f(StyleRefinement::default());
2640        self.node.style.extend_as(Variant::FOCUS_VISIBLE, s);
2641        self
2642    }
2643
2644    /// Styles while its root or an element inside it has focus
2645    /// (`focus-within:`).
2646    pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2647        let s = f(StyleRefinement::default());
2648        self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
2649        self
2650    }
2651
2652    /// Styles while its root is disabled (`disabled:`): the component's
2653    /// view disables it ([`Interactive::disabled`], a `disabled` prop).
2654    pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2655        let s = f(StyleRefinement::default());
2656        self.node.style.extend_as(Variant::DISABLED, s);
2657        self
2658    }
2659
2660    /// The id UI tests find its root by (TS: `testID` given the component),
2661    /// as [`Interactive::test_id`] names a view.
2662    pub fn test_id(mut self, id: &str) -> Self {
2663        super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
2664        self
2665    }
2666
2667    /// Puts `handle` on this component: its updates go to it.
2668    pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2669        self.node.attrs.element_ref = handle.element().target();
2670        self
2671    }
2672
2673    /// Handles its events (they then do not reach the app). Given several
2674    /// times, every listener hears them, in order. The element a
2675    /// `#[component]`'s constructor makes has a listener method per event
2676    /// instead (`.on_press(..)`: [`ComponentBuilder`]); this stays for
2677    /// components implemented by hand.
2678    pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
2679        let listener = listener.into_listener();
2680        if let ElKind::Component(c) = &mut self.node.kind {
2681            c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
2682                if let Some(event) = event.downcast_ref::<C::Event>() {
2683                    inner(event);
2684                }
2685            }));
2686        }
2687        self
2688    }
2689
2690    /// Handles the events `pick` picks, with the data it gives: the listener
2691    /// method of one event (`on_press`) that `#[derive(Event)]` generates
2692    /// calls it.
2693    #[doc(hidden)]
2694    pub fn __on_variant<T: ?Sized + 'static, M>(
2695        self,
2696        pick: fn(&C::Event) -> Option<&T>,
2697        listener: impl IntoListener<T, M>,
2698    ) -> Self {
2699        let listener = listener.into_listener();
2700        self.on_event(listener.wrap(move |inner, event: &C::Event| {
2701            if let Some(data) = pick(event) {
2702                inner(data);
2703            }
2704        }))
2705    }
2706}
2707
2708/// The element of a `#[component]`, as its constructor makes it: a
2709/// component is made and set up in Rust as a primitive is (`view()`),
2710/// as JSX does in TSX. `#[component] fn Picker` makes `picker()` (the
2711/// function's name in snake case), which returns a `PickerElement` with
2712/// each prop at its default and
2713///
2714/// - a setter per prop, named as its field (`.disabled(..)`): a value, a
2715///   signal, a memo or a prop of the field's type, or a closure returning
2716///   one (bound); an `Option<T>` prop takes a `T` (`.label("Pick one")`),
2717///   a slot the content to fill it with (`.header(text(..))`), the
2718///   children are its [`ParentElement::child`]ren;
2719/// - a listener method per event, named as its TSX handler in snake case
2720///   (`onSelect` is `.on_select(..)`): a unit variant's takes
2721///   `move || ..`, a one-field variant's `move |value: &T| ..`, a
2722///   named-field variant's the event itself;
2723/// - styles ([`Styled`]: they go on the component's root), with this
2724///   trait's for the root's states, and a
2725///   [`ComponentRef`](super::ComponentRef).
2726///
2727/// A prop's setter comes before an element method of the same name (a
2728/// component's `selected` prop before [`Styled::selected`], its `size`
2729/// before [`Styled::size`]; call those as `Styled::selected(element, ..)`).
2730///
2731/// ```
2732/// use nsh_core::prelude::*;
2733///
2734/// /// The props of [`Picker`].
2735/// #[derive(Clone, PartialEq, Props)]
2736/// pub struct PickerProps {
2737///     /// The options.
2738///     pub options: Prop<Vec<SharedString>>,
2739///     /// No presses.
2740///     #[prop(default)]
2741///     pub disabled: Prop<bool>,
2742///     /// What screen readers say.
2743///     pub label: Prop<Option<SharedString>>,
2744/// }
2745///
2746/// /// What a [`Picker`] reports.
2747/// #[derive(Event)]
2748/// pub enum PickerEvent {
2749///     /// Pressed.
2750///     Press,
2751///     /// An option was picked: its index.
2752///     Select(u32),
2753/// }
2754///
2755/// /// Picks an option.
2756/// #[component]
2757/// pub fn Picker(props: PickerProps, cx: Scope<PickerEvent>) -> impl IntoElement {
2758///     view()
2759///         .disabled(props.disabled)
2760///         .on_press(move || cx.emit(PickerEvent::Select(0)))
2761/// }
2762///
2763/// #[component]
2764/// pub fn Form() -> impl IntoElement {
2765///     let busy = signal(false);
2766///     let picked = signal(None::<u32>);
2767///     view().child(
2768///         picker()
2769///             .options(vec![SharedString::from("Tea"), "Coffee".into()])
2770///             .disabled(move || busy.get())
2771///             .label("Drink")
2772///             .on_press(move || log::info!("pressed"))
2773///             .on_select(move |&index: &u32| picked.set(Some(index)))
2774///             .px_4()
2775///             .active(|s| s.opacity(0.6)),
2776///     )
2777/// }
2778/// ```
2779pub trait ComponentBuilder: Element {
2780    /// Its component.
2781    type Component: Component;
2782
2783    /// The element it builds.
2784    #[doc(hidden)]
2785    fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
2786
2787    /// Styles while its root is pressed (Tailwind's `active:`; TS: an
2788    /// `active:` class or `activeStyle` given the component), applied
2789    /// natively. The root follows presses when it handles them (a
2790    /// [`Interactive::on_press`] of the component's view).
2791    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2792        let s = f(StyleRefinement::default());
2793        self.node().style.extend_as(Variant::ACTIVE, s);
2794        self
2795    }
2796
2797    /// Styles while a pointer hovers its root (`hover:`).
2798    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2799        let s = f(StyleRefinement::default());
2800        self.node().style.extend_as(Variant::HOVER, s);
2801        self
2802    }
2803
2804    /// Styles while its root has focus (`focus:`).
2805    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2806        let s = f(StyleRefinement::default());
2807        self.node().style.extend_as(Variant::FOCUS, s);
2808        self
2809    }
2810
2811    /// Styles while its root has focus and shows it (`focus-visible:`):
2812    /// the keyboard moved the focus there.
2813    fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2814        let s = f(StyleRefinement::default());
2815        self.node().style.extend_as(Variant::FOCUS_VISIBLE, s);
2816        self
2817    }
2818
2819    /// Styles while its root or an element inside it has focus
2820    /// (`focus-within:`).
2821    fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2822        let s = f(StyleRefinement::default());
2823        self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
2824        self
2825    }
2826
2827    /// Styles while its root is disabled (`disabled:`): the component's
2828    /// view disables it ([`Interactive::disabled`], a `disabled` prop).
2829    fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2830        let s = f(StyleRefinement::default());
2831        self.node().style.extend_as(Variant::DISABLED, s);
2832        self
2833    }
2834
2835    /// Puts `handle` on this component: its updates go to it.
2836    fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
2837        self.__element().node.attrs.element_ref = handle.element().target();
2838        self
2839    }
2840}
2841
2842impl<C: Component> Element for ComponentElement<C> {
2843    fn node(&mut self) -> &mut ElNode {
2844        &mut self.node
2845    }
2846}
2847
2848/// The content of a nested component: `.child(..)` / `.children(..)` are
2849/// its `Children`, [`ComponentElement::fill`] its slots, placed where its
2850/// view places the app's.
2851impl<C: Component> ParentElement for ComponentElement<C> {}
2852
2853impl<C: Component> IntoElement for ComponentElement<C> {
2854    fn into_element(self) -> AnyElement {
2855        AnyElement(self.node)
2856    }
2857}
2858
2859#[cfg(test)]
2860mod file_listener_tests {
2861    use std::cell::Cell;
2862
2863    use super::*;
2864
2865    #[test]
2866    fn file_drag_enter_keeps_all_original_listener_forms() {
2867        let calls = Rc::new(Cell::new(0));
2868        let a = calls.clone();
2869        let b = calls.clone();
2870        let c = calls.clone();
2871        let d = calls.clone();
2872        let unit: Listener<()> = (move |_: &()| c.set(c.get() + 1)).into_listener();
2873        let nodes = [
2874            view().on_file_drag_enter(move || a.set(a.get() + 1)),
2875            view().on_file_drag_enter(move |_: &()| b.set(b.get() + 1)),
2876            view().on_file_drag_enter(unit),
2877            view().on_file_drag_enter(move |e: &events::FileDragEvent| {
2878                assert_eq!(e.uris, ["file:///tmp/a%20b.png"]);
2879                assert_eq!(e.mime_types, ["image/png"]);
2880                d.set(d.get() + 1);
2881            }),
2882        ];
2883        let payload = EventPayload::FileDrop(vec!["file:///tmp/a%20b.png".into()]);
2884        for mut node in nodes {
2885            let listener = node
2886                .node()
2887                .handlers
2888                .iter()
2889                .find(|(kind, _)| *kind == EventKind::FileDragEnter)
2890                .unwrap();
2891            listener.1.call(&payload);
2892        }
2893        assert_eq!(calls.get(), 4);
2894    }
2895}