1use 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, HoverEvent, Hsla, ImageSource,
15 ListContentStyle, NativeProp, NodeId, PointerEvents, Points, Prop, Size, Tag, TouchEvent,
16 geometry::Radians, style::Color,
17};
18
19pub struct Listener<E: ?Sized> {
25 f: Rc<dyn Fn(&E)>,
26 owner: super::Owner,
27}
28
29impl<E: ?Sized + 'static> Listener<E> {
30 pub(crate) fn noop() -> Self {
32 Self::new(Rc::new(|_| {}))
33 }
34
35 fn new(f: Rc<dyn Fn(&E)>) -> Self {
36 Self {
37 f,
38 owner: super::Owner::current_or_detached(),
39 }
40 }
41
42 pub(crate) fn call(&self, event: &E) {
45 if self.owner == super::Owner::detached() {
46 (self.f)(event);
47 } else if self.owner.is_live() {
48 self.owner.scope(|| (self.f)(event));
49 }
50 }
51
52 pub(crate) fn wrap<F: ?Sized>(self, f: impl Fn(&dyn Fn(&E), &F) + 'static) -> Listener<F> {
55 let inner = self.f;
56 Listener {
57 f: Rc::new(move |event: &F| f(&*inner, event)),
58 owner: self.owner,
59 }
60 }
61}
62
63impl<E: 'static> Listener<E> {
64 pub fn map<F: ?Sized + 'static>(self, f: impl Fn(&F) -> E + 'static) -> Listener<F> {
66 self.wrap(move |inner, event: &F| inner(&f(event)))
67 }
68}
69
70impl<E: ?Sized + 'static, F: Fn(&E) + 'static> From<F> for Listener<E> {
72 fn from(f: F) -> Self {
73 Self::new(Rc::new(f))
74 }
75}
76
77#[diagnostic::on_unimplemented(
84 message = "`{Self}` is not a listener of `{E}`",
85 label = "not a listener of `{E}`",
86 note = "a listener is a closure `move |event: &{E}| ..` (`move || ..` for an event without data) or a `Listener<{E}>`"
87)]
88pub trait IntoListener<E: ?Sized, M> {
89 fn into_listener(self) -> Listener<E>;
91}
92
93#[doc(hidden)]
95pub struct OfEvent(());
96
97#[doc(hidden)]
100pub struct WithoutEvent(());
101
102impl<E: ?Sized> IntoListener<E, ()> for Listener<E> {
103 fn into_listener(self) -> Listener<E> {
104 self
105 }
106}
107
108impl<E: ?Sized + 'static, F: Fn(&E) + 'static> IntoListener<E, OfEvent> for F {
109 fn into_listener(self) -> Listener<E> {
110 Listener::new(Rc::new(self))
111 }
112}
113
114impl<F: Fn() + 'static> IntoListener<(), WithoutEvent> for F {
115 fn into_listener(self) -> Listener<()> {
116 Listener::new(Rc::new(move |_: &()| self()))
117 }
118}
119
120impl<E: ?Sized> Clone for Listener<E> {
121 fn clone(&self) -> Self {
122 Self {
123 f: self.f.clone(),
124 owner: self.owner,
125 }
126 }
127}
128
129pub(crate) trait AnyEvent: super::EventToJs {
132 fn as_any(&self) -> &dyn Any;
133}
134
135impl<E: Event> super::EventToJs for E {
136 fn name(&self) -> &'static str {
137 Event::name(self)
138 }
139
140 fn data_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
141 Event::data_js(self, host)
142 }
143
144 fn spread(&self) -> bool {
145 Event::spread(self)
146 }
147}
148
149impl<E: Event> AnyEvent for E {
150 fn as_any(&self) -> &dyn Any {
151 self
152 }
153}
154
155#[doc(hidden)]
157#[derive(Debug, Clone, Default, PartialEq)]
158pub struct Attrs {
159 pub(crate) disabled: bool,
160 pub(crate) accessible: Option<bool>,
161 pub(crate) label: Option<SharedString>,
162 pub(crate) hint: Option<SharedString>,
163 pub(crate) role: AccessibilityRole,
164 pub(crate) state: AccessibilityState,
165 pub(crate) value: Option<AccessibilityValue>,
166 pub(crate) pointer_events: PointerEvents,
167 pub(crate) number_of_lines: u32,
168 pub(crate) src: Option<super::ImageSrc>,
169 pub(crate) inset_padding: Option<EdgeInsets>,
170 pub(crate) inset_margin: Option<EdgeInsets>,
171 pub(crate) inline: Option<Arc<crate::StylePatch>>,
173 pub(crate) props: Vec<Prop>,
176 pub(crate) drawing: Option<Arc<crate::canvas::Drawing>>,
178 pub(crate) element_ref: Option<super::element_ref::RefTarget>,
181 pub(crate) animated: Vec<(crate::StyleDecl, super::LiveNode)>,
184 pub(crate) bound: Vec<super::LiveNode>,
186 pub(crate) class: Option<SharedString>,
189 pub(crate) selectable_view: bool,
191 pub(crate) projected_states: u8,
194 pub(crate) render: Option<super::renderer::RenderAt>,
197}
198
199impl Attrs {
200 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
202 use AccessibilityProp as A;
203 if self.disabled != old.disabled {
204 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
205 }
206 if self.accessible != old.accessible {
207 out.push(Prop::Accessibility(A::Accessible(self.accessible)));
208 }
209 if self.label != old.label {
210 out.push(Prop::Accessibility(A::Label(
211 self.label.as_ref().map(SharedString::to_arc),
212 )));
213 }
214 if self.hint != old.hint {
215 out.push(Prop::Accessibility(A::Hint(
216 self.hint.as_ref().map(SharedString::to_arc),
217 )));
218 }
219 if self.role != old.role {
220 out.push(Prop::Accessibility(A::Role(self.role)));
221 }
222 if self.state != old.state {
223 out.push(Prop::Accessibility(A::State(self.state)));
224 }
225 if self.value != old.value {
226 out.push(Prop::Accessibility(A::Value(self.value.clone())));
227 }
228 if self.pointer_events != old.pointer_events {
229 out.push(Prop::PointerEvents(self.pointer_events));
230 }
231 if self.number_of_lines != old.number_of_lines {
232 out.push(Prop::NumberOfLines(self.number_of_lines));
233 }
234 if self.src != old.src {
235 out.push(Prop::Source(self.src.as_ref().map(|src| ImageSource {
236 uri: src.uri.to_arc(),
237 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
238 scales: src.scales,
239 data: None,
240 })));
241 }
242 if self.inset_padding != old.inset_padding {
243 out.push(Prop::InsetPadding(self.inset_padding.unwrap_or_default()));
244 }
245 if self.inset_margin != old.inset_margin {
246 out.push(Prop::InsetMargin(self.inset_margin.unwrap_or_default()));
247 }
248 if self.selectable_view != old.selectable_view {
249 out.push(Prop::SelectableView(self.selectable_view));
250 }
251 if self.projected_states != old.projected_states {
252 out.push(Prop::ProjectedStates(self.projected_states));
253 }
254 for prop in &old.props {
257 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
258 && let Some(reset) = super::host::reset(prop)
259 {
260 out.push(reset);
261 }
262 }
263 for prop in &self.props {
264 if !old.props.contains(prop) {
265 out.push(prop.clone());
266 }
267 }
268 }
269}
270
271pub(crate) trait AnyProps {
273 fn as_any(&self) -> &dyn Any;
274 fn as_any_mut(&mut self) -> &mut dyn Any;
275 fn clone_box(&self) -> Box<dyn AnyProps>;
276}
277
278impl<P: Clone + 'static> AnyProps for P {
279 fn as_any(&self) -> &dyn Any {
280 self
281 }
282
283 fn as_any_mut(&mut self) -> &mut dyn Any {
284 self
285 }
286
287 fn clone_box(&self) -> Box<dyn AnyProps> {
288 Box::new(self.clone())
289 }
290}
291
292pub(crate) struct ComponentEl {
294 pub(crate) name: &'static str,
295 pub(crate) make: fn() -> Box<dyn AnyInstance>,
298 pub(crate) spec: fn() -> ComponentSpec,
300 pub(crate) props: Box<dyn AnyProps>,
301 pub(crate) on_event: Vec<Listener<dyn Any>>,
303}
304
305impl Clone for ComponentEl {
306 fn clone(&self) -> Self {
307 Self {
308 name: self.name,
309 make: self.make,
310 spec: self.spec,
311 props: self.props.clone_box(),
312 on_event: self.on_event.clone(),
313 }
314 }
315}
316
317pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
319
320#[derive(Clone, Copy)]
326pub struct Position {
327 index: super::reactive::Node,
328 count: super::reactive::Node,
329}
330
331impl Position {
332 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
335 Self { index, count }
336 }
337
338 pub(crate) fn fixed(index: usize, count: usize) -> Self {
340 Self::of(super::signal(index).node(), super::signal(count).node())
341 }
342
343 #[track_caller]
345 pub fn index(&self) -> usize {
346 self.index.with("a position", |i: &usize| *i)
347 }
348
349 #[track_caller]
351 pub fn count(&self) -> usize {
352 self.count.with("a position", |n: &usize| *n)
353 }
354
355 #[track_caller]
357 pub fn is_first(&self) -> bool {
358 self.index() == 0
359 }
360
361 #[track_caller]
363 pub fn is_last(&self) -> bool {
364 self.index() + 1 == self.count()
365 }
366}
367
368impl fmt::Debug for Position {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 let (index, count) = super::untracked(|| (self.index(), self.count()));
371 write!(f, "Position({index} of {count})")
372 }
373}
374
375#[doc(hidden)]
378#[derive(Debug, Clone, Copy, Default, PartialEq)]
379pub struct ListConfig {
380 pub(crate) estimated: Option<f32>,
381 pub(crate) columns: Option<u32>,
382 pub(crate) horizontal: Option<bool>,
383 pub(crate) inverted: Option<bool>,
384 pub(crate) scrollbar_visible: Option<bool>,
385 pub(crate) content: Option<ListContentStyle>,
386 pub(crate) follow_end: Option<f32>,
387 pub(crate) viewport: Option<crate::ListViewport>,
388}
389
390impl ListConfig {
391 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
393 if self.estimated != old.estimated {
394 out.push(Prop::EstimatedItemSize(Points(
395 self.estimated.unwrap_or(50.0),
396 )));
397 }
398 if self.columns != old.columns {
399 out.push(Prop::Columns(self.columns.unwrap_or(1)));
400 }
401 if self.horizontal != old.horizontal {
402 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
403 }
404 if self.inverted != old.inverted {
405 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
406 }
407 if self.scrollbar_visible != old.scrollbar_visible {
408 out.push(Prop::Scrollbar(self.scrollbar_visible.unwrap_or(true)));
409 }
410 if self.content != old.content {
411 out.push(Prop::ListContent(self.content.unwrap_or_default()));
412 }
413 if self.follow_end != old.follow_end {
414 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
415 }
416 if self.viewport != old.viewport {
417 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
418 }
419 }
420}
421
422#[derive(Clone)]
424pub(crate) struct ListEl {
425 pub(crate) name: &'static str,
426 pub(crate) config: ListConfig,
427 pub(crate) row: PlaceFn,
428}
429
430#[derive(Clone)]
432pub(crate) enum ElKind {
433 Plain,
434 Slot(&'static str),
436 Fill(&'static str),
439 Filled(&'static str),
442 Children,
444 JsChild(NodeId),
446 EachChild(PlaceFn),
448 List(Box<ListEl>),
450 VirtualList(Box<super::virtual_list::VirtualListEl>),
452 Raw,
455 Component(ComponentEl),
456 Region(super::flow::Region),
460 Keep,
463}
464
465#[doc(hidden)]
467#[derive(Clone)]
468pub struct ElNode {
469 pub(crate) tag: Tag,
470 pub(crate) key: Option<SharedString>,
471 pub(crate) text: Option<SharedString>,
473 pub(crate) attrs: Attrs,
474 pub(crate) style: StyleRefinement,
475 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
476 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
478 pub(crate) children: Vec<ElNode>,
479 pub(crate) kind: ElKind,
480 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
482 pub(crate) bound_attrs: Vec<BoundAttrs>,
484 pub(crate) bound_list: Vec<BoundListConfig>,
486}
487
488#[doc(hidden)]
490pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
491
492crate::static_reactive!(AccessibilityState: AccessibilityState);
493crate::static_reactive!(EdgeInsets: EdgeInsets);
494crate::static_reactive!(Style: Style);
495crate::static_reactive!(PointerEvents: PointerEvents);
496
497pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
499
500impl ElNode {
501 pub(crate) fn bind_attr<T: 'static>(
504 &mut self,
505 value: impl IntoReactive<T>,
506 apply: impl Fn(&mut Attrs, T) + 'static,
507 ) {
508 match value.into_reactive() {
509 Reactive::Static(v) => apply(&mut self.attrs, v),
510 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
511 }
512 }
513
514 pub(crate) fn is_bound(&self) -> bool {
516 self.bound_text.is_some()
517 || !self.bound_attrs.is_empty()
518 || self.style.is_bound()
519 || !self.bound_list.is_empty()
520 }
521
522 pub(crate) fn resolved_attrs(&self) -> Attrs {
525 let mut attrs = self.attrs.clone();
526 for part in &self.bound_attrs {
527 part(&mut attrs);
528 }
529 attrs
530 }
531
532 pub(crate) fn resolve_once(&mut self) {
535 if !self.is_bound() {
536 return;
537 }
538 super::untracked(|| {
539 if let Some(text) = self.bound_text.take() {
540 self.text = Some(text());
541 }
542 if !self.bound_attrs.is_empty() {
543 self.attrs = self.resolved_attrs();
544 self.bound_attrs.clear();
545 }
546 if self.style.is_bound() {
547 self.style = self.style.resolved();
548 }
549 let parts = std::mem::take(&mut self.bound_list);
550 if let Some(config) = self.list_config() {
551 for part in &parts {
552 part(config);
553 }
554 }
555 });
556 }
557
558 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
560 match &mut self.kind {
561 ElKind::List(list) => Some(&mut list.config),
562 ElKind::VirtualList(list) => Some(&mut list.config),
563 _ => None,
564 }
565 }
566
567 pub(crate) fn empty_view() -> Self {
569 Self::new(Tag::View)
570 }
571
572 pub(crate) fn new(tag: Tag) -> Self {
573 Self {
574 tag,
575 key: None,
576 text: None,
577 attrs: Attrs::default(),
578 style: StyleRefinement::default(),
579 handlers: Vec::new(),
580 responder: None,
581 children: Vec::new(),
582 kind: ElKind::Plain,
583 bound_text: None,
584 bound_attrs: Vec::new(),
585 bound_list: Vec::new(),
586 }
587 }
588}
589
590pub struct AnyElement(pub(crate) ElNode);
592
593pub trait IntoElement {
595 fn into_element(self) -> AnyElement;
597}
598
599impl IntoElement for AnyElement {
600 fn into_element(self) -> AnyElement {
601 self
602 }
603}
604
605impl IntoElement for SharedString {
606 fn into_element(self) -> AnyElement {
607 text(self).into_element()
608 }
609}
610
611impl IntoElement for &'static str {
612 fn into_element(self) -> AnyElement {
613 text(self).into_element()
614 }
615}
616
617impl IntoElement for String {
618 fn into_element(self) -> AnyElement {
619 text(self).into_element()
620 }
621}
622
623#[diagnostic::on_unimplemented(
629 message = "`{Self}` is not an element",
630 label = "not an element",
631 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
632)]
633pub trait IntoChild<M> {
634 #[doc(hidden)]
636 fn __push_into(self, out: &mut Vec<ElNode>);
637}
638
639#[doc(hidden)]
641pub struct OneChild(());
642
643#[doc(hidden)]
645pub struct ManyChildren(());
646
647impl<T: IntoElement> IntoChild<OneChild> for T {
648 fn __push_into(self, out: &mut Vec<ElNode>) {
649 out.push(self.into_element().0);
650 }
651}
652
653impl<I: IntoIterator> IntoChild<ManyChildren> for I
654where
655 I::Item: IntoElement,
656{
657 fn __push_into(self, out: &mut Vec<ElNode>) {
658 out.extend(self.into_iter().map(|c| c.into_element().0));
659 }
660}
661
662pub trait FluentBuilder: Sized {
666 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
668 if condition { then(self) } else { self }
669 }
670
671 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
673 match option {
674 Some(v) => then(self, v),
675 None => self,
676 }
677 }
678
679 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
681 f(self)
682 }
683}
684
685impl<T: Element> FluentBuilder for T {}
686
687pub trait Element: IntoElement + Sized {
691 #[doc(hidden)]
692 fn node(&mut self) -> &mut ElNode;
693
694 fn key(mut self, key: impl Into<SharedString>) -> Self {
697 self.node().key = Some(key.into());
698 self
699 }
700
701 fn bind_opacity(self, value: &impl super::Animated) -> Self {
703 self.bind(crate::animation::AnimationProp::Opacity, value)
704 }
705
706 fn bind_background(self, value: &impl super::Animated) -> Self {
709 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
710 }
711
712 fn bind_border_color(self, value: &impl super::Animated) -> Self {
714 self.bind(crate::animation::AnimationProp::BorderColor, value)
715 }
716
717 fn bind_color(self, value: &impl super::Animated) -> Self {
719 self.bind(crate::animation::AnimationProp::Color, value)
720 }
721
722 fn bind_shadow_color(self, value: &impl super::Animated) -> Self {
724 self.bind(crate::animation::AnimationProp::ShadowColor, value)
725 }
726
727 fn bind_shadow_opacity(self, value: &impl super::Animated) -> Self {
729 self.bind(crate::animation::AnimationProp::ShadowOpacity, value)
730 }
731
732 fn bind_shadow_radius(self, value: &impl super::Animated) -> Self {
734 self.bind(crate::animation::AnimationProp::ShadowRadius, value)
735 }
736
737 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
740 if let Some(node) = value.animated_node().live() {
741 let decl = crate::StyleDecl::Animated(prop, node.id());
742 self.node().attrs.animated.push((decl, node));
743 }
744 self
745 }
746
747 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
752 self.bind(crate::animation::AnimationProp::StickyTop, value)
753 }
754
755 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
757 self.bind(crate::animation::AnimationProp::StickyLeft, value)
758 }
759
760 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
763 if let Some(node) = value.animated_node().live() {
764 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
765 self.node().attrs.animated.push((decl, node));
766 }
767 self
768 }
769
770 fn bind_motion(self, motion: &super::Motion) -> Self {
774 use crate::animation::MotionChannel::*;
775 let mut this = self.bind_opacity(&motion.value(Opacity));
776 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
777 if let Some(kind) = channel.transform() {
778 this = this.bind_transform(kind, &motion.value(channel));
779 }
780 }
781 let scale = motion.value(Scale);
782 this.bind_transform(
783 crate::TransformKind::ScaleX,
784 &scale.mul(&motion.value(ScaleX)),
785 )
786 .bind_transform(
787 crate::TransformKind::ScaleY,
788 &scale.mul(&motion.value(ScaleY)),
789 )
790 }
791
792 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
794 self.bind_transform(crate::TransformKind::TranslateX, value)
795 }
796
797 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
799 self.bind_transform(crate::TransformKind::TranslateY, value)
800 }
801
802 fn bind_scale(self, value: &impl super::Animated) -> Self {
804 self.bind_transform(crate::TransformKind::Scale, value)
805 }
806
807 fn bind_rotate(self, value: &impl super::Animated) -> Self {
809 self.bind_transform(crate::TransformKind::Rotate, value)
810 }
811
812 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
815 self.node().attrs.element_ref = handle.target();
816 self
817 }
818
819 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
822 self.node()
823 .bind_attr(insets, |a, insets| a.inset_padding = Some(insets));
824 self
825 }
826
827 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
829 self.node()
830 .bind_attr(insets, |a, insets| a.inset_margin = Some(insets));
831 self
832 }
833
834 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
837 Style::apply(self.node(), style, Variant::default(), |a, patch| {
838 a.inline = patch
839 });
840 self
841 }
842
843 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
848 self.node()
849 .bind_attr(area, |a, area| a.selectable_view = area);
850 self
851 }
852
853 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
858 self.node().bind_attr(class, |a, class| a.class = class);
859 self
860 }
861}
862
863#[derive(Debug, Clone, Default, PartialEq)]
877pub struct Style(
878 pub(crate) Option<Arc<crate::StylePatch>>,
879 pub(crate) StyleRefinement,
882);
883
884impl Style {
885 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
889 let mut style = crate::Style::default();
890 let mut patch = crate::StylePatch::default();
891 for decl in decls {
892 let key = match &decl {
893 crate::StyleDecl::Set(key, _) => Some(*key),
894 _ => None,
895 };
896 if patch.push(&mut style, decl).is_err()
897 && let Some(key) = key
898 {
899 log::warn!("invalid value for style `{}`", key.name());
900 }
901 }
902 Self(Some(Arc::new(patch)), StyleRefinement::default())
903 }
904
905 pub fn with(self, key: crate::StyleKey, value: crate::PatchValue) -> Self {
908 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
909 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
910 style.1 = self.1;
911 style
912 }
913
914 pub fn decls(&self) -> &[crate::StyleDecl] {
916 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
917 }
918
919 pub(crate) fn apply(
925 node: &mut ElNode,
926 style: impl IntoReactive<Style>,
927 variant: Variant,
928 attr: impl Fn(&mut Attrs, Option<Arc<crate::StylePatch>>) + 'static,
929 ) {
930 match style.into_reactive() {
931 Reactive::Static(Style(patch, typed)) => {
932 attr(&mut node.attrs, patch);
933 if !typed.is_empty() {
934 node.style.extend_as(variant, typed);
935 }
936 }
937 Reactive::Bound(f) => {
938 let typed = super::untracked(|| !f().1.is_empty());
939 let patch = f.clone();
940 node.bind_attr(move || patch().0, attr);
941 if typed {
942 node.style
945 .bind(move |s| s.extend_as(variant, f().1.resolved()));
946 }
947 }
948 }
949 }
950}
951
952impl From<crate::StylePatch> for Style {
953 fn from(patch: crate::StylePatch) -> Self {
954 Self(Some(Arc::new(patch)), StyleRefinement::default())
955 }
956}
957
958impl From<StyleRefinement> for Style {
959 fn from(style: StyleRefinement) -> Self {
960 Self(None, style)
961 }
962}
963
964impl JsValue for Style {
965 fn ts_type(_types: &mut super::TsTypes) -> String {
966 "StyleProp<ViewStyle>".into()
967 }
968
969 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
972 if value.is_nullish() {
973 return Ok(Self::default());
974 }
975 Ok(Self::from(value.host().style(value.raw())?))
976 }
977
978 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
980 Err(PropError("a style does not convert back to JS".to_owned()))
981 }
982}
983
984impl<T: Element> Styled for T {
985 fn style(&mut self) -> &mut StyleRefinement {
986 &mut self.node().style
987 }
988}
989
990pub trait ParentElement: Element {
992 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
995 child.__push_into(&mut self.node().children);
996 self
997 }
998
999 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1001 self.node()
1002 .children
1003 .extend(children.into_iter().map(|c| c.into_element().0));
1004 self
1005 }
1006
1007 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1010 if let Some(slot) = slot {
1011 let mut node = ElNode::new(Tag::View);
1012 node.kind = ElKind::Slot(slot.name);
1013 self.node().children.push(place(SlotElement(node)).0);
1014 }
1015 self
1016 }
1017
1018 fn children_each<R: IntoElement>(
1021 mut self,
1022 children: impl Into<Children>,
1023 place: impl Fn(Child, Position) -> R + 'static,
1024 ) -> Self {
1025 let _ = children.into();
1026 let mut node = ElNode::new(Tag::View);
1027 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1028 self.node().children.push(node);
1029 self
1030 }
1031
1032 fn list<R: IntoElement>(
1038 mut self,
1039 items: Items,
1040 config: impl FnOnce(ListElement) -> ListElement,
1041 row: impl Fn(Child, Position) -> R + 'static,
1042 ) -> Self {
1043 let mut node = ElNode::new(Tag::List);
1044 node.kind = ElKind::List(Box::new(ListEl {
1045 name: items.name,
1046 config: ListConfig::default(),
1047 row: Rc::new(move |content, at| row(content, at).into_element()),
1048 }));
1049 self.node().children.push(config(ListElement(node)).0);
1050 self
1051 }
1052}
1053
1054pub trait Accessible: Element {
1056 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1058 self.node()
1059 .bind_attr(accessible, |a, accessible| a.accessible = Some(accessible));
1060 self
1061 }
1062
1063 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1065 self.node()
1066 .bind_attr(label, |a, label| a.label = Some(label));
1067 self
1068 }
1069
1070 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1073 self.node().bind_attr(label, |a, label| a.label = label);
1074 self
1075 }
1076
1077 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1079 self.node().bind_attr(hint, |a, hint| a.hint = Some(hint));
1080 self
1081 }
1082
1083 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1085 self.node().bind_attr(role, |a, role| a.role = role);
1086 self
1087 }
1088
1089 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1092 self.node().bind_attr(state, |a, state| {
1093 a.state = AccessibilityState {
1094 disabled: a.state.disabled,
1095 ..state
1096 };
1097 });
1098 self
1099 }
1100
1101 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1105 self.node().bind_attr(value, |a, value| a.value = value);
1106 self
1107 }
1108
1109 fn accessibility_actions(mut self, actions: Vec<crate::AccessibilityActionDef>) -> Self {
1114 super::host::set(
1115 self.node(),
1116 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1117 );
1118 self
1119 }
1120}
1121
1122pub trait IntoTooltip {
1125 #[doc(hidden)]
1126 fn apply_tooltip(self, node: &mut ElNode);
1127}
1128
1129impl IntoTooltip for AnyElement {
1130 fn apply_tooltip(self, node: &mut ElNode) {
1131 let mut hint = ElNode::new(Tag::Overlay);
1133 hint.key = Some("tooltip".into());
1134 hint.attrs.pointer_events = PointerEvents::None;
1135 let gap = Points(4.0);
1136 for prop in [
1137 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1138 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1139 crate::OverlayProp::Offset(gap),
1140 crate::OverlayProp::Margin(gap),
1141 ] {
1142 super::host::set(&mut hint, Prop::Overlay(prop));
1143 }
1144 hint.children.push(self.0);
1145 node.children.push(hint);
1146 }
1147}
1148
1149impl<C: Component> IntoTooltip for ComponentElement<C> {
1150 fn apply_tooltip(self, node: &mut ElNode) {
1151 self.into_element().apply_tooltip(node);
1152 }
1153}
1154
1155#[doc(hidden)]
1160pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1161 let mut hint = hint.0;
1162 hint.key = Some("tooltip".into());
1163 node.children.push(hint);
1164}
1165
1166pub trait Interactive: Element {
1168 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1174 tooltip.apply_tooltip(self.node());
1175 self
1176 }
1177
1178 fn on_file_drag_enter<M>(self, listener: impl IntoListener<(), M>) -> Self {
1180 self.on(
1181 EventKind::FileDragEnter,
1182 events::typed(listener.into_listener(), events::unit),
1183 )
1184 }
1185
1186 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1188 self.on(
1189 EventKind::FileDragLeave,
1190 events::typed(listener.into_listener(), events::unit),
1191 )
1192 }
1193
1194 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1196 self.on(
1197 EventKind::FileDrop,
1198 events::typed(listener.into_listener(), events::file_drop),
1199 )
1200 }
1201
1202 fn on_hover_in<M>(self, listener: impl IntoListener<(), M>) -> Self {
1204 self.on(
1205 EventKind::HoverIn,
1206 events::typed(listener.into_listener(), events::unit),
1207 )
1208 }
1209
1210 fn on_hover_out<M>(self, listener: impl IntoListener<(), M>) -> Self {
1212 self.on(
1213 EventKind::HoverOut,
1214 events::typed(listener.into_listener(), events::unit),
1215 )
1216 }
1217
1218 fn on_hover_move<M>(self, listener: impl IntoListener<HoverEvent, M>) -> Self {
1221 self.on(
1222 EventKind::HoverMove,
1223 events::typed(listener.into_listener(), events::hover),
1224 )
1225 }
1226
1227 fn on_mouse_move<M>(self, listener: impl IntoListener<crate::Point<crate::Points>, M>) -> Self {
1230 self.on(
1231 EventKind::MouseMove,
1232 events::typed(listener.into_listener(), events::mouse_position),
1233 )
1234 }
1235
1236 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1241 self.on(
1242 EventKind::ContextMenu,
1243 events::typed(listener.into_listener(), events::context_menu),
1244 )
1245 }
1246
1247 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1251 self.on(
1252 EventKind::Focus,
1253 events::typed(listener.into_listener(), events::unit),
1254 )
1255 }
1256
1257 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1259 self.on(
1260 EventKind::Blur,
1261 events::typed(listener.into_listener(), events::unit),
1262 )
1263 }
1264
1265 fn on_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1267 self.on(
1268 EventKind::Press,
1269 events::typed(listener.into_listener(), events::unit),
1270 )
1271 }
1272
1273 fn on_long_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1275 self.on(
1276 EventKind::LongPress,
1277 events::typed(listener.into_listener(), events::unit),
1278 )
1279 }
1280
1281 fn on_press_down<M>(self, listener: impl IntoListener<(), M>) -> Self {
1283 self.on(
1284 EventKind::PressDown,
1285 events::typed(listener.into_listener(), events::unit),
1286 )
1287 }
1288
1289 fn on_press_up<M>(self, listener: impl IntoListener<(), M>) -> Self {
1291 self.on(
1292 EventKind::PressUp,
1293 events::typed(listener.into_listener(), events::unit),
1294 )
1295 }
1296
1297 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1299 self.on(
1300 EventKind::Layout,
1301 events::typed(listener.into_listener(), events::layout),
1302 )
1303 }
1304
1305 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1309 self.on(
1310 EventKind::Touch,
1311 events::typed(listener.into_listener(), events::touch),
1312 )
1313 }
1314
1315 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1320 if let Some(pan) = claim.pan {
1321 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1322 }
1323 super::responder::of(self.node()).claims.push(claim);
1324 self
1325 }
1326
1327 fn keep_touches(mut self, keep: bool) -> Self {
1332 super::responder::of(self.node()).keep = keep;
1333 self
1334 }
1335
1336 fn on_responder_grant<M>(
1338 mut self,
1339 listener: impl IntoListener<super::ResponderEvent, M>,
1340 ) -> Self {
1341 super::responder::of(self.node()).grant = Some(listener.into_listener());
1342 self
1343 }
1344
1345 fn on_responder_reject<M>(
1348 mut self,
1349 listener: impl IntoListener<super::ResponderEvent, M>,
1350 ) -> Self {
1351 super::responder::of(self.node()).reject = Some(listener.into_listener());
1352 self
1353 }
1354
1355 fn on_responder_start<M>(
1358 mut self,
1359 listener: impl IntoListener<super::ResponderEvent, M>,
1360 ) -> Self {
1361 super::responder::of(self.node()).start = Some(listener.into_listener());
1362 self
1363 }
1364
1365 fn on_responder_move<M>(
1367 mut self,
1368 listener: impl IntoListener<super::ResponderEvent, M>,
1369 ) -> Self {
1370 super::responder::of(self.node()).moved = Some(listener.into_listener());
1371 self
1372 }
1373
1374 fn on_responder_end<M>(
1376 mut self,
1377 listener: impl IntoListener<super::ResponderEvent, M>,
1378 ) -> Self {
1379 super::responder::of(self.node()).end = Some(listener.into_listener());
1380 self
1381 }
1382
1383 fn on_responder_release<M>(
1386 mut self,
1387 listener: impl IntoListener<super::ResponderEvent, M>,
1388 ) -> Self {
1389 super::responder::of(self.node()).release = Some(listener.into_listener());
1390 self
1391 }
1392
1393 fn on_responder_terminate<M>(
1396 mut self,
1397 listener: impl IntoListener<super::ResponderEvent, M>,
1398 ) -> Self {
1399 super::responder::of(self.node()).terminate = Some(listener.into_listener());
1400 self
1401 }
1402
1403 fn pan_values(
1408 mut self,
1409 x: Option<&super::AnimatedValue>,
1410 y: Option<&super::AnimatedValue>,
1411 ) -> Self {
1412 let x = x.and_then(|v| v.node().live());
1413 let y = y.and_then(|v| v.node().live());
1414 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
1415 super::host::set(self.node(), prop);
1416 let bound = &mut self.node().attrs.bound;
1417 bound.extend(x);
1418 bound.extend(y);
1419 self
1420 }
1421
1422 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
1425 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
1426 self
1427 }
1428
1429 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
1433 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
1434 self
1435 }
1436
1437 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
1442 if let Some(node) = scale.node().live() {
1443 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
1444 self.node().attrs.bound.push(node);
1445 }
1446 self
1447 }
1448
1449 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
1453 if let Some(node) = angle.node().live() {
1454 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
1455 self.node().attrs.bound.push(node);
1456 }
1457 self
1458 }
1459
1460 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1462 self.on(
1463 EventKind::PanStart,
1464 events::typed(listener.into_listener(), events::pan),
1465 )
1466 }
1467
1468 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1470 self.on(
1471 EventKind::PanEnd,
1472 events::typed(listener.into_listener(), events::pan),
1473 )
1474 }
1475
1476 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1478 self.on(
1479 EventKind::PinchStart,
1480 events::typed(listener.into_listener(), events::pinch),
1481 )
1482 }
1483
1484 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1486 self.on(
1487 EventKind::PinchEnd,
1488 events::typed(listener.into_listener(), events::pinch),
1489 )
1490 }
1491
1492 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1494 self.on(
1495 EventKind::RotationStart,
1496 events::typed(listener.into_listener(), events::rotation),
1497 )
1498 }
1499
1500 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1502 self.on(
1503 EventKind::RotationEnd,
1504 events::typed(listener.into_listener(), events::rotation),
1505 )
1506 }
1507
1508 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
1510 self.on(
1511 EventKind::AccessibilityAction,
1512 events::typed(listener.into_listener(), events::action),
1513 )
1514 }
1515
1516 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
1519 self.node().handlers.push((kind, listener.into_listener()));
1520 self
1521 }
1522
1523 fn hit_slop(mut self, insets: EdgeInsets) -> Self {
1525 super::host::set(self.node(), Prop::HitSlop(insets));
1526 self
1527 }
1528
1529 fn long_press_delay(mut self, ms: f32) -> Self {
1531 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
1532 self
1533 }
1534
1535 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
1537 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
1538 self
1539 }
1540
1541 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
1543 super::host::set(self.node(), Prop::Elevation(elevation.into()));
1544 self
1545 }
1546
1547 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
1549 super::host::set(self.node(), Prop::BackdropMaterial(material));
1550 self
1551 }
1552
1553 fn test_id(mut self, id: &str) -> Self {
1555 super::host::set(self.node(), Prop::TestId(Some(id.into())));
1556 self
1557 }
1558
1559 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
1564 super::host::bind_prop(self.node(), enabled, |enabled| {
1565 Prop::WindowDrag(Some(enabled))
1566 });
1567 self
1568 }
1569
1570 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
1574 super::host::bind_prop(self.node(), focusable, |focusable| {
1575 Prop::Focusable(Some(focusable))
1576 });
1577 self
1578 }
1579
1580 fn native_id(mut self, id: &str) -> Self {
1582 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
1583 self
1584 }
1585
1586 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1588 let s = f(StyleRefinement::default());
1589 self.style().extend_as(Variant::ACTIVE, s);
1590 self
1591 }
1592
1593 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1595 let s = f(StyleRefinement::default());
1596 self.style().extend_as(Variant::HOVER, s);
1597 self
1598 }
1599
1600 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1602 let s = f(StyleRefinement::default());
1603 self.style().extend_as(Variant::FOCUS, s);
1604 self
1605 }
1606
1607 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1609 let s = f(StyleRefinement::default());
1610 self.style().extend_as(Variant::DISABLED, s);
1611 self
1612 }
1613
1614 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1616 self.node().bind_attr(disabled, |a, disabled| {
1617 a.disabled = disabled;
1618 a.state.disabled = disabled;
1619 });
1620 self
1621 }
1622
1623 fn pointer_events(mut self, pointer_events: impl IntoReactive<PointerEvents>) -> Self {
1625 self.node()
1626 .bind_attr(pointer_events, |a, p| a.pointer_events = p);
1627 self
1628 }
1629
1630 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
1633 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
1634 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
1635 });
1636 self
1637 }
1638
1639 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
1643 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
1644 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
1645 });
1646 self
1647 }
1648
1649 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
1653 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
1654 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
1655 });
1656 self
1657 }
1658
1659 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
1665 self.node().bind_attr(checked, |a, checked| {
1666 project(a, crate::tailwind::state::CHECKED, checked)
1667 });
1668 self
1669 }
1670
1671 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
1677 self.node().bind_attr(indeterminate, |a, indeterminate| {
1678 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
1679 });
1680 self
1681 }
1682
1683 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1688 self.node().bind_attr(disabled, |a, disabled| {
1689 project(a, crate::tailwind::state::DISABLED, disabled)
1690 });
1691 self
1692 }
1693}
1694
1695fn project(a: &mut Attrs, bit: u8, on: bool) {
1697 if on {
1698 a.projected_states |= bit;
1699 } else {
1700 a.projected_states &= !bit;
1701 }
1702}
1703
1704macro_rules! element {
1705 ($(#[$doc:meta])* $name:ident) => {
1706 $(#[$doc])*
1707 #[derive(Clone)]
1708 pub struct $name(ElNode);
1709
1710 impl Element for $name {
1711 fn node(&mut self) -> &mut ElNode {
1712 &mut self.0
1713 }
1714 }
1715
1716 impl IntoElement for $name {
1717 fn into_element(self) -> AnyElement {
1718 AnyElement(self.0)
1719 }
1720 }
1721
1722 impl Accessible for $name {}
1723
1724 impl IntoTooltip for $name {
1725 fn apply_tooltip(self, node: &mut ElNode) {
1726 self.into_element().apply_tooltip(node);
1727 }
1728 }
1729 };
1730}
1731
1732element! {
1733 View
1735}
1736
1737element! {
1738 Text
1740}
1741
1742element! {
1743 Image
1745}
1746
1747element! {
1748 SlotElement
1751}
1752
1753element! {
1754 ListElement
1756}
1757
1758impl Interactive for View {}
1759impl ParentElement for View {}
1760impl Interactive for SlotElement {}
1761impl Interactive for Text {}
1762impl Interactive for Image {}
1763
1764impl ParentElement for Text {
1769 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1770 let at = self.0.children.len();
1771 child.__push_into(&mut self.0.children);
1772 for el in &mut self.0.children[at..] {
1773 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
1774 }
1775 self
1776 }
1777
1778 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1779 self.0
1780 .children
1781 .extend(children.into_iter().map(|c| span(c.into_element().0)));
1782 self
1783 }
1784}
1785
1786fn span(mut el: ElNode) -> ElNode {
1789 if el.tag == Tag::Text
1790 && matches!(el.kind, ElKind::Plain)
1791 && el.key.is_none()
1792 && el.children.is_empty()
1793 && el.handlers.is_empty()
1794 && el.style.is_empty()
1795 && el.attrs == Attrs::default()
1796 && !el.is_bound()
1797 {
1798 el.kind = ElKind::Raw;
1799 }
1800 el
1801}
1802
1803impl Text {
1804 pub fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
1806 self.0
1807 .bind_attr(lines, |a, lines| a.number_of_lines = lines);
1808 self
1809 }
1810
1811 pub fn ellipsize_mode(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
1813 super::host::bind_prop(&mut self.0, mode, Prop::EllipsizeMode);
1814 self
1815 }
1816
1817 pub fn selectable(mut self, selectable: impl IntoReactive<bool>) -> Self {
1819 super::host::bind_prop(&mut self.0, selectable, |s| Prop::Selectable(Some(s)));
1820 self
1821 }
1822
1823 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
1825 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
1826 Prop::SelectionColor(Some(Color::from(c)))
1827 });
1828 self
1829 }
1830
1831 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
1833 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
1834 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
1835 self
1836 }
1837
1838 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
1841 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
1842 self
1843 }
1844
1845 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
1848 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
1849 self
1850 }
1851}
1852
1853impl Image {
1854 pub fn resize_mode(mut self, mode: impl IntoReactive<crate::ResizeMode>) -> Self {
1856 super::host::bind_prop(&mut self.0, mode, Prop::ResizeMode);
1857 self
1858 }
1859
1860 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
1863 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
1864 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
1865 uri: src.uri.to_arc(),
1866 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
1867 scales: src.scales,
1868 data: None,
1869 })))
1870 });
1871 self
1872 }
1873
1874 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
1876 Styled::tint_color(self, color)
1877 }
1878
1879 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
1881 super::host::set(
1882 &mut self.0,
1883 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
1884 );
1885 self
1886 }
1887
1888 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
1890 super::host::bind_prop(&mut self.0, ms, |ms| {
1891 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
1892 });
1893 self
1894 }
1895
1896 pub fn on_load<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
1898 self.on(
1899 EventKind::Load,
1900 events::typed(listener.into_listener(), events::size),
1901 )
1902 }
1903
1904 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1906 self.on(
1907 EventKind::Error,
1908 events::typed(listener.into_listener(), events::message),
1909 )
1910 }
1911
1912 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1914 self.on(
1915 EventKind::LoadStart,
1916 events::typed(listener.into_listener(), events::unit),
1917 )
1918 }
1919
1920 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1922 self.on(
1923 EventKind::LoadEnd,
1924 events::typed(listener.into_listener(), events::unit),
1925 )
1926 }
1927
1928 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
1931 self.on(
1932 EventKind::Progress,
1933 events::typed(listener.into_listener(), events::image_progress),
1934 )
1935 }
1936}
1937
1938impl super::Scrollable for ListElement {}
1939
1940impl super::ListLayout for ListElement {
1941 fn config(&mut self) -> &mut ListConfig {
1942 match &mut self.0.kind {
1943 ElKind::List(list) => &mut list.config,
1944 _ => unreachable!("a ListElement is a list"),
1945 }
1946 }
1947
1948 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
1949 &mut self.0.bound_list
1950 }
1951}
1952
1953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1956pub struct Slot {
1957 name: &'static str,
1958}
1959
1960impl Slot {
1961 pub(crate) fn new(name: &'static str) -> Self {
1962 Self { name }
1963 }
1964
1965 pub fn name(&self) -> &'static str {
1967 self.name
1968 }
1969
1970 pub fn element(self) -> SlotElement {
1972 let mut node = ElNode::new(Tag::View);
1973 node.kind = ElKind::Slot(self.name);
1974 SlotElement(node)
1975 }
1976}
1977
1978#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1982pub struct Items {
1983 name: &'static str,
1984}
1985
1986impl Items {
1987 #[doc(hidden)]
1988 pub const fn __new(name: &'static str) -> Self {
1989 Self { name }
1990 }
1991}
1992
1993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1997pub struct Child(ChildRef);
1998
1999#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2000enum ChildRef {
2001 Js(NodeId),
2002 Row,
2003}
2004
2005impl Child {
2006 pub(crate) fn js(id: NodeId) -> Self {
2007 Self(ChildRef::Js(id))
2008 }
2009
2010 pub(crate) fn row() -> Self {
2011 Self(ChildRef::Row)
2012 }
2013}
2014
2015impl IntoElement for Child {
2016 fn into_element(self) -> AnyElement {
2017 let mut node = ElNode::new(Tag::View);
2018 node.kind = match self.0 {
2019 ChildRef::Js(id) => ElKind::JsChild(id),
2020 ChildRef::Row => ElKind::Children,
2021 };
2022 AnyElement(node)
2023 }
2024}
2025
2026pub fn view() -> View {
2028 View(ElNode::new(Tag::View))
2029}
2030
2031pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2034 let mut node = ElNode::new(Tag::Text);
2035 match content.into_reactive() {
2036 Reactive::Static(content) => node.text = Some(content),
2037 Reactive::Bound(content) => {
2038 node.text = Some(SharedString::default());
2039 node.bound_text = Some(content);
2040 }
2041 }
2042 Text(node)
2043}
2044
2045pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2049 let mut node = ElNode::new(Tag::Image);
2050 node.bind_attr(src, |a, src| a.src = Some(src));
2051 Image(node)
2052}
2053
2054#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2057pub struct Children {
2058 present: bool,
2059}
2060
2061impl Children {
2062 pub(crate) fn new(present: bool) -> Self {
2063 Self { present }
2064 }
2065
2066 pub fn is_empty(&self) -> bool {
2068 !self.present
2069 }
2070}
2071
2072impl IntoElement for Children {
2073 fn into_element(self) -> AnyElement {
2074 let mut node = ElNode::new(Tag::View);
2075 node.kind = ElKind::Children;
2076 AnyElement(node)
2077 }
2078}
2079
2080pub struct ComponentElement<C: Component> {
2092 node: ElNode,
2093 _component: PhantomData<fn() -> C>,
2094}
2095
2096impl<C: Component> ComponentElement<C> {
2097 #[doc(hidden)]
2100 pub fn __new(props: C::Props) -> Self {
2101 Self::new(props)
2102 }
2103
2104 #[doc(hidden)]
2106 pub fn __props_mut(&mut self) -> &mut C::Props {
2107 match &mut self.node.kind {
2108 ElKind::Component(c) => c
2109 .props
2110 .as_any_mut()
2111 .downcast_mut::<C::Props>()
2112 .expect("a component element holds its component's props"),
2113 _ => unreachable!("a component element is a component's"),
2114 }
2115 }
2116
2117 pub(crate) fn new(props: C::Props) -> Self {
2118 let mut node = ElNode::new(Tag::View);
2119 node.kind = ElKind::Component(ComponentEl {
2120 name: super::component::name_of::<C>(),
2121 make: super::component::make_instance::<C>,
2122 spec: ComponentSpec::of::<C>,
2123 props: Box::new(props),
2124 on_event: Vec::new(),
2125 });
2126 Self {
2127 node,
2128 _component: PhantomData,
2129 }
2130 }
2131
2132 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2137 self.node
2138 .children
2139 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2140 let mut fill = ElNode::new(Tag::View);
2141 fill.kind = ElKind::Fill(slot);
2142 fill.children.push(content.into_element().0);
2143 self.node.children.push(fill);
2144 self
2145 }
2146
2147 pub fn items(mut self, list: super::VirtualList) -> Self {
2155 match <C::Props as super::Props>::ITEMS {
2156 Some(name) => self.node.children.push(list.into_items(name)),
2157 None => {
2158 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2159 }
2160 }
2161 self
2162 }
2163
2164 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2169 let s = f(StyleRefinement::default());
2170 self.node.style.extend_as(Variant::ACTIVE, s);
2171 self
2172 }
2173
2174 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2176 let s = f(StyleRefinement::default());
2177 self.node.style.extend_as(Variant::HOVER, s);
2178 self
2179 }
2180
2181 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2183 let s = f(StyleRefinement::default());
2184 self.node.style.extend_as(Variant::FOCUS, s);
2185 self
2186 }
2187
2188 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2191 let s = f(StyleRefinement::default());
2192 self.node.style.extend_as(Variant::DISABLED, s);
2193 self
2194 }
2195
2196 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2198 self.node.attrs.element_ref = handle.element().target();
2199 self
2200 }
2201
2202 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
2208 let listener = listener.into_listener();
2209 if let ElKind::Component(c) = &mut self.node.kind {
2210 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
2211 if let Some(event) = event.downcast_ref::<C::Event>() {
2212 inner(event);
2213 }
2214 }));
2215 }
2216 self
2217 }
2218
2219 #[doc(hidden)]
2223 pub fn __on_variant<T: ?Sized + 'static, M>(
2224 self,
2225 pick: fn(&C::Event) -> Option<&T>,
2226 listener: impl IntoListener<T, M>,
2227 ) -> Self {
2228 let listener = listener.into_listener();
2229 self.on_event(listener.wrap(move |inner, event: &C::Event| {
2230 if let Some(data) = pick(event) {
2231 inner(data);
2232 }
2233 }))
2234 }
2235}
2236
2237pub trait ComponentBuilder: Element {
2309 type Component: Component;
2311
2312 #[doc(hidden)]
2314 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
2315
2316 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2321 let s = f(StyleRefinement::default());
2322 self.node().style.extend_as(Variant::ACTIVE, s);
2323 self
2324 }
2325
2326 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2328 let s = f(StyleRefinement::default());
2329 self.node().style.extend_as(Variant::HOVER, s);
2330 self
2331 }
2332
2333 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2335 let s = f(StyleRefinement::default());
2336 self.node().style.extend_as(Variant::FOCUS, s);
2337 self
2338 }
2339
2340 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2343 let s = f(StyleRefinement::default());
2344 self.node().style.extend_as(Variant::DISABLED, s);
2345 self
2346 }
2347
2348 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
2350 self.__element().node.attrs.element_ref = handle.element().target();
2351 self
2352 }
2353}
2354
2355impl<C: Component> Element for ComponentElement<C> {
2356 fn node(&mut self) -> &mut ElNode {
2357 &mut self.node
2358 }
2359}
2360
2361impl<C: Component> ParentElement for ComponentElement<C> {}
2365
2366impl<C: Component> IntoElement for ComponentElement<C> {
2367 fn into_element(self) -> AnyElement {
2368 AnyElement(self.node)
2369 }
2370}