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