Skip to main content

nsh_core/element/
builder.rs

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