Skip to main content

nsh_core/element/
builder.rs

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