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