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, Bounds, ContextMenuEvent, EdgeInsets,
14 EventKind, EventPayload, HoverEvent, Hsla, ImageSource, ListContentStyle, NativeProp, NodeId,
15 PointerEvents, Points, Prop, Size, Tag, TouchEvent, geometry::Radians, style::Color,
16};
17
18pub struct Listener<E: ?Sized> {
24 f: Rc<dyn Fn(&E)>,
25 owner: super::Owner,
26}
27
28impl<E: ?Sized + 'static> Listener<E> {
29 pub(crate) fn noop() -> Self {
31 Self::new(Rc::new(|_| {}))
32 }
33
34 fn new(f: Rc<dyn Fn(&E)>) -> Self {
35 Self {
36 f,
37 owner: super::Owner::current_or_detached(),
38 }
39 }
40
41 pub(crate) fn call(&self, event: &E) {
44 if self.owner == super::Owner::detached() {
45 (self.f)(event);
46 } else if self.owner.is_live() {
47 self.owner.scope(|| (self.f)(event));
48 }
49 }
50
51 pub(crate) fn wrap<F: ?Sized>(self, f: impl Fn(&dyn Fn(&E), &F) + 'static) -> Listener<F> {
54 let inner = self.f;
55 Listener {
56 f: Rc::new(move |event: &F| f(&*inner, event)),
57 owner: self.owner,
58 }
59 }
60}
61
62impl<E: 'static> Listener<E> {
63 pub fn map<F: ?Sized + 'static>(self, f: impl Fn(&F) -> E + 'static) -> Listener<F> {
65 self.wrap(move |inner, event: &F| inner(&f(event)))
66 }
67}
68
69impl<E: ?Sized + 'static, F: Fn(&E) + 'static> From<F> for Listener<E> {
71 fn from(f: F) -> Self {
72 Self::new(Rc::new(f))
73 }
74}
75
76#[diagnostic::on_unimplemented(
83 message = "`{Self}` is not a listener of `{E}`",
84 label = "not a listener of `{E}`",
85 note = "a listener is a closure `move |event: &{E}| ..` (`move || ..` for an event without data) or a `Listener<{E}>`"
86)]
87pub trait IntoListener<E: ?Sized, M> {
88 fn into_listener(self) -> Listener<E>;
90}
91
92#[doc(hidden)]
94pub struct OfEvent(());
95
96#[doc(hidden)]
99pub struct WithoutEvent(());
100
101impl<E: ?Sized> IntoListener<E, ()> for Listener<E> {
102 fn into_listener(self) -> Listener<E> {
103 self
104 }
105}
106
107impl<E: ?Sized + 'static, F: Fn(&E) + 'static> IntoListener<E, OfEvent> for F {
108 fn into_listener(self) -> Listener<E> {
109 Listener::new(Rc::new(self))
110 }
111}
112
113impl<F: Fn() + 'static> IntoListener<(), WithoutEvent> for F {
114 fn into_listener(self) -> Listener<()> {
115 Listener::new(Rc::new(move |_: &()| self()))
116 }
117}
118
119impl<E: ?Sized> Clone for Listener<E> {
120 fn clone(&self) -> Self {
121 Self {
122 f: self.f.clone(),
123 owner: self.owner,
124 }
125 }
126}
127
128pub(crate) trait AnyEvent: super::EventToJs {
131 fn as_any(&self) -> &dyn Any;
132}
133
134impl<E: Event> super::EventToJs for E {
135 fn name(&self) -> &'static str {
136 Event::name(self)
137 }
138
139 fn data_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
140 Event::data_js(self, host)
141 }
142
143 fn spread(&self) -> bool {
144 Event::spread(self)
145 }
146}
147
148impl<E: Event> AnyEvent for E {
149 fn as_any(&self) -> &dyn Any {
150 self
151 }
152}
153
154#[doc(hidden)]
156#[derive(Debug, Clone, Default, PartialEq)]
157pub struct Attrs {
158 pub(crate) disabled: bool,
159 pub(crate) accessible: Option<bool>,
160 pub(crate) label: Option<SharedString>,
161 pub(crate) hint: Option<SharedString>,
162 pub(crate) role: AccessibilityRole,
163 pub(crate) state: AccessibilityState,
164 pub(crate) pointer_events: PointerEvents,
165 pub(crate) number_of_lines: u32,
166 pub(crate) src: Option<super::ImageSrc>,
167 pub(crate) inset_padding: Option<EdgeInsets>,
168 pub(crate) inset_margin: Option<EdgeInsets>,
169 pub(crate) inline: Option<Arc<crate::StylePatch>>,
171 pub(crate) props: Vec<Prop>,
174 pub(crate) drawing: Option<Arc<crate::canvas::Drawing>>,
176 pub(crate) element_ref: Option<super::element_ref::RefTarget>,
179 pub(crate) animated: Vec<(crate::StyleDecl, super::LiveNode)>,
182 pub(crate) bound: Vec<super::LiveNode>,
184 pub(crate) class: Option<SharedString>,
187 pub(crate) selection_area: bool,
189 pub(crate) projected_states: u8,
192 pub(crate) render: Option<super::renderer::RenderAt>,
195}
196
197impl Attrs {
198 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
200 use AccessibilityProp as A;
201 if self.disabled != old.disabled {
202 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
203 }
204 if self.accessible != old.accessible {
205 out.push(Prop::Accessibility(A::Accessible(self.accessible)));
206 }
207 if self.label != old.label {
208 out.push(Prop::Accessibility(A::Label(
209 self.label.as_ref().map(SharedString::to_arc),
210 )));
211 }
212 if self.hint != old.hint {
213 out.push(Prop::Accessibility(A::Hint(
214 self.hint.as_ref().map(SharedString::to_arc),
215 )));
216 }
217 if self.role != old.role {
218 out.push(Prop::Accessibility(A::Role(self.role)));
219 }
220 if self.state != old.state {
221 out.push(Prop::Accessibility(A::State(self.state)));
222 }
223 if self.pointer_events != old.pointer_events {
224 out.push(Prop::PointerEvents(self.pointer_events));
225 }
226 if self.number_of_lines != old.number_of_lines {
227 out.push(Prop::NumberOfLines(self.number_of_lines));
228 }
229 if self.src != old.src {
230 out.push(Prop::Source(self.src.as_ref().map(|src| ImageSource {
231 uri: src.uri.to_arc(),
232 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
233 scales: src.scales,
234 })));
235 }
236 if self.inset_padding != old.inset_padding {
237 out.push(Prop::InsetPadding(self.inset_padding.unwrap_or_default()));
238 }
239 if self.inset_margin != old.inset_margin {
240 out.push(Prop::InsetMargin(self.inset_margin.unwrap_or_default()));
241 }
242 if self.selection_area != old.selection_area {
243 out.push(Prop::SelectionArea(self.selection_area));
244 }
245 if self.projected_states != old.projected_states {
246 out.push(Prop::ProjectedStates(self.projected_states));
247 }
248 for prop in &old.props {
251 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
252 && let Some(reset) = super::host::reset(prop)
253 {
254 out.push(reset);
255 }
256 }
257 for prop in &self.props {
258 if !old.props.contains(prop) {
259 out.push(prop.clone());
260 }
261 }
262 }
263}
264
265pub(crate) trait AnyProps {
267 fn as_any(&self) -> &dyn Any;
268 fn as_any_mut(&mut self) -> &mut dyn Any;
269 fn clone_box(&self) -> Box<dyn AnyProps>;
270}
271
272impl<P: Clone + 'static> AnyProps for P {
273 fn as_any(&self) -> &dyn Any {
274 self
275 }
276
277 fn as_any_mut(&mut self) -> &mut dyn Any {
278 self
279 }
280
281 fn clone_box(&self) -> Box<dyn AnyProps> {
282 Box::new(self.clone())
283 }
284}
285
286pub(crate) struct ComponentEl {
288 pub(crate) name: &'static str,
289 pub(crate) make: fn() -> Box<dyn AnyInstance>,
292 pub(crate) spec: fn() -> ComponentSpec,
294 pub(crate) props: Box<dyn AnyProps>,
295 pub(crate) on_event: Vec<Listener<dyn Any>>,
297}
298
299impl Clone for ComponentEl {
300 fn clone(&self) -> Self {
301 Self {
302 name: self.name,
303 make: self.make,
304 spec: self.spec,
305 props: self.props.clone_box(),
306 on_event: self.on_event.clone(),
307 }
308 }
309}
310
311pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
313
314#[derive(Clone, Copy)]
320pub struct Position {
321 index: super::reactive::Node,
322 count: super::reactive::Node,
323}
324
325impl Position {
326 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
329 Self { index, count }
330 }
331
332 pub(crate) fn fixed(index: usize, count: usize) -> Self {
334 Self::of(super::signal(index).node(), super::signal(count).node())
335 }
336
337 #[track_caller]
339 pub fn index(&self) -> usize {
340 self.index.with("a position", |i: &usize| *i)
341 }
342
343 #[track_caller]
345 pub fn count(&self) -> usize {
346 self.count.with("a position", |n: &usize| *n)
347 }
348
349 #[track_caller]
351 pub fn is_first(&self) -> bool {
352 self.index() == 0
353 }
354
355 #[track_caller]
357 pub fn is_last(&self) -> bool {
358 self.index() + 1 == self.count()
359 }
360}
361
362impl fmt::Debug for Position {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 let (index, count) = super::untracked(|| (self.index(), self.count()));
365 write!(f, "Position({index} of {count})")
366 }
367}
368
369#[doc(hidden)]
372#[derive(Debug, Clone, Copy, Default, PartialEq)]
373pub struct ListConfig {
374 pub(crate) estimated: Option<f32>,
375 pub(crate) columns: Option<u32>,
376 pub(crate) horizontal: Option<bool>,
377 pub(crate) inverted: Option<bool>,
378 pub(crate) scrollbar_visible: Option<bool>,
379 pub(crate) content: Option<ListContentStyle>,
380 pub(crate) follow_end: Option<f32>,
381}
382
383impl ListConfig {
384 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
386 if self.estimated != old.estimated {
387 out.push(Prop::EstimatedItemSize(Points(
388 self.estimated.unwrap_or(50.0),
389 )));
390 }
391 if self.columns != old.columns {
392 out.push(Prop::Columns(self.columns.unwrap_or(1)));
393 }
394 if self.horizontal != old.horizontal {
395 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
396 }
397 if self.inverted != old.inverted {
398 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
399 }
400 if self.scrollbar_visible != old.scrollbar_visible {
401 out.push(Prop::Scrollbar(self.scrollbar_visible.unwrap_or(true)));
402 }
403 if self.content != old.content {
404 out.push(Prop::ListContent(self.content.unwrap_or_default()));
405 }
406 if self.follow_end != old.follow_end {
407 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
408 }
409 }
410}
411
412#[derive(Clone)]
414pub(crate) struct ListEl {
415 pub(crate) name: &'static str,
416 pub(crate) config: ListConfig,
417 pub(crate) row: PlaceFn,
418}
419
420#[derive(Clone)]
422pub(crate) enum ElKind {
423 Plain,
424 Slot(&'static str),
426 Fill(&'static str),
429 Filled(&'static str),
432 Children,
434 JsChild(NodeId),
436 EachChild(PlaceFn),
438 List(Box<ListEl>),
440 VirtualList(Box<super::virtual_list::VirtualListEl>),
442 Raw,
445 Component(ComponentEl),
446 Region(super::flow::Region),
450 Keep,
453}
454
455#[doc(hidden)]
457#[derive(Clone)]
458pub struct ElNode {
459 pub(crate) tag: Tag,
460 pub(crate) key: Option<SharedString>,
461 pub(crate) text: Option<SharedString>,
463 pub(crate) attrs: Attrs,
464 pub(crate) style: StyleRefinement,
465 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
466 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
468 pub(crate) children: Vec<ElNode>,
469 pub(crate) kind: ElKind,
470 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
472 pub(crate) bound_attrs: Vec<BoundAttrs>,
474 pub(crate) bound_list: Vec<BoundListConfig>,
476}
477
478#[doc(hidden)]
480pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
481
482crate::static_reactive!(AccessibilityState: AccessibilityState);
483crate::static_reactive!(EdgeInsets: EdgeInsets);
484crate::static_reactive!(Style: Style);
485crate::static_reactive!(PointerEvents: PointerEvents);
486
487pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
489
490impl ElNode {
491 pub(crate) fn bind_attr<T: 'static>(
494 &mut self,
495 value: impl IntoReactive<T>,
496 apply: impl Fn(&mut Attrs, T) + 'static,
497 ) {
498 match value.into_reactive() {
499 Reactive::Static(v) => apply(&mut self.attrs, v),
500 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
501 }
502 }
503
504 pub(crate) fn is_bound(&self) -> bool {
506 self.bound_text.is_some()
507 || !self.bound_attrs.is_empty()
508 || self.style.is_bound()
509 || !self.bound_list.is_empty()
510 }
511
512 pub(crate) fn resolved_attrs(&self) -> Attrs {
515 let mut attrs = self.attrs.clone();
516 for part in &self.bound_attrs {
517 part(&mut attrs);
518 }
519 attrs
520 }
521
522 pub(crate) fn resolve_once(&mut self) {
525 if !self.is_bound() {
526 return;
527 }
528 super::untracked(|| {
529 if let Some(text) = self.bound_text.take() {
530 self.text = Some(text());
531 }
532 if !self.bound_attrs.is_empty() {
533 self.attrs = self.resolved_attrs();
534 self.bound_attrs.clear();
535 }
536 if self.style.is_bound() {
537 self.style = self.style.resolved();
538 }
539 let parts = std::mem::take(&mut self.bound_list);
540 if let Some(config) = self.list_config() {
541 for part in &parts {
542 part(config);
543 }
544 }
545 });
546 }
547
548 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
550 match &mut self.kind {
551 ElKind::List(list) => Some(&mut list.config),
552 ElKind::VirtualList(list) => Some(&mut list.config),
553 _ => None,
554 }
555 }
556
557 pub(crate) fn empty_view() -> Self {
559 Self::new(Tag::View)
560 }
561
562 pub(crate) fn new(tag: Tag) -> Self {
563 Self {
564 tag,
565 key: None,
566 text: None,
567 attrs: Attrs::default(),
568 style: StyleRefinement::default(),
569 handlers: Vec::new(),
570 responder: None,
571 children: Vec::new(),
572 kind: ElKind::Plain,
573 bound_text: None,
574 bound_attrs: Vec::new(),
575 bound_list: Vec::new(),
576 }
577 }
578}
579
580pub struct AnyElement(pub(crate) ElNode);
582
583pub trait IntoElement {
585 fn into_element(self) -> AnyElement;
587}
588
589impl IntoElement for AnyElement {
590 fn into_element(self) -> AnyElement {
591 self
592 }
593}
594
595impl IntoElement for SharedString {
596 fn into_element(self) -> AnyElement {
597 text(self).into_element()
598 }
599}
600
601impl IntoElement for &'static str {
602 fn into_element(self) -> AnyElement {
603 text(self).into_element()
604 }
605}
606
607impl IntoElement for String {
608 fn into_element(self) -> AnyElement {
609 text(self).into_element()
610 }
611}
612
613#[diagnostic::on_unimplemented(
619 message = "`{Self}` is not an element",
620 label = "not an element",
621 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
622)]
623pub trait IntoChild<M> {
624 #[doc(hidden)]
626 fn __push_into(self, out: &mut Vec<ElNode>);
627}
628
629#[doc(hidden)]
631pub struct OneChild(());
632
633#[doc(hidden)]
635pub struct ManyChildren(());
636
637impl<T: IntoElement> IntoChild<OneChild> for T {
638 fn __push_into(self, out: &mut Vec<ElNode>) {
639 out.push(self.into_element().0);
640 }
641}
642
643impl<I: IntoIterator> IntoChild<ManyChildren> for I
644where
645 I::Item: IntoElement,
646{
647 fn __push_into(self, out: &mut Vec<ElNode>) {
648 out.extend(self.into_iter().map(|c| c.into_element().0));
649 }
650}
651
652pub trait FluentBuilder: Sized {
656 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
658 if condition { then(self) } else { self }
659 }
660
661 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
663 match option {
664 Some(v) => then(self, v),
665 None => self,
666 }
667 }
668
669 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
671 f(self)
672 }
673}
674
675impl<T: Element> FluentBuilder for T {}
676
677pub trait Element: IntoElement + Sized {
681 #[doc(hidden)]
682 fn node(&mut self) -> &mut ElNode;
683
684 fn key(mut self, key: impl Into<SharedString>) -> Self {
687 self.node().key = Some(key.into());
688 self
689 }
690
691 fn bind_opacity(self, value: &impl super::Animated) -> Self {
693 self.bind(crate::animation::AnimationProp::Opacity, value)
694 }
695
696 fn bind_background(self, value: &impl super::Animated) -> Self {
699 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
700 }
701
702 fn bind_border_color(self, value: &impl super::Animated) -> Self {
704 self.bind(crate::animation::AnimationProp::BorderColor, value)
705 }
706
707 fn bind_color(self, value: &impl super::Animated) -> Self {
709 self.bind(crate::animation::AnimationProp::Color, value)
710 }
711
712 fn bind_shadow_color(self, value: &impl super::Animated) -> Self {
714 self.bind(crate::animation::AnimationProp::ShadowColor, value)
715 }
716
717 fn bind_shadow_opacity(self, value: &impl super::Animated) -> Self {
719 self.bind(crate::animation::AnimationProp::ShadowOpacity, value)
720 }
721
722 fn bind_shadow_radius(self, value: &impl super::Animated) -> Self {
724 self.bind(crate::animation::AnimationProp::ShadowRadius, value)
725 }
726
727 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
730 if let Some(node) = value.animated_node().live() {
731 let decl = crate::StyleDecl::Animated(prop, node.id());
732 self.node().attrs.animated.push((decl, node));
733 }
734 self
735 }
736
737 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
740 if let Some(node) = value.animated_node().live() {
741 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
742 self.node().attrs.animated.push((decl, node));
743 }
744 self
745 }
746
747 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
749 self.bind_transform(crate::TransformKind::TranslateX, value)
750 }
751
752 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
754 self.bind_transform(crate::TransformKind::TranslateY, value)
755 }
756
757 fn bind_scale(self, value: &impl super::Animated) -> Self {
759 self.bind_transform(crate::TransformKind::Scale, value)
760 }
761
762 fn bind_rotate(self, value: &impl super::Animated) -> Self {
764 self.bind_transform(crate::TransformKind::Rotate, value)
765 }
766
767 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
770 self.node().attrs.element_ref = handle.target();
771 self
772 }
773
774 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
777 self.node()
778 .bind_attr(insets, |a, insets| a.inset_padding = Some(insets));
779 self
780 }
781
782 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
784 self.node()
785 .bind_attr(insets, |a, insets| a.inset_margin = Some(insets));
786 self
787 }
788
789 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
792 Style::apply(self.node(), style, Variant::default(), |a, patch| {
793 a.inline = patch
794 });
795 self
796 }
797
798 fn selection_area(mut self, area: impl IntoReactive<bool>) -> Self {
802 self.node()
803 .bind_attr(area, |a, area| a.selection_area = area);
804 self
805 }
806
807 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
812 self.node().bind_attr(class, |a, class| a.class = class);
813 self
814 }
815}
816
817#[derive(Debug, Clone, Default, PartialEq)]
831pub struct Style(
832 pub(crate) Option<Arc<crate::StylePatch>>,
833 pub(crate) StyleRefinement,
836);
837
838impl Style {
839 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
843 let mut style = crate::Style::default();
844 let mut patch = crate::StylePatch::default();
845 for decl in decls {
846 let key = match &decl {
847 crate::StyleDecl::Set(key, _) => Some(*key),
848 _ => None,
849 };
850 if patch.push(&mut style, decl).is_err()
851 && let Some(key) = key
852 {
853 log::warn!("invalid value for style `{}`", key.name());
854 }
855 }
856 Self(Some(Arc::new(patch)), StyleRefinement::default())
857 }
858
859 pub fn with(self, key: crate::StyleKey, value: crate::PatchValue) -> Self {
862 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
863 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
864 style.1 = self.1;
865 style
866 }
867
868 pub fn decls(&self) -> &[crate::StyleDecl] {
870 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
871 }
872
873 pub(crate) fn apply(
879 node: &mut ElNode,
880 style: impl IntoReactive<Style>,
881 variant: Variant,
882 attr: impl Fn(&mut Attrs, Option<Arc<crate::StylePatch>>) + 'static,
883 ) {
884 match style.into_reactive() {
885 Reactive::Static(Style(patch, typed)) => {
886 attr(&mut node.attrs, patch);
887 if !typed.is_empty() {
888 node.style.extend_as(variant, typed);
889 }
890 }
891 Reactive::Bound(f) => {
892 let typed = super::untracked(|| !f().1.is_empty());
893 let patch = f.clone();
894 node.bind_attr(move || patch().0, attr);
895 if typed {
896 node.style
899 .bind(move |s| s.extend_as(variant, f().1.resolved()));
900 }
901 }
902 }
903 }
904}
905
906impl From<crate::StylePatch> for Style {
907 fn from(patch: crate::StylePatch) -> Self {
908 Self(Some(Arc::new(patch)), StyleRefinement::default())
909 }
910}
911
912impl From<StyleRefinement> for Style {
913 fn from(style: StyleRefinement) -> Self {
914 Self(None, style)
915 }
916}
917
918impl JsValue for Style {
919 fn ts_type(_types: &mut super::TsTypes) -> String {
920 "StyleProp<ViewStyle>".into()
921 }
922
923 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
926 if value.is_nullish() {
927 return Ok(Self::default());
928 }
929 Ok(Self::from(value.host().style(value.raw())?))
930 }
931
932 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
934 Err(PropError("a style does not convert back to JS".to_owned()))
935 }
936}
937
938impl<T: Element> Styled for T {
939 fn style(&mut self) -> &mut StyleRefinement {
940 &mut self.node().style
941 }
942}
943
944pub trait ParentElement: Element {
946 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
949 child.__push_into(&mut self.node().children);
950 self
951 }
952
953 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
955 self.node()
956 .children
957 .extend(children.into_iter().map(|c| c.into_element().0));
958 self
959 }
960
961 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
964 if let Some(slot) = slot {
965 let mut node = ElNode::new(Tag::View);
966 node.kind = ElKind::Slot(slot.name);
967 self.node().children.push(place(SlotElement(node)).0);
968 }
969 self
970 }
971
972 fn children_each<R: IntoElement>(
975 mut self,
976 children: impl Into<Children>,
977 place: impl Fn(Child, Position) -> R + 'static,
978 ) -> Self {
979 let _ = children.into();
980 let mut node = ElNode::new(Tag::View);
981 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
982 self.node().children.push(node);
983 self
984 }
985
986 fn list<R: IntoElement>(
992 mut self,
993 items: Items,
994 config: impl FnOnce(ListElement) -> ListElement,
995 row: impl Fn(Child, Position) -> R + 'static,
996 ) -> Self {
997 let mut node = ElNode::new(Tag::List);
998 node.kind = ElKind::List(Box::new(ListEl {
999 name: items.name,
1000 config: ListConfig::default(),
1001 row: Rc::new(move |content, at| row(content, at).into_element()),
1002 }));
1003 self.node().children.push(config(ListElement(node)).0);
1004 self
1005 }
1006}
1007
1008pub trait Accessible: Element {
1010 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1012 self.node()
1013 .bind_attr(accessible, |a, accessible| a.accessible = Some(accessible));
1014 self
1015 }
1016
1017 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1019 self.node()
1020 .bind_attr(label, |a, label| a.label = Some(label));
1021 self
1022 }
1023
1024 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1027 self.node().bind_attr(label, |a, label| a.label = label);
1028 self
1029 }
1030
1031 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1033 self.node().bind_attr(hint, |a, hint| a.hint = Some(hint));
1034 self
1035 }
1036
1037 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1039 self.node().bind_attr(role, |a, role| a.role = role);
1040 self
1041 }
1042
1043 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1046 self.node().bind_attr(state, |a, state| {
1047 a.state = AccessibilityState {
1048 disabled: a.state.disabled,
1049 ..state
1050 };
1051 });
1052 self
1053 }
1054}
1055
1056pub trait IntoTooltip {
1060 #[doc(hidden)]
1061 fn apply_tooltip(self, node: &mut ElNode);
1062}
1063
1064impl IntoTooltip for &'static str {
1065 fn apply_tooltip(self, node: &mut ElNode) {
1066 SharedString::from(self).apply_tooltip(node);
1067 }
1068}
1069
1070impl IntoTooltip for String {
1071 fn apply_tooltip(self, node: &mut ElNode) {
1072 SharedString::from(self).apply_tooltip(node);
1073 }
1074}
1075
1076impl IntoTooltip for SharedString {
1077 fn apply_tooltip(self, node: &mut ElNode) {
1078 let content = if self.is_empty() {
1079 crate::overlay::TooltipContent::None
1080 } else {
1081 crate::overlay::TooltipContent::Text(Arc::from(self.as_str()))
1082 };
1083 super::host::set(node, Prop::Tooltip(content));
1084 }
1085}
1086
1087impl IntoTooltip for AnyElement {
1088 fn apply_tooltip(self, node: &mut ElNode) {
1089 let mut hint = ElNode::new(Tag::Overlay);
1091 hint.key = Some("tooltip".into());
1092 hint.attrs.pointer_events = PointerEvents::None;
1093 let gap = Points(4.0);
1094 for prop in [
1095 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1096 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1097 crate::OverlayProp::Offset(gap),
1098 crate::OverlayProp::Margin(gap),
1099 ] {
1100 super::host::set(&mut hint, Prop::Overlay(prop));
1101 }
1102 hint.children.push(self.0);
1103 node.children.push(hint);
1104 }
1105}
1106
1107impl<C: Component> IntoTooltip for ComponentElement<C> {
1108 fn apply_tooltip(self, node: &mut ElNode) {
1109 self.into_element().apply_tooltip(node);
1110 }
1111}
1112
1113#[doc(hidden)]
1118pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1119 let mut hint = hint.0;
1120 hint.key = Some("tooltip".into());
1121 node.children.push(hint);
1122}
1123
1124pub trait Interactive: Element {
1126 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1133 tooltip.apply_tooltip(self.node());
1134 self
1135 }
1136
1137 fn on_file_drag_enter<M>(self, listener: impl IntoListener<(), M>) -> Self {
1139 self.on(
1140 EventKind::FileDragEnter,
1141 events::typed(listener.into_listener(), events::unit),
1142 )
1143 }
1144
1145 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1147 self.on(
1148 EventKind::FileDragLeave,
1149 events::typed(listener.into_listener(), events::unit),
1150 )
1151 }
1152
1153 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1155 self.on(
1156 EventKind::FileDrop,
1157 events::typed(listener.into_listener(), events::file_drop),
1158 )
1159 }
1160
1161 fn on_hover_in<M>(self, listener: impl IntoListener<(), M>) -> Self {
1163 self.on(
1164 EventKind::HoverIn,
1165 events::typed(listener.into_listener(), events::unit),
1166 )
1167 }
1168
1169 fn on_hover_out<M>(self, listener: impl IntoListener<(), M>) -> Self {
1171 self.on(
1172 EventKind::HoverOut,
1173 events::typed(listener.into_listener(), events::unit),
1174 )
1175 }
1176
1177 fn on_hover_move<M>(self, listener: impl IntoListener<HoverEvent, M>) -> Self {
1180 self.on(
1181 EventKind::HoverMove,
1182 events::typed(listener.into_listener(), events::hover),
1183 )
1184 }
1185
1186 fn on_mouse_move<M>(self, listener: impl IntoListener<crate::Point<crate::Points>, M>) -> Self {
1189 self.on(
1190 EventKind::MouseMove,
1191 events::typed(listener.into_listener(), events::offset),
1192 )
1193 }
1194
1195 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1200 self.on(
1201 EventKind::ContextMenu,
1202 events::typed(listener.into_listener(), events::context_menu),
1203 )
1204 }
1205
1206 fn on_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1208 self.on(
1209 EventKind::Press,
1210 events::typed(listener.into_listener(), events::unit),
1211 )
1212 }
1213
1214 fn on_long_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
1216 self.on(
1217 EventKind::LongPress,
1218 events::typed(listener.into_listener(), events::unit),
1219 )
1220 }
1221
1222 fn on_press_down<M>(self, listener: impl IntoListener<(), M>) -> Self {
1224 self.on(
1225 EventKind::PressDown,
1226 events::typed(listener.into_listener(), events::unit),
1227 )
1228 }
1229
1230 fn on_press_up<M>(self, listener: impl IntoListener<(), M>) -> Self {
1232 self.on(
1233 EventKind::PressUp,
1234 events::typed(listener.into_listener(), events::unit),
1235 )
1236 }
1237
1238 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1240 self.on(
1241 EventKind::Layout,
1242 events::typed(listener.into_listener(), events::layout),
1243 )
1244 }
1245
1246 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1250 self.on(
1251 EventKind::Touch,
1252 events::typed(listener.into_listener(), events::touch),
1253 )
1254 }
1255
1256 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1261 if let Some(pan) = claim.pan {
1262 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1263 }
1264 super::responder::of(self.node()).claims.push(claim);
1265 self
1266 }
1267
1268 fn keep_touches(mut self, keep: bool) -> Self {
1273 super::responder::of(self.node()).keep = keep;
1274 self
1275 }
1276
1277 fn on_responder_grant<M>(
1279 mut self,
1280 listener: impl IntoListener<super::ResponderEvent, M>,
1281 ) -> Self {
1282 super::responder::of(self.node()).grant = Some(listener.into_listener());
1283 self
1284 }
1285
1286 fn on_responder_reject<M>(
1289 mut self,
1290 listener: impl IntoListener<super::ResponderEvent, M>,
1291 ) -> Self {
1292 super::responder::of(self.node()).reject = Some(listener.into_listener());
1293 self
1294 }
1295
1296 fn on_responder_start<M>(
1299 mut self,
1300 listener: impl IntoListener<super::ResponderEvent, M>,
1301 ) -> Self {
1302 super::responder::of(self.node()).start = Some(listener.into_listener());
1303 self
1304 }
1305
1306 fn on_responder_move<M>(
1308 mut self,
1309 listener: impl IntoListener<super::ResponderEvent, M>,
1310 ) -> Self {
1311 super::responder::of(self.node()).moved = Some(listener.into_listener());
1312 self
1313 }
1314
1315 fn on_responder_end<M>(
1317 mut self,
1318 listener: impl IntoListener<super::ResponderEvent, M>,
1319 ) -> Self {
1320 super::responder::of(self.node()).end = Some(listener.into_listener());
1321 self
1322 }
1323
1324 fn on_responder_release<M>(
1327 mut self,
1328 listener: impl IntoListener<super::ResponderEvent, M>,
1329 ) -> Self {
1330 super::responder::of(self.node()).release = Some(listener.into_listener());
1331 self
1332 }
1333
1334 fn on_responder_terminate<M>(
1337 mut self,
1338 listener: impl IntoListener<super::ResponderEvent, M>,
1339 ) -> Self {
1340 super::responder::of(self.node()).terminate = Some(listener.into_listener());
1341 self
1342 }
1343
1344 fn pan_values(
1349 mut self,
1350 x: Option<&super::AnimatedValue>,
1351 y: Option<&super::AnimatedValue>,
1352 ) -> Self {
1353 let x = x.and_then(|v| v.node().live());
1354 let y = y.and_then(|v| v.node().live());
1355 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
1356 super::host::set(self.node(), prop);
1357 let bound = &mut self.node().attrs.bound;
1358 bound.extend(x);
1359 bound.extend(y);
1360 self
1361 }
1362
1363 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
1368 if let Some(node) = scale.node().live() {
1369 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
1370 self.node().attrs.bound.push(node);
1371 }
1372 self
1373 }
1374
1375 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
1379 if let Some(node) = angle.node().live() {
1380 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
1381 self.node().attrs.bound.push(node);
1382 }
1383 self
1384 }
1385
1386 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1388 self.on(
1389 EventKind::PanStart,
1390 events::typed(listener.into_listener(), events::pan),
1391 )
1392 }
1393
1394 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1396 self.on(
1397 EventKind::PanEnd,
1398 events::typed(listener.into_listener(), events::pan),
1399 )
1400 }
1401
1402 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1404 self.on(
1405 EventKind::PinchStart,
1406 events::typed(listener.into_listener(), events::pinch),
1407 )
1408 }
1409
1410 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1412 self.on(
1413 EventKind::PinchEnd,
1414 events::typed(listener.into_listener(), events::pinch),
1415 )
1416 }
1417
1418 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1420 self.on(
1421 EventKind::RotationStart,
1422 events::typed(listener.into_listener(), events::rotation),
1423 )
1424 }
1425
1426 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1428 self.on(
1429 EventKind::RotationEnd,
1430 events::typed(listener.into_listener(), events::rotation),
1431 )
1432 }
1433
1434 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
1436 self.on(
1437 EventKind::AccessibilityAction,
1438 events::typed(listener.into_listener(), events::action),
1439 )
1440 }
1441
1442 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
1445 self.node().handlers.push((kind, listener.into_listener()));
1446 self
1447 }
1448
1449 fn hit_slop(mut self, insets: EdgeInsets) -> Self {
1451 super::host::set(self.node(), Prop::HitSlop(insets));
1452 self
1453 }
1454
1455 fn long_press_delay(mut self, ms: f32) -> Self {
1457 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
1458 self
1459 }
1460
1461 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
1463 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
1464 self
1465 }
1466
1467 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
1469 super::host::set(self.node(), Prop::Elevation(elevation.into()));
1470 self
1471 }
1472
1473 fn test_id(mut self, id: &str) -> Self {
1475 super::host::set(self.node(), Prop::TestId(Some(id.into())));
1476 self
1477 }
1478
1479 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
1484 super::host::bind_prop(self.node(), enabled, |enabled| {
1485 Prop::WindowDrag(Some(enabled))
1486 });
1487 self
1488 }
1489
1490 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
1494 super::host::bind_prop(self.node(), focusable, |focusable| {
1495 Prop::Focusable(Some(focusable))
1496 });
1497 self
1498 }
1499
1500 fn native_id(mut self, id: &str) -> Self {
1502 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
1503 self
1504 }
1505
1506 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1508 let s = f(StyleRefinement::default());
1509 self.style().extend_as(Variant::ACTIVE, s);
1510 self
1511 }
1512
1513 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1515 let s = f(StyleRefinement::default());
1516 self.style().extend_as(Variant::HOVER, s);
1517 self
1518 }
1519
1520 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1522 let s = f(StyleRefinement::default());
1523 self.style().extend_as(Variant::FOCUS, s);
1524 self
1525 }
1526
1527 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1529 let s = f(StyleRefinement::default());
1530 self.style().extend_as(Variant::DISABLED, s);
1531 self
1532 }
1533
1534 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1536 self.node().bind_attr(disabled, |a, disabled| {
1537 a.disabled = disabled;
1538 a.state.disabled = disabled;
1539 });
1540 self
1541 }
1542
1543 fn pointer_events(mut self, pointer_events: impl IntoReactive<PointerEvents>) -> Self {
1545 self.node()
1546 .bind_attr(pointer_events, |a, p| a.pointer_events = p);
1547 self
1548 }
1549
1550 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
1553 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
1554 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
1555 });
1556 self
1557 }
1558
1559 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
1563 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
1564 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
1565 });
1566 self
1567 }
1568
1569 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
1573 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
1574 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
1575 });
1576 self
1577 }
1578
1579 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
1585 self.node().bind_attr(checked, |a, checked| {
1586 project(a, crate::tailwind::state::CHECKED, checked)
1587 });
1588 self
1589 }
1590
1591 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
1597 self.node().bind_attr(indeterminate, |a, indeterminate| {
1598 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
1599 });
1600 self
1601 }
1602
1603 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1608 self.node().bind_attr(disabled, |a, disabled| {
1609 project(a, crate::tailwind::state::DISABLED, disabled)
1610 });
1611 self
1612 }
1613}
1614
1615fn project(a: &mut Attrs, bit: u8, on: bool) {
1617 if on {
1618 a.projected_states |= bit;
1619 } else {
1620 a.projected_states &= !bit;
1621 }
1622}
1623
1624macro_rules! element {
1625 ($(#[$doc:meta])* $name:ident) => {
1626 $(#[$doc])*
1627 #[derive(Clone)]
1628 pub struct $name(ElNode);
1629
1630 impl Element for $name {
1631 fn node(&mut self) -> &mut ElNode {
1632 &mut self.0
1633 }
1634 }
1635
1636 impl IntoElement for $name {
1637 fn into_element(self) -> AnyElement {
1638 AnyElement(self.0)
1639 }
1640 }
1641
1642 impl Accessible for $name {}
1643
1644 impl IntoTooltip for $name {
1645 fn apply_tooltip(self, node: &mut ElNode) {
1646 self.into_element().apply_tooltip(node);
1647 }
1648 }
1649 };
1650}
1651
1652element! {
1653 View
1655}
1656
1657element! {
1658 Text
1660}
1661
1662element! {
1663 Image
1665}
1666
1667element! {
1668 SlotElement
1671}
1672
1673element! {
1674 ListElement
1676}
1677
1678impl Interactive for View {}
1679impl ParentElement for View {}
1680impl Interactive for SlotElement {}
1681impl Interactive for Text {}
1682impl Interactive for Image {}
1683
1684impl ParentElement for Text {
1689 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1690 let at = self.0.children.len();
1691 child.__push_into(&mut self.0.children);
1692 for el in &mut self.0.children[at..] {
1693 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
1694 }
1695 self
1696 }
1697
1698 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1699 self.0
1700 .children
1701 .extend(children.into_iter().map(|c| span(c.into_element().0)));
1702 self
1703 }
1704}
1705
1706fn span(mut el: ElNode) -> ElNode {
1709 if el.tag == Tag::Text
1710 && matches!(el.kind, ElKind::Plain)
1711 && el.key.is_none()
1712 && el.children.is_empty()
1713 && el.handlers.is_empty()
1714 && el.style.is_empty()
1715 && el.attrs == Attrs::default()
1716 && !el.is_bound()
1717 {
1718 el.kind = ElKind::Raw;
1719 }
1720 el
1721}
1722
1723impl Text {
1724 pub fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
1726 self.0
1727 .bind_attr(lines, |a, lines| a.number_of_lines = lines);
1728 self
1729 }
1730
1731 pub fn ellipsize_mode(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
1733 super::host::bind_prop(&mut self.0, mode, Prop::EllipsizeMode);
1734 self
1735 }
1736
1737 pub fn selectable(mut self, selectable: impl IntoReactive<bool>) -> Self {
1739 super::host::bind_prop(&mut self.0, selectable, |s| Prop::Selectable(Some(s)));
1740 self
1741 }
1742
1743 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
1745 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
1746 Prop::SelectionColor(Some(Color::from(c)))
1747 });
1748 self
1749 }
1750
1751 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
1753 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
1754 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
1755 self
1756 }
1757
1758 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
1761 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
1762 self
1763 }
1764
1765 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
1768 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
1769 self
1770 }
1771}
1772
1773impl Image {
1774 pub fn resize_mode(mut self, mode: impl IntoReactive<crate::ResizeMode>) -> Self {
1776 super::host::bind_prop(&mut self.0, mode, Prop::ResizeMode);
1777 self
1778 }
1779
1780 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
1783 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
1784 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
1785 uri: src.uri.to_arc(),
1786 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
1787 scales: src.scales,
1788 })))
1789 });
1790 self
1791 }
1792
1793 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
1795 Styled::tint_color(self, color)
1796 }
1797
1798 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
1800 super::host::set(
1801 &mut self.0,
1802 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
1803 );
1804 self
1805 }
1806
1807 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
1809 super::host::bind_prop(&mut self.0, ms, |ms| {
1810 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
1811 });
1812 self
1813 }
1814
1815 pub fn on_load<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
1817 self.on(
1818 EventKind::Load,
1819 events::typed(listener.into_listener(), events::size),
1820 )
1821 }
1822
1823 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
1825 self.on(
1826 EventKind::Error,
1827 events::typed(listener.into_listener(), events::message),
1828 )
1829 }
1830
1831 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
1833 self.on(
1834 EventKind::LoadStart,
1835 events::typed(listener.into_listener(), events::unit),
1836 )
1837 }
1838
1839 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
1841 self.on(
1842 EventKind::LoadEnd,
1843 events::typed(listener.into_listener(), events::unit),
1844 )
1845 }
1846
1847 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
1850 self.on(
1851 EventKind::Progress,
1852 events::typed(listener.into_listener(), events::image_progress),
1853 )
1854 }
1855}
1856
1857impl super::Scrollable for ListElement {}
1858
1859impl super::ListLayout for ListElement {
1860 fn config(&mut self) -> &mut ListConfig {
1861 match &mut self.0.kind {
1862 ElKind::List(list) => &mut list.config,
1863 _ => unreachable!("a ListElement is a list"),
1864 }
1865 }
1866
1867 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
1868 &mut self.0.bound_list
1869 }
1870}
1871
1872#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1875pub struct Slot {
1876 name: &'static str,
1877}
1878
1879impl Slot {
1880 pub(crate) fn new(name: &'static str) -> Self {
1881 Self { name }
1882 }
1883
1884 pub fn name(&self) -> &'static str {
1886 self.name
1887 }
1888
1889 pub fn element(self) -> SlotElement {
1891 let mut node = ElNode::new(Tag::View);
1892 node.kind = ElKind::Slot(self.name);
1893 SlotElement(node)
1894 }
1895}
1896
1897#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1901pub struct Items {
1902 name: &'static str,
1903}
1904
1905impl Items {
1906 #[doc(hidden)]
1907 pub const fn __new(name: &'static str) -> Self {
1908 Self { name }
1909 }
1910}
1911
1912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1916pub struct Child(ChildRef);
1917
1918#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1919enum ChildRef {
1920 Js(NodeId),
1921 Row,
1922}
1923
1924impl Child {
1925 pub(crate) fn js(id: NodeId) -> Self {
1926 Self(ChildRef::Js(id))
1927 }
1928
1929 pub(crate) fn row() -> Self {
1930 Self(ChildRef::Row)
1931 }
1932}
1933
1934impl IntoElement for Child {
1935 fn into_element(self) -> AnyElement {
1936 let mut node = ElNode::new(Tag::View);
1937 node.kind = match self.0 {
1938 ChildRef::Js(id) => ElKind::JsChild(id),
1939 ChildRef::Row => ElKind::Children,
1940 };
1941 AnyElement(node)
1942 }
1943}
1944
1945pub fn view() -> View {
1947 View(ElNode::new(Tag::View))
1948}
1949
1950pub fn text(content: impl IntoReactive<SharedString>) -> Text {
1953 let mut node = ElNode::new(Tag::Text);
1954 match content.into_reactive() {
1955 Reactive::Static(content) => node.text = Some(content),
1956 Reactive::Bound(content) => {
1957 node.text = Some(SharedString::default());
1958 node.bound_text = Some(content);
1959 }
1960 }
1961 Text(node)
1962}
1963
1964pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
1968 let mut node = ElNode::new(Tag::Image);
1969 node.bind_attr(src, |a, src| a.src = Some(src));
1970 Image(node)
1971}
1972
1973#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1976pub struct Children {
1977 present: bool,
1978}
1979
1980impl Children {
1981 pub(crate) fn new(present: bool) -> Self {
1982 Self { present }
1983 }
1984
1985 pub fn is_empty(&self) -> bool {
1987 !self.present
1988 }
1989}
1990
1991impl IntoElement for Children {
1992 fn into_element(self) -> AnyElement {
1993 let mut node = ElNode::new(Tag::View);
1994 node.kind = ElKind::Children;
1995 AnyElement(node)
1996 }
1997}
1998
1999pub struct ComponentElement<C: Component> {
2011 node: ElNode,
2012 _component: PhantomData<fn() -> C>,
2013}
2014
2015impl<C: Component> ComponentElement<C> {
2016 #[doc(hidden)]
2019 pub fn __new(props: C::Props) -> Self {
2020 Self::new(props)
2021 }
2022
2023 #[doc(hidden)]
2025 pub fn __props_mut(&mut self) -> &mut C::Props {
2026 match &mut self.node.kind {
2027 ElKind::Component(c) => c
2028 .props
2029 .as_any_mut()
2030 .downcast_mut::<C::Props>()
2031 .expect("a component element holds its component's props"),
2032 _ => unreachable!("a component element is a component's"),
2033 }
2034 }
2035
2036 pub(crate) fn new(props: C::Props) -> Self {
2037 let mut node = ElNode::new(Tag::View);
2038 node.kind = ElKind::Component(ComponentEl {
2039 name: super::component::name_of::<C>(),
2040 make: super::component::make_instance::<C>,
2041 spec: ComponentSpec::of::<C>,
2042 props: Box::new(props),
2043 on_event: Vec::new(),
2044 });
2045 Self {
2046 node,
2047 _component: PhantomData,
2048 }
2049 }
2050
2051 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2056 self.node
2057 .children
2058 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2059 let mut fill = ElNode::new(Tag::View);
2060 fill.kind = ElKind::Fill(slot);
2061 fill.children.push(content.into_element().0);
2062 self.node.children.push(fill);
2063 self
2064 }
2065
2066 pub fn items(mut self, list: super::VirtualList) -> Self {
2074 match <C::Props as super::Props>::ITEMS {
2075 Some(name) => self.node.children.push(list.into_items(name)),
2076 None => {
2077 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2078 }
2079 }
2080 self
2081 }
2082
2083 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2088 let s = f(StyleRefinement::default());
2089 self.node.style.extend_as(Variant::ACTIVE, s);
2090 self
2091 }
2092
2093 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2095 let s = f(StyleRefinement::default());
2096 self.node.style.extend_as(Variant::HOVER, s);
2097 self
2098 }
2099
2100 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2102 let s = f(StyleRefinement::default());
2103 self.node.style.extend_as(Variant::FOCUS, s);
2104 self
2105 }
2106
2107 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2110 let s = f(StyleRefinement::default());
2111 self.node.style.extend_as(Variant::DISABLED, s);
2112 self
2113 }
2114
2115 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2117 self.node.attrs.element_ref = handle.element().target();
2118 self
2119 }
2120
2121 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
2127 let listener = listener.into_listener();
2128 if let ElKind::Component(c) = &mut self.node.kind {
2129 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
2130 if let Some(event) = event.downcast_ref::<C::Event>() {
2131 inner(event);
2132 }
2133 }));
2134 }
2135 self
2136 }
2137
2138 #[doc(hidden)]
2142 pub fn __on_variant<T: ?Sized + 'static, M>(
2143 self,
2144 pick: fn(&C::Event) -> Option<&T>,
2145 listener: impl IntoListener<T, M>,
2146 ) -> Self {
2147 let listener = listener.into_listener();
2148 self.on_event(listener.wrap(move |inner, event: &C::Event| {
2149 if let Some(data) = pick(event) {
2150 inner(data);
2151 }
2152 }))
2153 }
2154}
2155
2156pub trait ComponentBuilder: Element {
2228 type Component: Component;
2230
2231 #[doc(hidden)]
2233 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
2234
2235 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2240 let s = f(StyleRefinement::default());
2241 self.node().style.extend_as(Variant::ACTIVE, s);
2242 self
2243 }
2244
2245 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2247 let s = f(StyleRefinement::default());
2248 self.node().style.extend_as(Variant::HOVER, s);
2249 self
2250 }
2251
2252 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2254 let s = f(StyleRefinement::default());
2255 self.node().style.extend_as(Variant::FOCUS, s);
2256 self
2257 }
2258
2259 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2262 let s = f(StyleRefinement::default());
2263 self.node().style.extend_as(Variant::DISABLED, s);
2264 self
2265 }
2266
2267 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
2269 self.__element().node.attrs.element_ref = handle.element().target();
2270 self
2271 }
2272}
2273
2274impl<C: Component> Element for ComponentElement<C> {
2275 fn node(&mut self) -> &mut ElNode {
2276 &mut self.node
2277 }
2278}
2279
2280impl<C: Component> ParentElement for ComponentElement<C> {}
2284
2285impl<C: Component> IntoElement for ComponentElement<C> {
2286 fn into_element(self) -> AnyElement {
2287 AnyElement(self.node)
2288 }
2289}