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, Hsla, ImageSource, ListContentStyle,
15 MouseEvent, NativeProp, NodeId, PointerEvents, Points, PressEvent, Prop, Size, Tag, TouchEvent,
16 geometry::{DevicePixels, Radians},
17 style::Color,
18};
19
20pub struct Listener<E: ?Sized> {
27 f: Rc<dyn Fn(&E)>,
28 owner: super::Owner,
29}
30
31impl<E: ?Sized + 'static> Listener<E> {
32 pub(crate) fn noop() -> Self {
34 Self::new(Rc::new(|_| {}))
35 }
36
37 fn new(f: Rc<dyn Fn(&E)>) -> Self {
38 Self {
39 f,
40 owner: super::Owner::current_or_detached(),
41 }
42 }
43
44 pub(crate) fn same_owner(&self, other: &Self) -> bool {
46 self.owner == other.owner
47 }
48
49 pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
51 self.same_owner(other) && Rc::ptr_eq(&self.f, &other.f)
52 }
53
54 pub(crate) fn call(&self, event: &E) {
57 if self.owner == super::Owner::detached() {
58 (self.f)(event);
59 } else if self.owner.is_live() {
60 self.owner.scope(|| (self.f)(event));
61 }
62 }
63
64 pub(crate) fn wrap<F: ?Sized>(self, f: impl Fn(&dyn Fn(&E), &F) + 'static) -> Listener<F> {
67 let inner = self.f;
68 Listener {
69 f: Rc::new(move |event: &F| f(&*inner, event)),
70 owner: self.owner,
71 }
72 }
73}
74
75impl<E: 'static> Listener<E> {
76 pub fn map<F: ?Sized + 'static>(self, f: impl Fn(&F) -> E + 'static) -> Listener<F> {
78 self.wrap(move |inner, event: &F| inner(&f(event)))
79 }
80}
81
82impl<E: ?Sized + 'static, F: Fn(&E) + 'static> From<F> for Listener<E> {
84 fn from(f: F) -> Self {
85 Self::new(Rc::new(f))
86 }
87}
88
89#[diagnostic::on_unimplemented(
97 message = "`{Self}` is not a listener of `{E}`",
98 label = "not a listener of `{E}`",
99 note = "a listener is a closure `move |event: &{E}| ..` (`move || ..` for an event without data) or a `Listener<{E}>`"
100)]
101pub trait IntoListener<E: ?Sized, M> {
102 fn into_listener(self) -> Listener<E>;
104}
105
106#[doc(hidden)]
108pub struct OfEvent(());
109
110#[doc(hidden)]
113pub struct WithoutEvent(());
114
115impl<E: ?Sized> IntoListener<E, ()> for Listener<E> {
116 fn into_listener(self) -> Listener<E> {
117 self
118 }
119}
120
121impl<E: ?Sized + 'static, F: Fn(&E) + 'static> IntoListener<E, OfEvent> for F {
122 fn into_listener(self) -> Listener<E> {
123 Listener::new(Rc::new(self))
124 }
125}
126
127impl<F: Fn() + 'static> IntoListener<(), WithoutEvent> for F {
128 fn into_listener(self) -> Listener<()> {
129 Listener::new(Rc::new(move |_: &()| self()))
130 }
131}
132
133#[doc(hidden)]
136pub struct OfUnit(());
137
138impl<F: Fn() + 'static> IntoListener<PressEvent, WithoutEvent> for F {
140 fn into_listener(self) -> Listener<PressEvent> {
141 Listener::new(Rc::new(move |_: &PressEvent| self()))
142 }
143}
144
145impl<F: Fn(&()) + 'static> IntoListener<PressEvent, OfUnit> for F {
147 fn into_listener(self) -> Listener<PressEvent> {
148 Listener::new(Rc::new(move |_: &PressEvent| self(&())))
149 }
150}
151
152impl IntoListener<PressEvent, ()> for Listener<()> {
154 fn into_listener(self) -> Listener<PressEvent> {
155 self.map(|_: &PressEvent| ())
156 }
157}
158
159impl<E: ?Sized> Clone for Listener<E> {
160 fn clone(&self) -> Self {
161 Self {
162 f: self.f.clone(),
163 owner: self.owner,
164 }
165 }
166}
167
168pub(crate) trait AnyEvent: super::EventToJs {
171 fn as_any(&self) -> &dyn Any;
172}
173
174impl<E: Event> super::EventToJs for E {
175 fn name(&self) -> &'static str {
176 Event::name(self)
177 }
178
179 fn data_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
180 Event::data_js(self, host)
181 }
182}
183
184impl<E: Event> AnyEvent for E {
185 fn as_any(&self) -> &dyn Any {
186 self
187 }
188}
189
190#[doc(hidden)]
192#[derive(Debug, Clone, Default, PartialEq)]
193pub struct Attrs {
194 pub(crate) disabled: bool,
195 pub(crate) accessible: Option<bool>,
196 pub(crate) label: Option<SharedString>,
197 pub(crate) hint: Option<SharedString>,
198 pub(crate) role: AccessibilityRole,
199 pub(crate) state: AccessibilityState,
200 pub(crate) value: Option<AccessibilityValue>,
201 pub(crate) pointer_events: PointerEvents,
203 pub(crate) src: Option<super::ImageSrc>,
204 pub(crate) inset_padding: Option<EdgeInsets>,
205 pub(crate) inset_margin: Option<EdgeInsets>,
206 pub(crate) inline: Option<std::rc::Rc<crate::StylePatch>>,
208 pub(crate) props: Vec<Prop>,
211 pub(crate) drawing: Option<Arc<crate::canvas::Drawing>>,
213 pub(crate) element_ref: Option<super::element_ref::RefTarget>,
216 pub(crate) animated: Vec<(crate::StyleDecl, super::LiveNode)>,
219 pub(crate) bound: Vec<super::LiveNode>,
221 pub(crate) class: Option<SharedString>,
224 pub(crate) selectable_view: bool,
226 pub(crate) projected_states: u16,
229 pub(crate) projected_data: Vec<&'static str>,
232 pub(crate) render: Option<super::renderer::RenderAt>,
235}
236
237impl Attrs {
238 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
240 use AccessibilityProp as A;
241 if self.disabled != old.disabled {
242 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
243 }
244 if self.accessible != old.accessible {
245 out.push(Prop::Accessibility(A::Accessible(self.accessible)));
246 }
247 if self.label != old.label {
248 out.push(Prop::Accessibility(A::Label(
249 self.label.as_ref().map(SharedString::to_arc),
250 )));
251 }
252 if self.hint != old.hint {
253 out.push(Prop::Accessibility(A::Hint(
254 self.hint.as_ref().map(SharedString::to_arc),
255 )));
256 }
257 if self.role != old.role {
258 out.push(Prop::Accessibility(A::Role(self.role)));
259 }
260 if self.state != old.state {
261 out.push(Prop::Accessibility(A::State(self.state)));
262 }
263 if self.value != old.value {
264 out.push(Prop::Accessibility(A::Value(self.value.clone())));
265 }
266 if self.pointer_events != old.pointer_events {
267 out.push(Prop::PointerEvents(self.pointer_events));
268 }
269 if self.src != old.src {
270 out.push(Prop::Source(self.src.as_ref().map(|src| ImageSource {
271 uri: src.uri.to_arc(),
272 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
273 scales: src.scales,
274 data: src.data.clone(),
275 })));
276 }
277 if self.inset_padding != old.inset_padding {
278 out.push(Prop::InsetPadding(self.inset_padding.unwrap_or_default()));
279 }
280 if self.inset_margin != old.inset_margin {
281 out.push(Prop::InsetMargin(self.inset_margin.unwrap_or_default()));
282 }
283 if self.selectable_view != old.selectable_view {
284 out.push(Prop::SelectableView(self.selectable_view));
285 }
286 if self.projected_states != old.projected_states {
287 out.push(Prop::ProjectedStates(self.projected_states));
288 }
289 if self.projected_data != old.projected_data {
290 out.push(Prop::ProjectedData(self.projected_data.as_slice().into()));
291 }
292 for prop in &old.props {
295 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
296 && let Some(reset) = super::host::reset(prop)
297 {
298 out.push(reset);
299 }
300 }
301 for prop in &self.props {
302 if !old.props.contains(prop) {
303 out.push(prop.clone());
304 }
305 }
306 }
307}
308
309pub(crate) trait AnyProps {
311 fn as_any(&self) -> &dyn Any;
312 fn as_any_mut(&mut self) -> &mut dyn Any;
313 fn clone_box(&self) -> Box<dyn AnyProps>;
314}
315
316impl<P: Clone + 'static> AnyProps for P {
317 fn as_any(&self) -> &dyn Any {
318 self
319 }
320
321 fn as_any_mut(&mut self) -> &mut dyn Any {
322 self
323 }
324
325 fn clone_box(&self) -> Box<dyn AnyProps> {
326 Box::new(self.clone())
327 }
328}
329
330pub(crate) struct ComponentEl {
332 pub(crate) name: &'static str,
333 pub(crate) make: fn() -> Box<dyn AnyInstance>,
336 pub(crate) spec: fn() -> ComponentSpec,
338 pub(crate) props: Box<dyn AnyProps>,
339 pub(crate) on_event: Vec<Listener<dyn Any>>,
341}
342
343impl Clone for ComponentEl {
344 fn clone(&self) -> Self {
345 Self {
346 name: self.name,
347 make: self.make,
348 spec: self.spec,
349 props: self.props.clone_box(),
350 on_event: self.on_event.clone(),
351 }
352 }
353}
354
355pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
357
358#[derive(Clone, Copy)]
364pub struct Position {
365 index: super::reactive::Node,
366 count: super::reactive::Node,
367}
368
369impl Position {
370 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
373 Self { index, count }
374 }
375
376 pub(crate) fn fixed(index: usize, count: usize) -> Self {
378 Self::of(super::signal(index).node(), super::signal(count).node())
379 }
380
381 #[track_caller]
383 pub fn index(&self) -> usize {
384 self.index.with("a position", |i: &usize| *i)
385 }
386
387 #[track_caller]
389 pub fn count(&self) -> usize {
390 self.count.with("a position", |n: &usize| *n)
391 }
392
393 #[track_caller]
395 pub fn is_first(&self) -> bool {
396 self.index() == 0
397 }
398
399 #[track_caller]
401 pub fn is_last(&self) -> bool {
402 self.index() + 1 == self.count()
403 }
404}
405
406impl fmt::Debug for Position {
407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 let (index, count) = super::untracked(|| (self.index(), self.count()));
409 write!(f, "Position({index} of {count})")
410 }
411}
412
413#[doc(hidden)]
416#[derive(Debug, Clone, Copy, Default, PartialEq)]
417pub struct ListConfig {
418 pub(crate) estimated: Option<f32>,
419 pub(crate) columns: Option<u32>,
420 pub(crate) horizontal: Option<bool>,
421 pub(crate) inverted: Option<bool>,
422 pub(crate) scrollbar_visible: Option<bool>,
423 pub(crate) content: Option<ListContentStyle>,
424 pub(crate) follow_end: Option<f32>,
425 pub(crate) viewport: Option<crate::ListViewport>,
426}
427
428impl ListConfig {
429 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
431 if self.estimated != old.estimated {
432 out.push(Prop::EstimatedItemSize(Points(
433 self.estimated.unwrap_or(50.0),
434 )));
435 }
436 if self.columns != old.columns {
437 out.push(Prop::Columns(self.columns.unwrap_or(1)));
438 }
439 if self.horizontal != old.horizontal {
440 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
441 }
442 if self.inverted != old.inverted {
443 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
444 }
445 if self.scrollbar_visible != old.scrollbar_visible {
446 out.push(Prop::Scrollbar(
447 self.scrollbar_visible.unwrap_or(true).into(),
448 ));
449 }
450 if self.content != old.content {
451 out.push(Prop::ListContent(self.content.unwrap_or_default()));
452 }
453 if self.follow_end != old.follow_end {
454 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
455 }
456 if self.viewport != old.viewport {
457 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
458 }
459 }
460}
461
462#[derive(Clone)]
464pub(crate) struct ListEl {
465 pub(crate) name: &'static str,
466 pub(crate) config: ListConfig,
467 pub(crate) row: PlaceFn,
468}
469
470#[derive(Clone)]
472pub(crate) enum ElKind {
473 Plain,
474 Slot(&'static str),
476 Fill(&'static str),
479 Filled(&'static str),
482 Children,
484 JsChild(NodeId),
486 EachChild(PlaceFn),
488 List(Box<ListEl>),
490 VirtualList(Box<super::virtual_list::VirtualListEl>),
492 Raw,
495 Component(ComponentEl),
496 Region(super::flow::Region),
500 Keep,
503}
504
505#[doc(hidden)]
507#[derive(Clone)]
508pub struct ElNode {
509 pub(crate) tag: Tag,
510 pub(crate) key: Option<SharedString>,
511 pub(crate) text: Option<SharedString>,
513 pub(crate) attrs: Attrs,
514 pub(crate) style: StyleRefinement,
515 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
516 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
518 pub(crate) children: Vec<ElNode>,
519 pub(crate) kind: ElKind,
520 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
522 pub(crate) bound_attrs: Vec<BoundAttrs>,
524 pub(crate) bound_list: Vec<BoundListConfig>,
526}
527
528#[doc(hidden)]
530pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
531
532crate::static_reactive!(AccessibilityState: AccessibilityState);
533crate::static_reactive!(EdgeInsets: EdgeInsets);
534crate::static_reactive!(Style: Style);
535crate::static_reactive!(PointerEvents: PointerEvents);
536
537pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
539
540impl ElNode {
541 pub(crate) fn bind_attr<T: 'static>(
544 &mut self,
545 value: impl IntoReactive<T>,
546 apply: impl Fn(&mut Attrs, T) + 'static,
547 ) {
548 match value.into_reactive() {
549 Reactive::Static(v) => apply(&mut self.attrs, v),
550 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
551 }
552 }
553
554 pub(crate) fn is_bound(&self) -> bool {
556 self.bound_text.is_some()
557 || !self.bound_attrs.is_empty()
558 || self.style.is_bound()
559 || !self.bound_list.is_empty()
560 }
561
562 pub(crate) fn resolved_attrs(&self) -> Attrs {
565 let mut attrs = self.attrs.clone();
566 for part in &self.bound_attrs {
567 part(&mut attrs);
568 }
569 attrs
570 }
571
572 pub(crate) fn resolve_once(&mut self) {
575 if !self.is_bound() {
576 return;
577 }
578 super::untracked(|| {
579 if let Some(text) = self.bound_text.take() {
580 self.text = Some(text());
581 }
582 if !self.bound_attrs.is_empty() {
583 self.attrs = self.resolved_attrs();
584 self.bound_attrs.clear();
585 }
586 if self.style.is_bound() {
587 self.style = self.style.resolved();
588 }
589 let parts = std::mem::take(&mut self.bound_list);
590 if let Some(config) = self.list_config() {
591 for part in &parts {
592 part(config);
593 }
594 }
595 });
596 }
597
598 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
600 match &mut self.kind {
601 ElKind::List(list) => Some(&mut list.config),
602 ElKind::VirtualList(list) => Some(&mut list.config),
603 _ => None,
604 }
605 }
606
607 pub(crate) fn empty_view() -> Self {
609 Self::new(Tag::View)
610 }
611
612 pub(crate) fn new(tag: Tag) -> Self {
613 Self {
614 tag,
615 key: None,
616 text: None,
617 attrs: Attrs::default(),
618 style: StyleRefinement::default(),
619 handlers: Vec::new(),
620 responder: None,
621 children: Vec::new(),
622 kind: ElKind::Plain,
623 bound_text: None,
624 bound_attrs: Vec::new(),
625 bound_list: Vec::new(),
626 }
627 }
628}
629
630pub struct AnyElement(pub(crate) ElNode);
632
633pub trait IntoElement {
635 fn into_element(self) -> AnyElement;
637}
638
639impl IntoElement for AnyElement {
640 fn into_element(self) -> AnyElement {
641 self
642 }
643}
644
645impl IntoElement for SharedString {
646 fn into_element(self) -> AnyElement {
647 text(self).into_element()
648 }
649}
650
651impl IntoElement for &'static str {
652 fn into_element(self) -> AnyElement {
653 text(self).into_element()
654 }
655}
656
657impl IntoElement for String {
658 fn into_element(self) -> AnyElement {
659 text(self).into_element()
660 }
661}
662
663#[diagnostic::on_unimplemented(
669 message = "`{Self}` is not an element",
670 label = "not an element",
671 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
672)]
673pub trait IntoChild<M> {
674 #[doc(hidden)]
676 fn __push_into(self, out: &mut Vec<ElNode>);
677}
678
679#[doc(hidden)]
681pub struct OneChild(());
682
683#[doc(hidden)]
685pub struct ManyChildren(());
686
687impl<T: IntoElement> IntoChild<OneChild> for T {
688 fn __push_into(self, out: &mut Vec<ElNode>) {
689 out.push(self.into_element().0);
690 }
691}
692
693impl<I: IntoIterator> IntoChild<ManyChildren> for I
694where
695 I::Item: IntoElement,
696{
697 fn __push_into(self, out: &mut Vec<ElNode>) {
698 out.extend(self.into_iter().map(|c| c.into_element().0));
699 }
700}
701
702pub trait FluentBuilder: Sized {
706 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
708 if condition { then(self) } else { self }
709 }
710
711 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
713 match option {
714 Some(v) => then(self, v),
715 None => self,
716 }
717 }
718
719 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
721 f(self)
722 }
723}
724
725impl<T: Element> FluentBuilder for T {}
726
727pub trait Element: IntoElement + Sized {
731 #[doc(hidden)]
732 fn node(&mut self) -> &mut ElNode;
733
734 fn key(mut self, key: impl Into<SharedString>) -> Self {
737 self.node().key = Some(key.into());
738 self
739 }
740
741 fn bind_opacity(self, value: &impl super::Animated) -> Self {
743 self.bind(crate::animation::AnimationProp::Opacity, value)
744 }
745
746 fn bind_background(self, value: &impl super::Animated) -> Self {
749 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
750 }
751
752 fn bind_border_color(self, value: &impl super::Animated) -> Self {
754 self.bind(crate::animation::AnimationProp::BorderColor, value)
755 }
756
757 fn bind_color(self, value: &impl super::Animated) -> Self {
759 self.bind(crate::animation::AnimationProp::Color, value)
760 }
761
762 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
765 if let Some(node) = value.animated_node().live() {
766 let decl = crate::StyleDecl::Animated(prop, node.id());
767 self.node().attrs.animated.push((decl, node));
768 }
769 self
770 }
771
772 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
777 self.bind(crate::animation::AnimationProp::StickyTop, value)
778 }
779
780 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
782 self.bind(crate::animation::AnimationProp::StickyLeft, value)
783 }
784
785 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
788 if let Some(node) = value.animated_node().live() {
789 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
790 self.node().attrs.animated.push((decl, node));
791 }
792 self
793 }
794
795 fn bind_motion(self, motion: &super::Motion) -> Self {
799 use crate::animation::MotionChannel::*;
800 let mut this = self.bind_opacity(&motion.value(Opacity));
801 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
802 if let Some(kind) = channel.transform() {
803 this = this.bind_transform(kind, &motion.value(channel));
804 }
805 }
806 let scale = motion.value(Scale);
807 this.bind_transform(
808 crate::TransformKind::ScaleX,
809 &scale.mul(&motion.value(ScaleX)),
810 )
811 .bind_transform(
812 crate::TransformKind::ScaleY,
813 &scale.mul(&motion.value(ScaleY)),
814 )
815 }
816
817 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
819 self.bind_transform(crate::TransformKind::TranslateX, value)
820 }
821
822 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
824 self.bind_transform(crate::TransformKind::TranslateY, value)
825 }
826
827 fn bind_scale(self, value: &impl super::Animated) -> Self {
829 self.bind_transform(crate::TransformKind::Scale, value)
830 }
831
832 fn bind_rotate(self, value: &impl super::Animated) -> Self {
834 self.bind_transform(crate::TransformKind::Rotate, value)
835 }
836
837 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
840 self.node().attrs.element_ref = handle.target();
841 self
842 }
843
844 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
847 self.node()
848 .bind_attr(insets, |a, insets| a.inset_padding = Some(insets));
849 self
850 }
851
852 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
854 self.node()
855 .bind_attr(insets, |a, insets| a.inset_margin = Some(insets));
856 self
857 }
858
859 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
862 Style::apply(self.node(), style, Variant::default(), |a, patch| {
863 a.inline = patch
864 });
865 self
866 }
867
868 fn state_inline_style(mut self, style: impl Fn() -> Style + 'static) -> Self {
873 Style::apply_bound(
874 self.node(),
875 Rc::new(style),
876 Variant::default(),
877 true,
878 |a, patch| a.inline = patch,
879 );
880 self
881 }
882
883 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
888 self.node()
889 .bind_attr(area, |a, area| a.selectable_view = area);
890 self
891 }
892
893 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
898 self.node().bind_attr(class, |a, class| a.class = class);
899 self
900 }
901}
902
903#[derive(Debug, Clone, Default, PartialEq)]
917pub struct Style(
918 pub(crate) Option<std::rc::Rc<crate::StylePatch>>,
919 pub(crate) StyleRefinement,
922);
923
924impl Style {
925 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
929 let mut style = crate::Style::default();
930 let mut patch = crate::StylePatch::default();
931 for decl in decls {
932 let key = match &decl {
933 crate::StyleDecl::Set(key, _) => Some(*key),
934 _ => None,
935 };
936 if patch.push(&mut style, decl).is_err()
937 && let Some(key) = key
938 {
939 log::warn!("invalid value for style `{}`", key.name());
940 }
941 }
942 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
943 }
944
945 pub fn with(self, key: crate::StyleKey, value: crate::PropertyValue) -> Self {
948 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
949 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
950 style.1 = self.1;
951 style
952 }
953
954 pub fn then(&self, over: &Style) -> Self {
958 if over.0.is_none() && over.1.is_empty() {
959 return self.clone();
960 }
961 if self.0.is_none() && self.1.is_empty() {
962 return over.clone();
963 }
964 let mut style = if self.0.is_none() {
965 Self(over.0.clone(), StyleRefinement::default())
966 } else if over.0.is_none() {
967 Self(self.0.clone(), StyleRefinement::default())
968 } else {
969 Self::from_decls(self.decls().iter().chain(over.decls()).cloned())
970 };
971 let mut typed = self.1.clone();
972 typed.extend_as(Variant::default(), over.1.clone());
973 style.1 = typed;
974 style
975 }
976
977 pub fn decls(&self) -> &[crate::StyleDecl] {
979 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
980 }
981
982 pub(crate) fn apply(
988 node: &mut ElNode,
989 style: impl IntoReactive<Style>,
990 variant: Variant,
991 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
992 ) {
993 match style.into_reactive() {
994 Reactive::Static(Style(patch, typed)) => {
995 attr(&mut node.attrs, patch);
996 if !typed.is_empty() {
997 node.style.extend_as(variant, typed);
998 }
999 }
1000 Reactive::Bound(f) => Self::apply_bound(node, f, variant, false, attr),
1001 }
1002 }
1003
1004 pub(crate) fn apply_bound(
1007 node: &mut ElNode,
1008 f: Rc<dyn Fn() -> Style>,
1009 variant: Variant,
1010 typed_later: bool,
1011 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1012 ) {
1013 let typed = typed_later || super::untracked(|| !f().1.is_empty());
1014 let patch = f.clone();
1015 node.bind_attr(move || patch().0, attr);
1016 if typed {
1017 node.style
1020 .bind(move |s| s.extend_as(variant, f().1.resolved()));
1021 }
1022 }
1023}
1024
1025impl From<crate::StylePatch> for Style {
1026 fn from(patch: crate::StylePatch) -> Self {
1027 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1028 }
1029}
1030
1031impl From<StyleRefinement> for Style {
1032 fn from(style: StyleRefinement) -> Self {
1033 Self(None, style)
1034 }
1035}
1036
1037impl JsValue for Style {
1038 fn ts_type(_types: &mut super::TsTypes) -> String {
1039 "StyleProp<ViewStyle>".into()
1040 }
1041
1042 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1045 if value.is_nullish() {
1046 return Ok(Self::default());
1047 }
1048 Ok(Self::from(value.host().style(value.raw())?))
1049 }
1050
1051 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1053 Err(PropError("a style does not convert back to JS".to_owned()))
1054 }
1055}
1056
1057#[derive(Debug, Clone, Default, PartialEq)]
1065#[non_exhaustive]
1066pub struct TextPartStyle(pub Style);
1067
1068impl From<Style> for TextPartStyle {
1069 fn from(style: Style) -> Self {
1070 Self(style)
1071 }
1072}
1073
1074impl From<StyleRefinement> for TextPartStyle {
1075 fn from(style: StyleRefinement) -> Self {
1076 Self(Style::from(style))
1077 }
1078}
1079
1080impl From<TextPartStyle> for Style {
1081 fn from(style: TextPartStyle) -> Self {
1082 style.0
1083 }
1084}
1085
1086impl JsValue for TextPartStyle {
1087 fn ts_type(_types: &mut super::TsTypes) -> String {
1088 "StyleProp<TextStyle>".into()
1089 }
1090
1091 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1092 Style::from_js(value).map(Self)
1093 }
1094
1095 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1096 self.0.to_js(host)
1097 }
1098}
1099
1100#[derive(Debug, Clone, Default, PartialEq)]
1106#[non_exhaustive]
1107pub struct InputPartStyle(pub Style);
1108
1109impl From<Style> for InputPartStyle {
1110 fn from(style: Style) -> Self {
1111 Self(style)
1112 }
1113}
1114
1115impl From<StyleRefinement> for InputPartStyle {
1116 fn from(style: StyleRefinement) -> Self {
1117 Self(Style::from(style))
1118 }
1119}
1120
1121impl From<InputPartStyle> for Style {
1122 fn from(style: InputPartStyle) -> Self {
1123 style.0
1124 }
1125}
1126
1127impl JsValue for InputPartStyle {
1128 fn ts_type(_types: &mut super::TsTypes) -> String {
1129 "StyleProp<InputStyle>".into()
1130 }
1131
1132 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1133 Style::from_js(value).map(Self)
1134 }
1135
1136 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1137 self.0.to_js(host)
1138 }
1139}
1140
1141impl<T: Element> Styled for T {
1142 fn style(&mut self) -> &mut StyleRefinement {
1143 &mut self.node().style
1144 }
1145}
1146
1147pub trait ParentElement: Element {
1149 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1152 child.__push_into(&mut self.node().children);
1153 self
1154 }
1155
1156 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1158 self.node()
1159 .children
1160 .extend(children.into_iter().map(|c| c.into_element().0));
1161 self
1162 }
1163
1164 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1167 if let Some(slot) = slot {
1168 let mut node = ElNode::new(Tag::View);
1169 node.kind = ElKind::Slot(slot.name);
1170 self.node().children.push(place(SlotElement(node)).0);
1171 }
1172 self
1173 }
1174
1175 fn children_each<R: IntoElement>(
1178 mut self,
1179 children: impl Into<Children>,
1180 place: impl Fn(Child, Position) -> R + 'static,
1181 ) -> Self {
1182 let _ = children.into();
1183 let mut node = ElNode::new(Tag::View);
1184 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1185 self.node().children.push(node);
1186 self
1187 }
1188
1189 fn list<R: IntoElement>(
1195 mut self,
1196 items: Items,
1197 config: impl FnOnce(ListElement) -> ListElement,
1198 row: impl Fn(Child, Position) -> R + 'static,
1199 ) -> Self {
1200 let mut node = ElNode::new(Tag::List);
1201 node.kind = ElKind::List(Box::new(ListEl {
1202 name: items.name,
1203 config: ListConfig::default(),
1204 row: Rc::new(move |content, at| row(content, at).into_element()),
1205 }));
1206 self.node().children.push(config(ListElement(node)).0);
1207 self
1208 }
1209}
1210
1211pub trait Accessible: Element {
1213 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1215 self.node()
1216 .bind_attr(accessible, |a, accessible| a.accessible = Some(accessible));
1217 self
1218 }
1219
1220 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1222 self.node()
1223 .bind_attr(label, |a, label| a.label = Some(label));
1224 self
1225 }
1226
1227 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1230 self.node().bind_attr(label, |a, label| a.label = label);
1231 self
1232 }
1233
1234 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1236 self.node().bind_attr(hint, |a, hint| a.hint = Some(hint));
1237 self
1238 }
1239
1240 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1242 self.node().bind_attr(role, |a, role| a.role = role);
1243 self
1244 }
1245
1246 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1249 self.node().bind_attr(state, |a, state| {
1250 a.state = AccessibilityState {
1251 disabled: a.state.disabled,
1252 ..state
1253 };
1254 });
1255 self
1256 }
1257
1258 fn accessibility_level(mut self, level: impl IntoReactive<u32>) -> Self {
1262 self.node().bind_attr(level, |a, level| {
1263 super::host::set_in(
1264 &mut a.props,
1265 Prop::Accessibility(AccessibilityProp::Level((level > 0).then_some(level))),
1266 )
1267 });
1268 self
1269 }
1270
1271 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1275 self.node().bind_attr(value, |a, value| a.value = value);
1276 self
1277 }
1278
1279 fn accessibility_elements_hidden(mut self, hidden: impl IntoReactive<bool>) -> Self {
1285 self.node().bind_attr(hidden, |a, hidden| {
1286 super::host::set_in(
1287 &mut a.props,
1288 Prop::Accessibility(AccessibilityProp::Hidden(hidden)),
1289 )
1290 });
1291 self
1292 }
1293
1294 fn accessibility_actions(mut self, actions: Vec<crate::AccessibilityActionDef>) -> Self {
1299 super::host::set(
1300 self.node(),
1301 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1302 );
1303 self
1304 }
1305}
1306
1307pub trait IntoTooltip {
1310 #[doc(hidden)]
1311 fn apply_tooltip(self, node: &mut ElNode);
1312}
1313
1314impl IntoTooltip for AnyElement {
1315 fn apply_tooltip(self, node: &mut ElNode) {
1316 let mut hint = ElNode::new(Tag::Overlay);
1318 hint.key = Some("tooltip".into());
1319 hint.attrs.pointer_events = PointerEvents::None;
1320 let gap = Points(4.0);
1321 for prop in [
1322 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1323 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1324 crate::OverlayProp::Offset(gap),
1325 crate::OverlayProp::Margin(gap),
1326 ] {
1327 super::host::set(&mut hint, Prop::Overlay(prop));
1328 }
1329 hint.children.push(self.0);
1330 node.children.push(hint);
1331 }
1332}
1333
1334impl<C: Component> IntoTooltip for ComponentElement<C> {
1335 fn apply_tooltip(self, node: &mut ElNode) {
1336 self.into_element().apply_tooltip(node);
1337 }
1338}
1339
1340#[doc(hidden)]
1345pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1346 let mut hint = hint.0;
1347 hint.key = Some("tooltip".into());
1348 node.children.push(hint);
1349}
1350
1351pub trait Interactive: Element {
1353 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1359 tooltip.apply_tooltip(self.node());
1360 self
1361 }
1362
1363 fn on_file_drag_enter<M>(self, listener: impl IntoListener<(), M>) -> Self {
1365 self.on(
1366 EventKind::FileDragEnter,
1367 events::typed(listener.into_listener(), events::unit),
1368 )
1369 }
1370
1371 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1373 self.on(
1374 EventKind::FileDragLeave,
1375 events::typed(listener.into_listener(), events::unit),
1376 )
1377 }
1378
1379 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1381 self.on(
1382 EventKind::FileDrop,
1383 events::typed(listener.into_listener(), events::file_drop),
1384 )
1385 }
1386
1387 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1390 self.on(
1391 EventKind::MouseEnter,
1392 events::typed(listener.into_listener(), events::mouse),
1393 )
1394 }
1395
1396 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1399 self.on(
1400 EventKind::MouseLeave,
1401 events::typed(listener.into_listener(), events::mouse),
1402 )
1403 }
1404
1405 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1410 self.on(
1411 EventKind::MouseMove,
1412 events::typed(listener.into_listener(), events::mouse),
1413 )
1414 }
1415
1416 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1421 self.on(
1422 EventKind::ContextMenu,
1423 events::typed(listener.into_listener(), events::context_menu),
1424 )
1425 }
1426
1427 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1431 self.on(
1432 EventKind::Focus,
1433 events::typed(listener.into_listener(), events::unit),
1434 )
1435 }
1436
1437 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1439 self.on(
1440 EventKind::Blur,
1441 events::typed(listener.into_listener(), events::unit),
1442 )
1443 }
1444
1445 fn on_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1451 self.on(
1452 EventKind::Press,
1453 events::typed(listener.into_listener(), events::press),
1454 )
1455 }
1456
1457 fn on_long_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1459 self.on(
1460 EventKind::LongPress,
1461 events::typed(listener.into_listener(), events::press),
1462 )
1463 }
1464
1465 fn on_press_down<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1467 self.on(
1468 EventKind::PressDown,
1469 events::typed(listener.into_listener(), events::press),
1470 )
1471 }
1472
1473 fn on_press_up<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1475 self.on(
1476 EventKind::PressUp,
1477 events::typed(listener.into_listener(), events::press),
1478 )
1479 }
1480
1481 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1483 self.on(
1484 EventKind::Layout,
1485 events::typed(listener.into_listener(), events::layout),
1486 )
1487 }
1488
1489 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1493 self.on(
1494 EventKind::Touch,
1495 events::typed(listener.into_listener(), events::touch),
1496 )
1497 }
1498
1499 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1504 if let Some(pan) = claim.pan {
1505 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1506 }
1507 super::responder::of(self.node()).claims.push(claim);
1508 self
1509 }
1510
1511 fn keep_touches(mut self, keep: bool) -> Self {
1516 super::responder::of(self.node()).keep = keep;
1517 self
1518 }
1519
1520 fn on_responder_grant<M>(
1522 mut self,
1523 listener: impl IntoListener<super::ResponderEvent, M>,
1524 ) -> Self {
1525 super::responder::of(self.node()).grant = Some(listener.into_listener());
1526 self
1527 }
1528
1529 fn on_responder_reject<M>(
1532 mut self,
1533 listener: impl IntoListener<super::ResponderEvent, M>,
1534 ) -> Self {
1535 super::responder::of(self.node()).reject = Some(listener.into_listener());
1536 self
1537 }
1538
1539 fn on_responder_start<M>(
1542 mut self,
1543 listener: impl IntoListener<super::ResponderEvent, M>,
1544 ) -> Self {
1545 super::responder::of(self.node()).start = Some(listener.into_listener());
1546 self
1547 }
1548
1549 fn on_responder_move<M>(
1551 mut self,
1552 listener: impl IntoListener<super::ResponderEvent, M>,
1553 ) -> Self {
1554 super::responder::of(self.node()).moved = Some(listener.into_listener());
1555 self
1556 }
1557
1558 fn on_responder_end<M>(
1560 mut self,
1561 listener: impl IntoListener<super::ResponderEvent, M>,
1562 ) -> Self {
1563 super::responder::of(self.node()).end = Some(listener.into_listener());
1564 self
1565 }
1566
1567 fn on_responder_release<M>(
1570 mut self,
1571 listener: impl IntoListener<super::ResponderEvent, M>,
1572 ) -> Self {
1573 super::responder::of(self.node()).release = Some(listener.into_listener());
1574 self
1575 }
1576
1577 fn on_responder_terminate<M>(
1580 mut self,
1581 listener: impl IntoListener<super::ResponderEvent, M>,
1582 ) -> Self {
1583 super::responder::of(self.node()).terminate = Some(listener.into_listener());
1584 self
1585 }
1586
1587 fn pan_values(
1592 mut self,
1593 x: Option<&super::AnimatedValue>,
1594 y: Option<&super::AnimatedValue>,
1595 ) -> Self {
1596 let x = x.and_then(|v| v.node().live());
1597 let y = y.and_then(|v| v.node().live());
1598 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
1599 super::host::set(self.node(), prop);
1600 let bound = &mut self.node().attrs.bound;
1601 bound.extend(x);
1602 bound.extend(y);
1603 self
1604 }
1605
1606 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
1609 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
1610 self
1611 }
1612
1613 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
1617 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
1618 self
1619 }
1620
1621 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
1626 if let Some(node) = scale.node().live() {
1627 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
1628 self.node().attrs.bound.push(node);
1629 }
1630 self
1631 }
1632
1633 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
1637 if let Some(node) = angle.node().live() {
1638 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
1639 self.node().attrs.bound.push(node);
1640 }
1641 self
1642 }
1643
1644 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1646 self.on(
1647 EventKind::PanStart,
1648 events::typed(listener.into_listener(), events::pan),
1649 )
1650 }
1651
1652 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
1654 self.on(
1655 EventKind::PanEnd,
1656 events::typed(listener.into_listener(), events::pan),
1657 )
1658 }
1659
1660 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1662 self.on(
1663 EventKind::PinchStart,
1664 events::typed(listener.into_listener(), events::pinch),
1665 )
1666 }
1667
1668 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
1670 self.on(
1671 EventKind::PinchEnd,
1672 events::typed(listener.into_listener(), events::pinch),
1673 )
1674 }
1675
1676 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1678 self.on(
1679 EventKind::RotationStart,
1680 events::typed(listener.into_listener(), events::rotation),
1681 )
1682 }
1683
1684 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
1686 self.on(
1687 EventKind::RotationEnd,
1688 events::typed(listener.into_listener(), events::rotation),
1689 )
1690 }
1691
1692 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
1694 self.on(
1695 EventKind::AccessibilityAction,
1696 events::typed(listener.into_listener(), events::action),
1697 )
1698 }
1699
1700 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
1703 self.node().handlers.push((kind, listener.into_listener()));
1704 self
1705 }
1706
1707 fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1709 super::host::bind_prop(self.node(), insets, Prop::HitSlop);
1710 self
1711 }
1712
1713 fn long_press_delay(mut self, ms: f32) -> Self {
1715 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
1716 self
1717 }
1718
1719 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
1721 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
1722 self
1723 }
1724
1725 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
1727 super::host::set(self.node(), Prop::Elevation(elevation.into()));
1728 self
1729 }
1730
1731 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
1733 super::host::set(self.node(), Prop::BackdropMaterial(material));
1734 self
1735 }
1736
1737 fn test_id(mut self, id: &str) -> Self {
1739 super::host::set(self.node(), Prop::TestId(Some(id.into())));
1740 self
1741 }
1742
1743 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
1748 super::host::bind_prop(self.node(), enabled, |enabled| {
1749 Prop::WindowDrag(Some(enabled))
1750 });
1751 self
1752 }
1753
1754 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
1762 super::host::bind_prop(self.node(), focusable, |focusable| {
1763 Prop::Focusable(Some(focusable))
1764 });
1765 self
1766 }
1767
1768 fn native_id(mut self, id: &str) -> Self {
1770 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
1771 self
1772 }
1773
1774 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1776 let s = f(StyleRefinement::default());
1777 self.style().extend_as(Variant::ACTIVE, s);
1778 self
1779 }
1780
1781 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1783 let s = f(StyleRefinement::default());
1784 self.style().extend_as(Variant::HOVER, s);
1785 self
1786 }
1787
1788 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1790 let s = f(StyleRefinement::default());
1791 self.style().extend_as(Variant::FOCUS, s);
1792 self
1793 }
1794
1795 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1800 let s = f(StyleRefinement::default());
1801 self.style().extend_as(Variant::FOCUS_WITHIN, s);
1802 self
1803 }
1804
1805 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
1807 let s = f(StyleRefinement::default());
1808 self.style().extend_as(Variant::DISABLED, s);
1809 self
1810 }
1811
1812 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1814 self.node().bind_attr(disabled, |a, disabled| {
1815 a.disabled = disabled;
1816 a.state.disabled = disabled;
1817 });
1818 self
1819 }
1820
1821 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
1824 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
1825 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
1826 });
1827 self
1828 }
1829
1830 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
1834 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
1835 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
1836 });
1837 self
1838 }
1839
1840 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
1844 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
1845 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
1846 });
1847 self
1848 }
1849
1850 fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
1854 Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
1855 super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
1856 });
1857 self
1858 }
1859
1860 fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
1864 Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
1865 super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
1866 });
1867 self
1868 }
1869
1870 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
1876 self.node().bind_attr(checked, |a, checked| {
1877 project(a, crate::tailwind::state::CHECKED, checked)
1878 });
1879 self
1880 }
1881
1882 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
1888 self.node().bind_attr(indeterminate, |a, indeterminate| {
1889 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
1890 });
1891 self
1892 }
1893
1894 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
1899 self.node().bind_attr(disabled, |a, disabled| {
1900 project(a, crate::tailwind::state::DISABLED, disabled)
1901 });
1902 self
1903 }
1904
1905 fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
1911 self.node().bind_attr(focused, |a, focused| {
1912 project(a, crate::tailwind::state::FOCUSED, focused)
1913 });
1914 self
1915 }
1916
1917 fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
1926 self.node().bind_attr(on, move |a, on| {
1927 let at = a.projected_data.binary_search(&name);
1928 match (at, on) {
1929 (Err(i), true) => a.projected_data.insert(i, name),
1930 (Ok(i), false) => {
1931 a.projected_data.remove(i);
1932 }
1933 _ => {}
1934 }
1935 });
1936 self
1937 }
1938}
1939
1940fn project(a: &mut Attrs, bit: u16, on: bool) {
1942 if on {
1943 a.projected_states |= bit;
1944 } else {
1945 a.projected_states &= !bit;
1946 }
1947}
1948
1949macro_rules! element {
1950 ($(#[$doc:meta])* $name:ident) => {
1951 $(#[$doc])*
1952 #[derive(Clone)]
1953 pub struct $name(ElNode);
1954
1955 impl Element for $name {
1956 fn node(&mut self) -> &mut ElNode {
1957 &mut self.0
1958 }
1959 }
1960
1961 impl IntoElement for $name {
1962 fn into_element(self) -> AnyElement {
1963 AnyElement(self.0)
1964 }
1965 }
1966
1967 impl Accessible for $name {}
1968
1969 impl IntoTooltip for $name {
1970 fn apply_tooltip(self, node: &mut ElNode) {
1971 self.into_element().apply_tooltip(node);
1972 }
1973 }
1974 };
1975}
1976
1977element! {
1978 View
1980}
1981
1982element! {
1983 Text
1985}
1986
1987element! {
1988 Image
1990}
1991
1992element! {
1993 SlotElement
1996}
1997
1998element! {
1999 ListElement
2001}
2002
2003impl Interactive for View {}
2004impl ParentElement for View {}
2005
2006impl View {
2007 pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2021 let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2022 t.and_then(|t| t.target()).map(super::FollowTarget)
2023 });
2024 super::host::bind_prop(&mut self.0, target, Prop::Follow);
2025 self
2026 }
2027
2028 pub fn follow_transition(
2034 mut self,
2035 transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2036 ) -> Self {
2037 super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2038 self
2039 }
2040}
2041impl Interactive for SlotElement {}
2042impl Interactive for Text {}
2043impl Interactive for Image {}
2044
2045impl ParentElement for Text {
2050 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2051 let at = self.0.children.len();
2052 child.__push_into(&mut self.0.children);
2053 for el in &mut self.0.children[at..] {
2054 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2055 }
2056 self
2057 }
2058
2059 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2060 self.0
2061 .children
2062 .extend(children.into_iter().map(|c| span(c.into_element().0)));
2063 self
2064 }
2065}
2066
2067fn span(mut el: ElNode) -> ElNode {
2070 if el.tag == Tag::Text
2071 && matches!(el.kind, ElKind::Plain)
2072 && el.key.is_none()
2073 && el.children.is_empty()
2074 && el.handlers.is_empty()
2075 && el.style.is_empty()
2076 && el.attrs == Attrs::default()
2077 && !el.is_bound()
2078 {
2079 el.kind = ElKind::Raw;
2080 }
2081 el
2082}
2083
2084impl Text {
2085 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2087 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2088 Prop::SelectionColor(Some(Color::from(c)))
2089 });
2090 self
2091 }
2092
2093 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2095 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2096 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2097 self
2098 }
2099
2100 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2103 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2104 self
2105 }
2106
2107 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2110 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2111 self
2112 }
2113}
2114
2115impl Image {
2116 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2119 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2120 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2121 uri: src.uri.to_arc(),
2122 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2123 scales: src.scales,
2124 data: src.data,
2125 })))
2126 });
2127 self
2128 }
2129
2130 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2132 Styled::tint_color(self, color)
2133 }
2134
2135 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2137 super::host::set(
2138 &mut self.0,
2139 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2140 );
2141 self
2142 }
2143
2144 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2146 super::host::bind_prop(&mut self.0, ms, |ms| {
2147 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
2148 });
2149 self
2150 }
2151
2152 pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
2154 self.on(
2155 EventKind::Load,
2156 events::typed(listener.into_listener(), events::pixel_size),
2157 )
2158 }
2159
2160 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
2162 self.on(
2163 EventKind::Error,
2164 events::typed(listener.into_listener(), events::message),
2165 )
2166 }
2167
2168 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
2170 self.on(
2171 EventKind::LoadStart,
2172 events::typed(listener.into_listener(), events::unit),
2173 )
2174 }
2175
2176 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
2178 self.on(
2179 EventKind::LoadEnd,
2180 events::typed(listener.into_listener(), events::unit),
2181 )
2182 }
2183
2184 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
2187 self.on(
2188 EventKind::Progress,
2189 events::typed(listener.into_listener(), events::image_progress),
2190 )
2191 }
2192}
2193
2194impl super::Scrollable for ListElement {}
2195
2196impl super::ListLayout for ListElement {
2197 fn config(&mut self) -> &mut ListConfig {
2198 match &mut self.0.kind {
2199 ElKind::List(list) => &mut list.config,
2200 _ => unreachable!("a ListElement is a list"),
2201 }
2202 }
2203
2204 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
2205 &mut self.0.bound_list
2206 }
2207}
2208
2209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2212pub struct Slot {
2213 name: &'static str,
2214}
2215
2216impl Slot {
2217 pub(crate) fn new(name: &'static str) -> Self {
2218 Self { name }
2219 }
2220
2221 pub fn name(&self) -> &'static str {
2223 self.name
2224 }
2225
2226 pub fn element(self) -> SlotElement {
2228 let mut node = ElNode::new(Tag::View);
2229 node.kind = ElKind::Slot(self.name);
2230 SlotElement(node)
2231 }
2232}
2233
2234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2238pub struct Items {
2239 name: &'static str,
2240}
2241
2242impl Items {
2243 #[doc(hidden)]
2244 pub const fn __new(name: &'static str) -> Self {
2245 Self { name }
2246 }
2247}
2248
2249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2253pub struct Child(ChildRef);
2254
2255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2256enum ChildRef {
2257 Js(NodeId),
2258 Row,
2259}
2260
2261impl Child {
2262 pub(crate) fn js(id: NodeId) -> Self {
2263 Self(ChildRef::Js(id))
2264 }
2265
2266 pub(crate) fn row() -> Self {
2267 Self(ChildRef::Row)
2268 }
2269}
2270
2271impl IntoElement for Child {
2272 fn into_element(self) -> AnyElement {
2273 let mut node = ElNode::new(Tag::View);
2274 node.kind = match self.0 {
2275 ChildRef::Js(id) => ElKind::JsChild(id),
2276 ChildRef::Row => ElKind::Children,
2277 };
2278 AnyElement(node)
2279 }
2280}
2281
2282pub fn view() -> View {
2284 View(ElNode::new(Tag::View))
2285}
2286
2287pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2290 let mut node = ElNode::new(Tag::Text);
2291 match content.into_reactive() {
2292 Reactive::Static(content) => node.text = Some(content),
2293 Reactive::Bound(content) => {
2294 node.text = Some(SharedString::default());
2295 node.bound_text = Some(content);
2296 }
2297 }
2298 Text(node)
2299}
2300
2301pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2305 let mut node = ElNode::new(Tag::Image);
2306 node.bind_attr(src, |a, src| a.src = Some(src));
2307 Image(node)
2308}
2309
2310#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2313pub struct Children {
2314 present: bool,
2315}
2316
2317impl Children {
2318 pub(crate) fn new(present: bool) -> Self {
2319 Self { present }
2320 }
2321
2322 pub fn is_empty(&self) -> bool {
2324 !self.present
2325 }
2326}
2327
2328impl IntoElement for Children {
2329 fn into_element(self) -> AnyElement {
2330 let mut node = ElNode::new(Tag::View);
2331 node.kind = ElKind::Children;
2332 AnyElement(node)
2333 }
2334}
2335
2336pub struct ComponentElement<C: Component> {
2349 node: ElNode,
2350 _component: PhantomData<fn() -> C>,
2351}
2352
2353impl<C: Component> ComponentElement<C> {
2354 #[doc(hidden)]
2357 pub fn __new(props: C::Props) -> Self {
2358 Self::new(props)
2359 }
2360
2361 #[doc(hidden)]
2363 pub fn __props_mut(&mut self) -> &mut C::Props {
2364 match &mut self.node.kind {
2365 ElKind::Component(c) => c
2366 .props
2367 .as_any_mut()
2368 .downcast_mut::<C::Props>()
2369 .expect("a component element holds its component's props"),
2370 _ => unreachable!("a component element is a component's"),
2371 }
2372 }
2373
2374 pub(crate) fn new(props: C::Props) -> Self {
2375 let mut node = ElNode::new(Tag::View);
2376 node.kind = ElKind::Component(ComponentEl {
2377 name: super::component::name_of::<C>(),
2378 make: super::component::make_instance::<C>,
2379 spec: ComponentSpec::of::<C>,
2380 props: Box::new(props),
2381 on_event: Vec::new(),
2382 });
2383 Self {
2384 node,
2385 _component: PhantomData,
2386 }
2387 }
2388
2389 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2394 self.node
2395 .children
2396 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2397 let mut fill = ElNode::new(Tag::View);
2398 fill.kind = ElKind::Fill(slot);
2399 fill.children.push(content.into_element().0);
2400 self.node.children.push(fill);
2401 self
2402 }
2403
2404 pub fn items(mut self, list: super::VirtualList) -> Self {
2412 match <C::Props as super::Props>::ITEMS {
2413 Some(name) => self.node.children.push(list.into_items(name)),
2414 None => {
2415 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2416 }
2417 }
2418 self
2419 }
2420
2421 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2426 let s = f(StyleRefinement::default());
2427 self.node.style.extend_as(Variant::ACTIVE, s);
2428 self
2429 }
2430
2431 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2433 let s = f(StyleRefinement::default());
2434 self.node.style.extend_as(Variant::HOVER, s);
2435 self
2436 }
2437
2438 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2440 let s = f(StyleRefinement::default());
2441 self.node.style.extend_as(Variant::FOCUS, s);
2442 self
2443 }
2444
2445 pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2448 let s = f(StyleRefinement::default());
2449 self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
2450 self
2451 }
2452
2453 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2456 let s = f(StyleRefinement::default());
2457 self.node.style.extend_as(Variant::DISABLED, s);
2458 self
2459 }
2460
2461 pub fn test_id(mut self, id: &str) -> Self {
2464 super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
2465 self
2466 }
2467
2468 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2470 self.node.attrs.element_ref = handle.element().target();
2471 self
2472 }
2473
2474 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
2480 let listener = listener.into_listener();
2481 if let ElKind::Component(c) = &mut self.node.kind {
2482 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
2483 if let Some(event) = event.downcast_ref::<C::Event>() {
2484 inner(event);
2485 }
2486 }));
2487 }
2488 self
2489 }
2490
2491 #[doc(hidden)]
2495 pub fn __on_variant<T: ?Sized + 'static, M>(
2496 self,
2497 pick: fn(&C::Event) -> Option<&T>,
2498 listener: impl IntoListener<T, M>,
2499 ) -> Self {
2500 let listener = listener.into_listener();
2501 self.on_event(listener.wrap(move |inner, event: &C::Event| {
2502 if let Some(data) = pick(event) {
2503 inner(data);
2504 }
2505 }))
2506 }
2507}
2508
2509pub trait ComponentBuilder: Element {
2581 type Component: Component;
2583
2584 #[doc(hidden)]
2586 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
2587
2588 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2593 let s = f(StyleRefinement::default());
2594 self.node().style.extend_as(Variant::ACTIVE, s);
2595 self
2596 }
2597
2598 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2600 let s = f(StyleRefinement::default());
2601 self.node().style.extend_as(Variant::HOVER, s);
2602 self
2603 }
2604
2605 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2607 let s = f(StyleRefinement::default());
2608 self.node().style.extend_as(Variant::FOCUS, s);
2609 self
2610 }
2611
2612 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2615 let s = f(StyleRefinement::default());
2616 self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
2617 self
2618 }
2619
2620 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2623 let s = f(StyleRefinement::default());
2624 self.node().style.extend_as(Variant::DISABLED, s);
2625 self
2626 }
2627
2628 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
2630 self.__element().node.attrs.element_ref = handle.element().target();
2631 self
2632 }
2633}
2634
2635impl<C: Component> Element for ComponentElement<C> {
2636 fn node(&mut self) -> &mut ElNode {
2637 &mut self.node
2638 }
2639}
2640
2641impl<C: Component> ParentElement for ComponentElement<C> {}
2645
2646impl<C: Component> IntoElement for ComponentElement<C> {
2647 fn into_element(self) -> AnyElement {
2648 AnyElement(self.node)
2649 }
2650}