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, KeyCapture, KeyEvent,
15 ListContentStyle, MouseEvent, NativeProp, NodeId, PinchEvent, PointerEvents, Points,
16 PressEvent, Prop, Size, Tag, TouchEvent, WheelEvent,
17 geometry::{DevicePixels, Radians},
18 style::Color,
19};
20
21pub struct Listener<E: ?Sized> {
28 f: Rc<dyn Fn(&E)>,
29 owner: super::Owner,
30}
31
32impl<E: ?Sized + 'static> Listener<E> {
33 pub(crate) fn noop() -> Self {
35 Self::new(Rc::new(|_| {}))
36 }
37
38 fn new(f: Rc<dyn Fn(&E)>) -> Self {
39 Self {
40 f,
41 owner: super::Owner::current_or_detached(),
42 }
43 }
44
45 pub(crate) fn same_owner(&self, other: &Self) -> bool {
47 self.owner == other.owner
48 }
49
50 pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
52 self.same_owner(other) && Rc::ptr_eq(&self.f, &other.f)
53 }
54
55 pub(crate) fn call(&self, event: &E) {
58 if self.owner == super::Owner::detached() {
59 (self.f)(event);
60 } else if self.owner.is_live() {
61 self.owner.scope(|| (self.f)(event));
62 }
63 }
64
65 pub(crate) fn wrap<F: ?Sized>(self, f: impl Fn(&dyn Fn(&E), &F) + 'static) -> Listener<F> {
68 let inner = self.f;
69 Listener {
70 f: Rc::new(move |event: &F| f(&*inner, event)),
71 owner: self.owner,
72 }
73 }
74}
75
76impl<E: 'static> Listener<E> {
77 pub fn map<F: ?Sized + 'static>(self, f: impl Fn(&F) -> E + 'static) -> Listener<F> {
79 self.wrap(move |inner, event: &F| inner(&f(event)))
80 }
81}
82
83impl<E: ?Sized + 'static, F: Fn(&E) + 'static> From<F> for Listener<E> {
85 fn from(f: F) -> Self {
86 Self::new(Rc::new(f))
87 }
88}
89
90#[diagnostic::on_unimplemented(
98 message = "`{Self}` is not a listener of `{E}`",
99 label = "not a listener of `{E}`",
100 note = "a listener is a closure `move |event: &{E}| ..` (`move || ..` for an event without data) or a `Listener<{E}>`"
101)]
102pub trait IntoListener<E: ?Sized, M> {
103 fn into_listener(self) -> Listener<E>;
105}
106
107#[doc(hidden)]
109pub struct OfEvent(());
110
111#[doc(hidden)]
114pub struct WithoutEvent(());
115
116impl<E: ?Sized> IntoListener<E, ()> for Listener<E> {
117 fn into_listener(self) -> Listener<E> {
118 self
119 }
120}
121
122impl<E: ?Sized + 'static, F: Fn(&E) + 'static> IntoListener<E, OfEvent> for F {
123 fn into_listener(self) -> Listener<E> {
124 Listener::new(Rc::new(self))
125 }
126}
127
128impl<F: Fn() + 'static> IntoListener<(), WithoutEvent> for F {
129 fn into_listener(self) -> Listener<()> {
130 Listener::new(Rc::new(move |_: &()| self()))
131 }
132}
133
134#[doc(hidden)]
137pub struct OfUnit(());
138
139impl<F: Fn() + 'static> IntoListener<PressEvent, WithoutEvent> for F {
141 fn into_listener(self) -> Listener<PressEvent> {
142 Listener::new(Rc::new(move |_: &PressEvent| self()))
143 }
144}
145
146impl<F: Fn(&()) + 'static> IntoListener<PressEvent, OfUnit> for F {
148 fn into_listener(self) -> Listener<PressEvent> {
149 Listener::new(Rc::new(move |_: &PressEvent| self(&())))
150 }
151}
152
153impl IntoListener<PressEvent, ()> for Listener<()> {
155 fn into_listener(self) -> Listener<PressEvent> {
156 self.map(|_: &PressEvent| ())
157 }
158}
159
160impl<F: Fn() + 'static> IntoListener<events::FileDragEvent, WithoutEvent> for F {
162 fn into_listener(self) -> Listener<events::FileDragEvent> {
163 Listener::new(Rc::new(move |_: &events::FileDragEvent| self()))
164 }
165}
166
167impl<F: Fn(&()) + 'static> IntoListener<events::FileDragEvent, OfUnit> for F {
169 fn into_listener(self) -> Listener<events::FileDragEvent> {
170 Listener::new(Rc::new(move |_: &events::FileDragEvent| self(&())))
171 }
172}
173
174impl IntoListener<events::FileDragEvent, ()> for Listener<()> {
176 fn into_listener(self) -> Listener<events::FileDragEvent> {
177 self.map(|_: &events::FileDragEvent| ())
178 }
179}
180
181impl<E: ?Sized> Clone for Listener<E> {
182 fn clone(&self) -> Self {
183 Self {
184 f: self.f.clone(),
185 owner: self.owner,
186 }
187 }
188}
189
190pub(crate) trait AnyEvent: super::EventToJs {
193 fn as_any(&self) -> &dyn Any;
194}
195
196impl<E: Event> super::EventToJs for E {
197 fn name(&self) -> &'static str {
198 Event::name(self)
199 }
200
201 fn data_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
202 Event::data_js(self, host)
203 }
204}
205
206impl<E: Event> AnyEvent for E {
207 fn as_any(&self) -> &dyn Any {
208 self
209 }
210}
211
212#[derive(Debug, Clone, Default, PartialEq)]
215pub(crate) struct RareAttrs {
216 pub(crate) accessible: Option<bool>,
217 pub(crate) hint: Option<SharedString>,
218 pub(crate) description: Option<SharedString>,
219 pub(crate) value: Option<AccessibilityValue>,
220 pub(crate) src: Option<super::ImageSrc>,
221 pub(crate) inset_padding: Option<EdgeInsets>,
222 pub(crate) inset_margin: Option<EdgeInsets>,
223 pub(crate) drawing: Option<Arc<crate::canvas::Drawing>>,
225 pub(crate) element_ref: Option<super::element_ref::RefTarget>,
228 pub(crate) animated: Vec<(crate::StyleDecl, super::LiveNode)>,
231 pub(crate) bound: Vec<super::LiveNode>,
233 pub(crate) selectable_view: bool,
235 pub(crate) continues_text: bool,
237 pub(crate) projected_states: u16,
240 pub(crate) projected_data: Vec<&'static str>,
243 pub(crate) projected_active: Option<&'static str>,
246 pub(crate) render: Option<super::renderer::RenderAt>,
249 pub(crate) window: Option<Box<crate::desktop::WindowOptions>>,
252}
253
254impl RareAttrs {
255 pub(crate) fn is_empty(&self) -> bool {
256 self.accessible.is_none()
257 && self.hint.is_none()
258 && self.description.is_none()
259 && self.value.is_none()
260 && self.src.is_none()
261 && self.inset_padding.is_none()
262 && self.inset_margin.is_none()
263 && self.drawing.is_none()
264 && self.element_ref.is_none()
265 && self.animated.is_empty()
266 && self.bound.is_empty()
267 && !self.selectable_view
268 && !self.continues_text
269 && self.projected_states == 0
270 && self.projected_data.is_empty()
271 && self.projected_active.is_none()
272 && self.render.is_none()
273 && self.window.is_none()
274 }
275
276 pub(crate) fn boxed(self) -> Option<Box<Self>> {
277 (!self.is_empty()).then(|| Box::new(self))
278 }
279}
280
281#[doc(hidden)]
283#[derive(Debug, Clone, Default)]
284pub struct Attrs {
285 pub(crate) disabled: bool,
286 pub(crate) role: AccessibilityRole,
287 pub(crate) state: AccessibilityState,
288 pub(crate) pointer_events: PointerEvents,
290 pub(crate) label: Option<SharedString>,
291 pub(crate) inline: Option<std::rc::Rc<crate::StylePatch>>,
293 pub(crate) class: Option<SharedString>,
296 pub(crate) props: Vec<Prop>,
299 pub(crate) rare: Option<Box<RareAttrs>>,
300}
301
302impl PartialEq for Attrs {
303 fn eq(&self, other: &Self) -> bool {
304 self.disabled == other.disabled
305 && self.role == other.role
306 && self.state == other.state
307 && self.pointer_events == other.pointer_events
308 && self.label == other.label
309 && self.inline == other.inline
310 && self.class == other.class
311 && self.props == other.props
312 && match (&self.rare, &other.rare) {
313 (None, None) => true,
314 (Some(a), None) => a.is_empty(),
315 (None, Some(b)) => b.is_empty(),
316 (Some(a), Some(b)) => a == b,
317 }
318 }
319}
320
321impl Attrs {
322 #[inline]
323 pub(crate) fn rare_mut(&mut self) -> &mut RareAttrs {
324 self.rare.get_or_insert_with(Box::default)
325 }
326
327 #[inline]
328 pub(crate) fn animated(&self) -> &[(crate::StyleDecl, super::LiveNode)] {
329 self.rare.as_deref().map_or(&[], |r| r.animated.as_slice())
330 }
331
332 #[cfg(test)]
333 #[inline]
334 pub(crate) fn bound(&self) -> &[super::LiveNode] {
335 self.rare.as_deref().map_or(&[], |r| r.bound.as_slice())
336 }
337
338 #[inline]
339 pub(crate) fn element_ref(&self) -> Option<&super::element_ref::RefTarget> {
340 self.rare.as_ref().and_then(|r| r.element_ref.as_ref())
341 }
342
343 #[inline]
344 pub(crate) fn set_element_ref(&mut self, target: Option<super::element_ref::RefTarget>) {
345 if target.is_some() || self.rare.is_some() {
346 self.rare_mut().element_ref = target;
347 }
348 }
349
350 #[inline]
351 pub(crate) fn take_element_ref(&mut self) -> Option<super::element_ref::RefTarget> {
352 self.rare.as_mut().and_then(|r| r.element_ref.take())
353 }
354
355 #[inline]
356 pub(crate) fn insets(&self) -> (Option<EdgeInsets>, Option<EdgeInsets>) {
357 match &self.rare {
358 Some(r) => (r.inset_padding, r.inset_margin),
359 None => (None, None),
360 }
361 }
362
363 #[inline]
364 pub(crate) fn set_insets(&mut self, insets: (Option<EdgeInsets>, Option<EdgeInsets>)) {
365 if insets != (None, None) || self.rare.is_some() {
366 let r = self.rare_mut();
367 r.inset_padding = insets.0;
368 r.inset_margin = insets.1;
369 }
370 }
371
372 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
374 use AccessibilityProp as A;
375 if self.disabled != old.disabled {
376 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
377 }
378 let check_rare = self.rare.is_some() || old.rare.is_some();
379 let default_rare;
380 let (sr, or) = if check_rare {
381 default_rare = RareAttrs::default();
382 (
383 self.rare.as_deref().unwrap_or(&default_rare),
384 old.rare.as_deref().unwrap_or(&default_rare),
385 )
386 } else {
387 default_rare = RareAttrs::default();
388 (&default_rare, &default_rare)
389 };
390 if check_rare && sr.accessible != or.accessible {
391 out.push(Prop::Accessibility(A::Accessible(sr.accessible)));
392 }
393 if self.label != old.label {
394 out.push(Prop::Accessibility(A::Label(
395 self.label.as_ref().map(SharedString::to_arc),
396 )));
397 }
398 if check_rare && sr.hint != or.hint {
399 out.push(Prop::Accessibility(A::Hint(
400 sr.hint.as_ref().map(SharedString::to_arc),
401 )));
402 }
403 if check_rare && sr.description != or.description {
404 out.push(Prop::Accessibility(A::Description(
405 sr.description.as_ref().map(SharedString::to_arc),
406 )));
407 }
408 if self.role != old.role {
409 out.push(Prop::Accessibility(A::Role(self.role)));
410 }
411 if self.state != old.state {
412 out.push(Prop::Accessibility(A::State(self.state)));
413 }
414 if check_rare && sr.value != or.value {
415 out.push(Prop::Accessibility(A::Value(sr.value.clone())));
416 }
417 if self.pointer_events != old.pointer_events {
418 out.push(Prop::PointerEvents(self.pointer_events));
419 }
420 if check_rare {
421 if sr.src != or.src {
422 out.push(Prop::Source(sr.src.as_ref().map(|src| ImageSource {
423 uri: src.uri.to_arc(),
424 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
425 scales: src.scales,
426 data: src.data.clone(),
427 })));
428 }
429 if sr.inset_padding != or.inset_padding {
430 out.push(Prop::InsetPadding(sr.inset_padding.unwrap_or_default()));
431 }
432 if sr.inset_margin != or.inset_margin {
433 out.push(Prop::InsetMargin(sr.inset_margin.unwrap_or_default()));
434 }
435 if sr.selectable_view != or.selectable_view {
436 out.push(Prop::SelectableView(sr.selectable_view));
437 }
438 if sr.continues_text != or.continues_text {
439 out.push(Prop::ContinuesText(sr.continues_text));
440 }
441 if sr.projected_states != or.projected_states {
442 out.push(Prop::ProjectedStates(sr.projected_states));
443 }
444 if sr.projected_data != or.projected_data {
445 out.push(Prop::ProjectedData(sr.projected_data.as_slice().into()));
446 }
447 if sr.projected_active != or.projected_active {
448 out.push(Prop::ProjectedActive(sr.projected_active));
449 }
450 }
451 for prop in &old.props {
454 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
455 && let Some(reset) = super::host::reset(prop)
456 {
457 out.push(reset);
458 }
459 }
460 for prop in &self.props {
461 if !old.props.contains(prop) {
462 out.push(prop.clone());
463 }
464 }
465 }
466}
467
468pub(crate) trait AnyProps {
470 fn as_any(&self) -> &dyn Any;
471 fn as_any_mut(&mut self) -> &mut dyn Any;
472 fn clone_box(&self) -> Box<dyn AnyProps>;
473}
474
475impl<P: Clone + 'static> AnyProps for P {
476 fn as_any(&self) -> &dyn Any {
477 self
478 }
479
480 fn as_any_mut(&mut self) -> &mut dyn Any {
481 self
482 }
483
484 fn clone_box(&self) -> Box<dyn AnyProps> {
485 Box::new(self.clone())
486 }
487}
488
489pub(crate) struct ComponentEl {
491 pub(crate) name: &'static str,
492 pub(crate) make: fn() -> Box<dyn AnyInstance>,
495 pub(crate) spec: fn() -> ComponentSpec,
497 pub(crate) props: Box<dyn AnyProps>,
498 pub(crate) on_event: Vec<Listener<dyn Any>>,
500}
501
502impl Clone for ComponentEl {
503 fn clone(&self) -> Self {
504 Self {
505 name: self.name,
506 make: self.make,
507 spec: self.spec,
508 props: self.props.clone_box(),
509 on_event: self.on_event.clone(),
510 }
511 }
512}
513
514pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
516
517#[derive(Clone, Copy)]
523pub struct Position {
524 index: super::reactive::Node,
525 count: super::reactive::Node,
526 rows: Option<super::reactive::Node>,
531}
532
533impl Position {
534 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
537 Self {
538 index,
539 count,
540 rows: None,
541 }
542 }
543
544 pub(crate) fn of_row(
547 index: super::reactive::Node,
548 count: super::reactive::Node,
549 rows: Option<super::reactive::Node>,
550 ) -> Self {
551 Self { index, count, rows }
552 }
553
554 pub(crate) fn fixed(index: usize, count: usize) -> Self {
556 Self::of(super::signal(index).node(), super::signal(count).node())
557 }
558
559 #[track_caller]
561 pub fn index(&self) -> usize {
562 if let Some(rows) = self.rows
563 && rows.is_outdated()
564 {
565 let before = self.index.with_untracked("a position", |i: &usize| *i);
566 rows.bring_up_to_date();
567 if !self.index.is_live() {
571 return before;
572 }
573 }
574 self.index.with("a position", |i: &usize| *i)
575 }
576
577 #[track_caller]
579 pub fn count(&self) -> usize {
580 if let Some(rows) = self.rows {
581 rows.bring_up_to_date();
582 }
583 self.count.with("a position", |n: &usize| *n)
584 }
585
586 #[track_caller]
588 pub fn is_first(&self) -> bool {
589 self.index() == 0
590 }
591
592 #[track_caller]
594 pub fn is_last(&self) -> bool {
595 self.index() + 1 == self.count()
596 }
597}
598
599impl fmt::Debug for Position {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 let (index, count) = super::untracked(|| (self.index(), self.count()));
602 write!(f, "Position({index} of {count})")
603 }
604}
605
606#[doc(hidden)]
609#[derive(Debug, Clone, Copy, Default, PartialEq)]
610pub struct ListConfig {
611 pub(crate) estimated: Option<f32>,
612 pub(crate) columns: Option<u32>,
613 pub(crate) horizontal: Option<bool>,
614 pub(crate) inverted: Option<bool>,
615 pub(crate) scrollbar_visible: Option<bool>,
616 pub(crate) content: Option<ListContentStyle>,
617 pub(crate) follow_end: Option<f32>,
618 pub(crate) alignment: Option<crate::ListAlignment>,
619 pub(crate) viewport: Option<crate::ListViewport>,
620}
621
622impl ListConfig {
623 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
625 if self.estimated != old.estimated {
626 out.push(Prop::EstimatedItemSize(Points(
627 self.estimated.unwrap_or(50.0),
628 )));
629 }
630 if self.columns != old.columns {
631 out.push(Prop::Columns(self.columns.unwrap_or(1)));
632 }
633 if self.horizontal != old.horizontal {
634 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
635 }
636 if self.inverted != old.inverted {
637 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
638 }
639 if self.scrollbar_visible != old.scrollbar_visible {
640 out.push(Prop::Scrollbar(
641 self.scrollbar_visible.unwrap_or(true).into(),
642 ));
643 }
644 if self.content != old.content {
645 out.push(Prop::ListContent(self.content.unwrap_or_default()));
646 }
647 if self.follow_end != old.follow_end {
648 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
649 }
650 if self.alignment != old.alignment {
651 out.push(Prop::ListAlignment(self.alignment.unwrap_or_default()));
652 }
653 if self.viewport != old.viewport {
654 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
655 }
656 }
657}
658
659#[derive(Clone)]
661pub(crate) struct ListEl {
662 pub(crate) name: &'static str,
663 pub(crate) config: ListConfig,
664 pub(crate) row: PlaceFn,
665}
666
667#[derive(Clone)]
669pub(crate) enum ElKind {
670 Plain,
671 Slot(&'static str),
673 Fill(&'static str),
676 Filled(&'static str),
679 Children,
681 JsChild(NodeId),
683 EachChild(PlaceFn),
685 List(Box<ListEl>),
687 VirtualList(Box<super::virtual_list::VirtualListEl>),
689 Raw,
692 Component(ComponentEl),
693 Region(super::flow::Region),
697}
698
699#[doc(hidden)]
701#[derive(Clone)]
702pub struct ElNode {
703 pub(crate) tag: Tag,
704 pub(crate) key: Option<SharedString>,
705 pub(crate) text: Option<SharedString>,
707 pub(crate) attrs: Attrs,
708 pub(crate) style: StyleRefinement,
709 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
710 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
712 pub(crate) children: Vec<ElNode>,
713 pub(crate) kind: ElKind,
714 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
716 pub(crate) bound_attrs: Vec<BoundAttrs>,
718 pub(crate) bound_list: Vec<BoundListConfig>,
720}
721
722#[doc(hidden)]
724pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
725
726crate::static_reactive!(AccessibilityState: AccessibilityState);
727crate::static_reactive!(EdgeInsets: EdgeInsets);
728crate::static_reactive!(Style: Style);
729crate::static_reactive!(PointerEvents: PointerEvents);
730crate::static_reactive!(KeyCapture: KeyCapture);
731
732pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
734
735impl ElNode {
736 pub(crate) fn bind_attr<T: 'static>(
739 &mut self,
740 value: impl IntoReactive<T>,
741 apply: impl Fn(&mut Attrs, T) + 'static,
742 ) {
743 match value.into_reactive() {
744 Reactive::Static(v) => apply(&mut self.attrs, v),
745 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
746 }
747 }
748
749 pub(crate) fn is_bound(&self) -> bool {
751 self.bound_text.is_some()
752 || !self.bound_attrs.is_empty()
753 || self.style.is_bound()
754 || !self.bound_list.is_empty()
755 }
756
757 pub(crate) fn resolved_attrs(&self) -> Attrs {
760 let mut attrs = self.attrs.clone();
761 for part in &self.bound_attrs {
762 part(&mut attrs);
763 }
764 attrs
765 }
766
767 pub(crate) fn resolve_once(&mut self) {
770 if !self.is_bound() {
771 return;
772 }
773 super::untracked(|| {
774 if let Some(text) = self.bound_text.take() {
775 self.text = Some(text());
776 }
777 if !self.bound_attrs.is_empty() {
778 self.attrs = self.resolved_attrs();
779 self.bound_attrs.clear();
780 }
781 if self.style.is_bound() {
782 self.style = self.style.resolved();
783 }
784 let parts = std::mem::take(&mut self.bound_list);
785 if let Some(config) = self.list_config() {
786 for part in &parts {
787 part(config);
788 }
789 }
790 });
791 }
792
793 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
795 match &mut self.kind {
796 ElKind::List(list) => Some(&mut list.config),
797 ElKind::VirtualList(list) => Some(&mut list.config),
798 _ => None,
799 }
800 }
801
802 pub(crate) fn empty_view() -> Self {
804 Self::new(Tag::View)
805 }
806
807 pub(crate) fn new(tag: Tag) -> Self {
808 Self {
809 tag,
810 key: None,
811 text: None,
812 attrs: Attrs::default(),
813 style: StyleRefinement::default(),
814 handlers: Vec::new(),
815 responder: None,
816 children: Vec::new(),
817 kind: ElKind::Plain,
818 bound_text: None,
819 bound_attrs: Vec::new(),
820 bound_list: Vec::new(),
821 }
822 }
823}
824
825pub struct AnyElement(pub(crate) ElNode);
827
828pub trait IntoElement {
830 fn into_element(self) -> AnyElement;
832}
833
834impl IntoElement for AnyElement {
835 fn into_element(self) -> AnyElement {
836 self
837 }
838}
839
840impl IntoElement for SharedString {
841 fn into_element(self) -> AnyElement {
842 text(self).into_element()
843 }
844}
845
846impl IntoElement for &'static str {
847 fn into_element(self) -> AnyElement {
848 text(self).into_element()
849 }
850}
851
852impl IntoElement for String {
853 fn into_element(self) -> AnyElement {
854 text(self).into_element()
855 }
856}
857
858#[diagnostic::on_unimplemented(
864 message = "`{Self}` is not an element",
865 label = "not an element",
866 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
867)]
868pub trait IntoChild<M> {
869 #[doc(hidden)]
871 fn __push_into(self, out: &mut Vec<ElNode>);
872}
873
874#[doc(hidden)]
876pub struct OneChild(());
877
878#[doc(hidden)]
880pub struct ManyChildren(());
881
882impl<T: IntoElement> IntoChild<OneChild> for T {
883 fn __push_into(self, out: &mut Vec<ElNode>) {
884 out.push(self.into_element().0);
885 }
886}
887
888impl<I: IntoIterator> IntoChild<ManyChildren> for I
889where
890 I::Item: IntoElement,
891{
892 fn __push_into(self, out: &mut Vec<ElNode>) {
893 out.extend(self.into_iter().map(|c| c.into_element().0));
894 }
895}
896
897pub trait FluentBuilder: Sized {
901 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
903 if condition { then(self) } else { self }
904 }
905
906 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
908 match option {
909 Some(v) => then(self, v),
910 None => self,
911 }
912 }
913
914 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
916 f(self)
917 }
918}
919
920impl<T: Element> FluentBuilder for T {}
921
922pub trait Element: IntoElement + Sized {
926 #[doc(hidden)]
927 fn node(&mut self) -> &mut ElNode;
928
929 fn key(mut self, key: impl Into<SharedString>) -> Self {
932 self.node().key = Some(key.into());
933 self
934 }
935
936 fn bind_opacity(self, value: &impl super::Animated) -> Self {
938 self.bind(crate::animation::AnimationProp::Opacity, value)
939 }
940
941 fn bind_background(self, value: &impl super::Animated) -> Self {
944 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
945 }
946
947 fn bind_border_color(self, value: &impl super::Animated) -> Self {
949 self.bind(crate::animation::AnimationProp::BorderColor, value)
950 }
951
952 fn bind_color(self, value: &impl super::Animated) -> Self {
954 self.bind(crate::animation::AnimationProp::Color, value)
955 }
956
957 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
960 if let Some(node) = value.animated_node().live() {
961 let decl = crate::StyleDecl::Animated(prop, node.id());
962 self.node().attrs.rare_mut().animated.push((decl, node));
963 }
964 self
965 }
966
967 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
972 self.bind(crate::animation::AnimationProp::StickyTop, value)
973 }
974
975 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
977 self.bind(crate::animation::AnimationProp::StickyLeft, value)
978 }
979
980 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
983 if let Some(node) = value.animated_node().live() {
984 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
985 self.node().attrs.rare_mut().animated.push((decl, node));
986 }
987 self
988 }
989
990 fn bind_motion(self, motion: &super::Motion) -> Self {
994 use crate::animation::MotionChannel::*;
995 let mut this = self.bind_opacity(&motion.value(Opacity));
996 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
997 if let Some(kind) = channel.transform() {
998 this = this.bind_transform(kind, &motion.value(channel));
999 }
1000 }
1001 let scale = motion.value(Scale);
1002 this.bind_transform(
1003 crate::TransformKind::ScaleX,
1004 &scale.mul(&motion.value(ScaleX)),
1005 )
1006 .bind_transform(
1007 crate::TransformKind::ScaleY,
1008 &scale.mul(&motion.value(ScaleY)),
1009 )
1010 }
1011
1012 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
1014 self.bind_transform(crate::TransformKind::TranslateX, value)
1015 }
1016
1017 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
1019 self.bind_transform(crate::TransformKind::TranslateY, value)
1020 }
1021
1022 fn bind_scale(self, value: &impl super::Animated) -> Self {
1024 self.bind_transform(crate::TransformKind::Scale, value)
1025 }
1026
1027 fn bind_rotate(self, value: &impl super::Animated) -> Self {
1029 self.bind_transform(crate::TransformKind::Rotate, value)
1030 }
1031
1032 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
1035 self.node().attrs.set_element_ref(handle.target());
1036 self
1037 }
1038
1039 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1042 self.node().bind_attr(insets, |a, insets| {
1043 a.rare_mut().inset_padding = Some(insets)
1044 });
1045 self
1046 }
1047
1048 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1050 self.node()
1051 .bind_attr(insets, |a, insets| a.rare_mut().inset_margin = Some(insets));
1052 self
1053 }
1054
1055 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
1058 Style::apply(self.node(), style, Variant::default(), |a, patch| {
1059 a.inline = patch
1060 });
1061 self
1062 }
1063
1064 fn state_inline_style(mut self, style: impl Fn() -> Style + 'static) -> Self {
1069 Style::apply_bound(
1070 self.node(),
1071 Rc::new(style),
1072 Variant::default(),
1073 true,
1074 |a, patch| a.inline = patch,
1075 );
1076 self
1077 }
1078
1079 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
1084 self.node().bind_attr(area, |a, area| {
1085 if area || a.rare.is_some() {
1086 a.rare_mut().selectable_view = area;
1087 }
1088 });
1089 self
1090 }
1091
1092 fn selection_menu(mut self, items: impl IntoReactive<Vec<super::desktop::MenuItem>>) -> Self {
1113 super::host::bind_prop(self.node(), items, |items| {
1114 Prop::SelectionMenu(super::desktop::register_selection_menu(items))
1115 });
1116 self
1117 }
1118
1119 fn continues_text(mut self, continues: impl IntoReactive<bool>) -> Self {
1127 self.node().bind_attr(continues, |a, continues| {
1128 if continues || a.rare.is_some() {
1129 a.rare_mut().continues_text = continues;
1130 }
1131 });
1132 self
1133 }
1134
1135 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
1140 self.node().bind_attr(class, |a, class| a.class = class);
1141 self
1142 }
1143}
1144
1145#[derive(Debug, Clone, Default, PartialEq)]
1159pub struct Style(
1160 pub(crate) Option<std::rc::Rc<crate::StylePatch>>,
1161 pub(crate) StyleRefinement,
1164);
1165
1166impl Style {
1167 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
1171 let mut style = crate::Style::default();
1172 let mut patch = crate::StylePatch::default();
1173 for decl in decls {
1174 let key = match &decl {
1175 crate::StyleDecl::Set(key, _) => Some(*key),
1176 _ => None,
1177 };
1178 if patch.push(&mut style, decl).is_err()
1179 && let Some(key) = key
1180 {
1181 log::warn!("invalid value for style `{}`", key.name());
1182 }
1183 }
1184 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1185 }
1186
1187 pub fn with(self, key: crate::StyleKey, value: crate::PropertyValue) -> Self {
1190 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
1191 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
1192 style.1 = self.1;
1193 style
1194 }
1195
1196 pub fn then(&self, over: &Style) -> Self {
1200 if over.0.is_none() && over.1.is_empty() {
1201 return self.clone();
1202 }
1203 if self.0.is_none() && self.1.is_empty() {
1204 return over.clone();
1205 }
1206 let mut style = if self.0.is_none() {
1207 Self(over.0.clone(), StyleRefinement::default())
1208 } else if over.0.is_none() {
1209 Self(self.0.clone(), StyleRefinement::default())
1210 } else {
1211 Self::from_decls(self.decls().iter().chain(over.decls()).cloned())
1212 };
1213 let mut typed = self.1.clone();
1214 typed.extend_as(Variant::default(), over.1.clone());
1215 style.1 = typed;
1216 style
1217 }
1218
1219 pub fn background_color(&self) -> Option<crate::element::AdaptiveColor> {
1225 let typed = self.1.static_color(crate::StyleKey::BackgroundColor);
1226 let declared = || {
1227 self.decls().iter().rev().find_map(|decl| match decl {
1228 crate::StyleDecl::Set(
1229 crate::StyleKey::BackgroundColor,
1230 crate::PropertyValue::Color(color),
1231 ) => Some(color.map(crate::element::AdaptiveColor::from)),
1232 _ => None,
1233 })?
1234 };
1235 typed
1236 .or_else(declared)
1237 .filter(|c| *c != crate::element::AdaptiveColor::from(crate::Color::TRANSPARENT))
1238 }
1239
1240 pub fn decls(&self) -> &[crate::StyleDecl] {
1242 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
1243 }
1244
1245 pub(crate) fn apply(
1251 node: &mut ElNode,
1252 style: impl IntoReactive<Style>,
1253 variant: Variant,
1254 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1255 ) {
1256 match style.into_reactive() {
1257 Reactive::Static(Style(patch, typed)) => {
1258 attr(&mut node.attrs, patch);
1259 if !typed.is_empty() {
1260 node.style.extend_as(variant, typed);
1261 }
1262 }
1263 Reactive::Bound(f) => Self::apply_bound(node, f, variant, false, attr),
1264 }
1265 }
1266
1267 pub(crate) fn apply_bound(
1270 node: &mut ElNode,
1271 f: Rc<dyn Fn() -> Style>,
1272 variant: Variant,
1273 typed_later: bool,
1274 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1275 ) {
1276 let typed = typed_later || super::untracked(|| !f().1.is_empty());
1277 let patch = f.clone();
1278 node.bind_attr(move || patch().0, attr);
1279 if typed {
1280 node.style
1283 .bind(move |s| s.extend_as(variant, f().1.resolved()));
1284 }
1285 }
1286}
1287
1288impl From<crate::StylePatch> for Style {
1289 fn from(patch: crate::StylePatch) -> Self {
1290 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1291 }
1292}
1293
1294impl From<StyleRefinement> for Style {
1295 fn from(style: StyleRefinement) -> Self {
1296 Self(None, style)
1297 }
1298}
1299
1300impl JsValue for Style {
1301 fn ts_type(_types: &mut super::TsTypes) -> String {
1302 "StyleProp<ViewStyle>".into()
1303 }
1304
1305 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1308 if value.is_nullish() {
1309 return Ok(Self::default());
1310 }
1311 Ok(Self::from(value.host().style(value.raw())?))
1312 }
1313
1314 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1316 Err(PropError("a style does not convert back to JS".to_owned()))
1317 }
1318}
1319
1320#[derive(Debug, Clone, Default, PartialEq)]
1328#[non_exhaustive]
1329pub struct TextPartStyle(pub Style);
1330
1331impl From<Style> for TextPartStyle {
1332 fn from(style: Style) -> Self {
1333 Self(style)
1334 }
1335}
1336
1337impl From<StyleRefinement> for TextPartStyle {
1338 fn from(style: StyleRefinement) -> Self {
1339 Self(Style::from(style))
1340 }
1341}
1342
1343impl From<TextPartStyle> for Style {
1344 fn from(style: TextPartStyle) -> Self {
1345 style.0
1346 }
1347}
1348
1349impl JsValue for TextPartStyle {
1350 fn ts_type(_types: &mut super::TsTypes) -> String {
1351 "StyleProp<TextStyle>".into()
1352 }
1353
1354 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1355 Style::from_js(value).map(Self)
1356 }
1357
1358 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1359 self.0.to_js(host)
1360 }
1361}
1362
1363#[derive(Debug, Clone, Default, PartialEq)]
1369#[non_exhaustive]
1370pub struct InputPartStyle(pub Style);
1371
1372impl From<Style> for InputPartStyle {
1373 fn from(style: Style) -> Self {
1374 Self(style)
1375 }
1376}
1377
1378impl From<StyleRefinement> for InputPartStyle {
1379 fn from(style: StyleRefinement) -> Self {
1380 Self(Style::from(style))
1381 }
1382}
1383
1384impl From<InputPartStyle> for Style {
1385 fn from(style: InputPartStyle) -> Self {
1386 style.0
1387 }
1388}
1389
1390impl JsValue for InputPartStyle {
1391 fn ts_type(_types: &mut super::TsTypes) -> String {
1392 "StyleProp<InputStyle>".into()
1393 }
1394
1395 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1396 Style::from_js(value).map(Self)
1397 }
1398
1399 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1400 self.0.to_js(host)
1401 }
1402}
1403
1404impl<T: Element> Styled for T {
1405 fn style(&mut self) -> &mut StyleRefinement {
1406 &mut self.node().style
1407 }
1408}
1409
1410pub trait ParentElement: Element {
1412 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1415 child.__push_into(&mut self.node().children);
1416 self
1417 }
1418
1419 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1421 self.node()
1422 .children
1423 .extend(children.into_iter().map(|c| c.into_element().0));
1424 self
1425 }
1426
1427 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1430 if let Some(slot) = slot {
1431 let mut node = ElNode::new(Tag::View);
1432 node.kind = ElKind::Slot(slot.name);
1433 self.node().children.push(place(SlotElement(node)).0);
1434 }
1435 self
1436 }
1437
1438 fn children_each<R: IntoElement>(
1441 mut self,
1442 children: impl Into<Children>,
1443 place: impl Fn(Child, Position) -> R + 'static,
1444 ) -> Self {
1445 let _ = children.into();
1446 let mut node = ElNode::new(Tag::View);
1447 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1448 self.node().children.push(node);
1449 self
1450 }
1451
1452 fn list<R: IntoElement>(
1458 mut self,
1459 items: Items,
1460 config: impl FnOnce(ListElement) -> ListElement,
1461 row: impl Fn(Child, Position) -> R + 'static,
1462 ) -> Self {
1463 let mut node = ElNode::new(Tag::List);
1464 node.kind = ElKind::List(Box::new(ListEl {
1465 name: items.name,
1466 config: ListConfig::default(),
1467 row: Rc::new(move |content, at| row(content, at).into_element()),
1468 }));
1469 self.node().children.push(config(ListElement(node)).0);
1470 self
1471 }
1472}
1473
1474pub trait Accessible: Element {
1476 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1478 self.node().bind_attr(accessible, |a, accessible| {
1479 a.rare_mut().accessible = Some(accessible)
1480 });
1481 self
1482 }
1483
1484 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1486 self.node()
1487 .bind_attr(label, |a, label| a.label = Some(label));
1488 self
1489 }
1490
1491 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1494 self.node().bind_attr(label, |a, label| a.label = label);
1495 self
1496 }
1497
1498 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1500 self.node()
1501 .bind_attr(hint, |a, hint| a.rare_mut().hint = Some(hint));
1502 self
1503 }
1504
1505 fn accessibility_description(mut self, description: impl IntoReactive<SharedString>) -> Self {
1509 self.node().bind_attr(description, |a, description| {
1510 a.rare_mut().description = Some(description)
1511 });
1512 self
1513 }
1514
1515 fn optional_accessibility_description(
1519 mut self,
1520 description: impl IntoReactive<Option<SharedString>>,
1521 ) -> Self {
1522 self.node().bind_attr(description, |a, description| {
1523 if description.is_some() || a.rare.is_some() {
1524 a.rare_mut().description = description;
1525 }
1526 });
1527 self
1528 }
1529
1530 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1532 self.node().bind_attr(role, |a, role| a.role = role);
1533 self
1534 }
1535
1536 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1539 self.node().bind_attr(state, |a, state| {
1540 a.state = AccessibilityState {
1541 disabled: a.state.disabled,
1542 ..state
1543 };
1544 });
1545 self
1546 }
1547
1548 fn accessibility_level(mut self, level: impl IntoReactive<u32>) -> Self {
1552 self.node().bind_attr(level, |a, level| {
1553 super::host::set_in(
1554 &mut a.props,
1555 Prop::Accessibility(AccessibilityProp::Level((level > 0).then_some(level))),
1556 )
1557 });
1558 self
1559 }
1560
1561 fn accessibility_active_descendant(
1569 mut self,
1570 target: impl IntoReactive<Option<super::ElementRef>>,
1571 ) -> Self {
1572 self.node()
1573 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1574 super::host::set_in(
1575 &mut a.props,
1576 Prop::Accessibility(AccessibilityProp::ActiveDescendant(
1577 target.and_then(|t| t.element_target()),
1578 )),
1579 )
1580 });
1581 self
1582 }
1583
1584 fn accessibility_controls(
1588 mut self,
1589 target: impl IntoReactive<Option<super::ElementRef>>,
1590 ) -> Self {
1591 self.node()
1592 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1593 super::host::set_in(
1594 &mut a.props,
1595 Prop::Accessibility(AccessibilityProp::Controls(
1596 target.and_then(|t| t.element_target()),
1597 )),
1598 )
1599 });
1600 self
1601 }
1602
1603 fn accessibility_described_by(
1610 mut self,
1611 target: impl IntoReactive<Option<super::ElementRef>>,
1612 ) -> Self {
1613 self.node()
1614 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1615 super::host::set_in(
1616 &mut a.props,
1617 Prop::Accessibility(AccessibilityProp::DescribedBy(
1618 target.and_then(|t| t.element_target()),
1619 )),
1620 )
1621 });
1622 self
1623 }
1624
1625 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1629 self.node().bind_attr(value, |a, value| {
1630 if value.is_some() || a.rare.is_some() {
1631 a.rare_mut().value = value;
1632 }
1633 });
1634 self
1635 }
1636
1637 fn accessibility_elements_hidden(mut self, hidden: impl IntoReactive<bool>) -> Self {
1643 self.node().bind_attr(hidden, |a, hidden| {
1644 super::host::set_in(
1645 &mut a.props,
1646 Prop::Accessibility(AccessibilityProp::Hidden(hidden)),
1647 )
1648 });
1649 self
1650 }
1651
1652 fn accessibility_actions(mut self, actions: Vec<crate::AccessibilityActionDef>) -> Self {
1657 super::host::set(
1658 self.node(),
1659 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1660 );
1661 self
1662 }
1663}
1664
1665pub trait IntoTooltip {
1668 #[doc(hidden)]
1669 fn apply_tooltip(self, node: &mut ElNode);
1670}
1671
1672impl IntoTooltip for AnyElement {
1673 fn apply_tooltip(self, node: &mut ElNode) {
1674 let mut hint = ElNode::new(Tag::Overlay);
1676 hint.key = Some("tooltip".into());
1677 hint.attrs.pointer_events = PointerEvents::None;
1678 let gap = Points(4.0);
1679 for prop in [
1680 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1681 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1682 crate::OverlayProp::Offset(gap),
1683 crate::OverlayProp::Margin(gap),
1684 ] {
1685 super::host::set(&mut hint, Prop::Overlay(prop));
1686 }
1687 hint.children.push(self.0);
1688 node.children.push(hint);
1689 }
1690}
1691
1692impl<C: Component> IntoTooltip for ComponentElement<C> {
1693 fn apply_tooltip(self, node: &mut ElNode) {
1694 self.into_element().apply_tooltip(node);
1695 }
1696}
1697
1698#[doc(hidden)]
1703pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1704 let mut hint = hint.0;
1705 hint.key = Some("tooltip".into());
1706 node.children.push(hint);
1707}
1708
1709pub trait Interactive: Element {
1711 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1717 tooltip.apply_tooltip(self.node());
1718 self
1719 }
1720
1721 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
1725 self.on(
1726 EventKind::FileDragEnter,
1727 events::typed(listener.into_listener(), events::file_drag),
1728 )
1729 }
1730
1731 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1733 self.on(
1734 EventKind::FileDragLeave,
1735 events::typed(listener.into_listener(), events::unit),
1736 )
1737 }
1738
1739 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1741 self.on(
1742 EventKind::FileDrop,
1743 events::typed(listener.into_listener(), events::file_drop),
1744 )
1745 }
1746
1747 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1750 self.on(
1751 EventKind::MouseEnter,
1752 events::typed(listener.into_listener(), events::mouse),
1753 )
1754 }
1755
1756 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1759 self.on(
1760 EventKind::MouseLeave,
1761 events::typed(listener.into_listener(), events::mouse),
1762 )
1763 }
1764
1765 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1770 self.on(
1771 EventKind::MouseMove,
1772 events::typed(listener.into_listener(), events::mouse),
1773 )
1774 }
1775
1776 fn on_wheel<M>(self, listener: impl IntoListener<WheelEvent, M>) -> Self {
1784 self.on(
1785 EventKind::Wheel,
1786 events::typed(listener.into_listener(), events::wheel),
1787 )
1788 }
1789
1790 fn on_pinch<M>(self, listener: impl IntoListener<PinchEvent, M>) -> Self {
1801 self.on(
1802 EventKind::Pinch,
1803 events::typed(listener.into_listener(), events::touchpad_pinch),
1804 )
1805 }
1806
1807 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1812 self.on(
1813 EventKind::MouseUp,
1814 events::typed(listener.into_listener(), events::mouse),
1815 )
1816 }
1817
1818 fn on_key_down<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1826 self.on(
1827 EventKind::KeyDown,
1828 events::typed(listener.into_listener(), events::key_event),
1829 )
1830 }
1831
1832 fn on_key_up<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1838 self.on(
1839 EventKind::KeyUp,
1840 events::typed(listener.into_listener(), events::key_event),
1841 )
1842 }
1843
1844 fn capture_keys(mut self, capture: impl IntoReactive<KeyCapture>) -> Self {
1852 super::host::bind_prop(self.node(), capture, Prop::KeyCapture);
1853 self
1854 }
1855 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1860 self.on(
1861 EventKind::ContextMenu,
1862 events::typed(listener.into_listener(), events::context_menu),
1863 )
1864 }
1865
1866 fn on_text_selection_change<M>(
1875 self,
1876 listener: impl IntoListener<super::TextSelectionEvent, M>,
1877 ) -> Self {
1878 self.on(
1879 EventKind::SelectionChange,
1880 events::typed(listener.into_listener(), events::selected_text),
1881 )
1882 }
1883
1884 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1888 self.on(
1889 EventKind::Focus,
1890 events::typed(listener.into_listener(), events::unit),
1891 )
1892 }
1893
1894 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1896 self.on(
1897 EventKind::Blur,
1898 events::typed(listener.into_listener(), events::unit),
1899 )
1900 }
1901
1902 fn on_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1908 self.on(
1909 EventKind::Press,
1910 events::typed(listener.into_listener(), events::press),
1911 )
1912 }
1913
1914 fn on_long_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1916 self.on(
1917 EventKind::LongPress,
1918 events::typed(listener.into_listener(), events::press),
1919 )
1920 }
1921
1922 fn on_press_down<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1924 self.on(
1925 EventKind::PressDown,
1926 events::typed(listener.into_listener(), events::press),
1927 )
1928 }
1929
1930 fn on_press_up<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1932 self.on(
1933 EventKind::PressUp,
1934 events::typed(listener.into_listener(), events::press),
1935 )
1936 }
1937
1938 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1940 self.on(
1941 EventKind::Layout,
1942 events::typed(listener.into_listener(), events::layout),
1943 )
1944 }
1945
1946 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1950 self.on(
1951 EventKind::Touch,
1952 events::typed(listener.into_listener(), events::touch),
1953 )
1954 }
1955
1956 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1961 if let Some(pan) = claim.pan {
1962 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1963 }
1964 super::responder::of(self.node()).claims.push(claim);
1965 self
1966 }
1967
1968 fn keep_touches(mut self, keep: bool) -> Self {
1973 super::responder::of(self.node()).keep = keep;
1974 self
1975 }
1976
1977 fn on_responder_grant<M>(
1979 mut self,
1980 listener: impl IntoListener<super::ResponderEvent, M>,
1981 ) -> Self {
1982 super::responder::of(self.node()).grant = Some(listener.into_listener());
1983 self
1984 }
1985
1986 fn on_responder_reject<M>(
1989 mut self,
1990 listener: impl IntoListener<super::ResponderEvent, M>,
1991 ) -> Self {
1992 super::responder::of(self.node()).reject = Some(listener.into_listener());
1993 self
1994 }
1995
1996 fn on_responder_start<M>(
1999 mut self,
2000 listener: impl IntoListener<super::ResponderEvent, M>,
2001 ) -> Self {
2002 super::responder::of(self.node()).start = Some(listener.into_listener());
2003 self
2004 }
2005
2006 fn on_responder_move<M>(
2008 mut self,
2009 listener: impl IntoListener<super::ResponderEvent, M>,
2010 ) -> Self {
2011 super::responder::of(self.node()).moved = Some(listener.into_listener());
2012 self
2013 }
2014
2015 fn on_responder_end<M>(
2017 mut self,
2018 listener: impl IntoListener<super::ResponderEvent, M>,
2019 ) -> Self {
2020 super::responder::of(self.node()).end = Some(listener.into_listener());
2021 self
2022 }
2023
2024 fn on_responder_release<M>(
2027 mut self,
2028 listener: impl IntoListener<super::ResponderEvent, M>,
2029 ) -> Self {
2030 super::responder::of(self.node()).release = Some(listener.into_listener());
2031 self
2032 }
2033
2034 fn on_responder_terminate<M>(
2037 mut self,
2038 listener: impl IntoListener<super::ResponderEvent, M>,
2039 ) -> Self {
2040 super::responder::of(self.node()).terminate = Some(listener.into_listener());
2041 self
2042 }
2043
2044 fn pan_values(
2049 mut self,
2050 x: Option<&super::AnimatedValue>,
2051 y: Option<&super::AnimatedValue>,
2052 ) -> Self {
2053 let x = x.and_then(|v| v.node().live());
2054 let y = y.and_then(|v| v.node().live());
2055 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
2056 super::host::set(self.node(), prop);
2057 if x.is_some() || y.is_some() {
2058 let bound = &mut self.node().attrs.rare_mut().bound;
2059 bound.extend(x);
2060 bound.extend(y);
2061 }
2062 self
2063 }
2064
2065 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
2068 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
2069 self
2070 }
2071
2072 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
2077 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
2078 self
2079 }
2080
2081 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
2086 if let Some(node) = scale.node().live() {
2087 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
2088 self.node().attrs.rare_mut().bound.push(node);
2089 }
2090 self
2091 }
2092
2093 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
2097 if let Some(node) = angle.node().live() {
2098 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
2099 self.node().attrs.rare_mut().bound.push(node);
2100 }
2101 self
2102 }
2103
2104 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2106 self.on(
2107 EventKind::PanStart,
2108 events::typed(listener.into_listener(), events::pan),
2109 )
2110 }
2111
2112 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2114 self.on(
2115 EventKind::PanEnd,
2116 events::typed(listener.into_listener(), events::pan),
2117 )
2118 }
2119
2120 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2122 self.on(
2123 EventKind::PinchStart,
2124 events::typed(listener.into_listener(), events::pinch),
2125 )
2126 }
2127
2128 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2130 self.on(
2131 EventKind::PinchEnd,
2132 events::typed(listener.into_listener(), events::pinch),
2133 )
2134 }
2135
2136 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2138 self.on(
2139 EventKind::RotationStart,
2140 events::typed(listener.into_listener(), events::rotation),
2141 )
2142 }
2143
2144 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2146 self.on(
2147 EventKind::RotationEnd,
2148 events::typed(listener.into_listener(), events::rotation),
2149 )
2150 }
2151
2152 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
2154 self.on(
2155 EventKind::AccessibilityAction,
2156 events::typed(listener.into_listener(), events::action),
2157 )
2158 }
2159
2160 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
2163 self.node().handlers.push((kind, listener.into_listener()));
2164 self
2165 }
2166
2167 fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
2169 super::host::bind_prop(self.node(), insets, Prop::HitSlop);
2170 self
2171 }
2172
2173 #[doc(hidden)]
2177 fn __link_href(mut self, href: impl IntoReactive<Option<SharedString>>) -> Self {
2178 super::host::bind_prop(self.node(), href, |href: Option<SharedString>| {
2179 Prop::Href(href.map(|href| href.to_arc()))
2180 });
2181 self
2182 }
2183
2184 fn long_press_delay(mut self, ms: f32) -> Self {
2186 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
2187 self
2188 }
2189
2190 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
2192 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
2193 self
2194 }
2195
2196 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
2198 super::host::set(self.node(), Prop::Elevation(elevation.into()));
2199 self
2200 }
2201
2202 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
2204 super::host::set(self.node(), Prop::BackdropMaterial(material));
2205 self
2206 }
2207
2208 fn macos_backdrop(mut self, backdrop: impl IntoReactive<Option<crate::MacOsBackdrop>>) -> Self {
2211 super::host::bind_prop(self.node(), backdrop, Prop::MacOsBackdrop);
2212 self
2213 }
2214
2215 fn windows_backdrop(
2219 mut self,
2220 backdrop: impl IntoReactive<Option<crate::WindowsBackdrop>>,
2221 ) -> Self {
2222 super::host::bind_prop(self.node(), backdrop, Prop::WindowsBackdrop);
2223 self
2224 }
2225
2226 fn test_id(mut self, id: &str) -> Self {
2228 super::host::set(self.node(), Prop::TestId(Some(id.into())));
2229 self
2230 }
2231
2232 fn web_element(mut self, element: crate::WebElement) -> Self {
2238 super::host::set(self.node(), Prop::WebElement(Some(element)));
2239 self
2240 }
2241
2242 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
2250 super::host::bind_prop(self.node(), enabled, |enabled| {
2251 Prop::WindowDrag(Some(enabled))
2252 });
2253 self
2254 }
2255
2256 fn window_control(mut self, control: crate::desktop::WindowControl) -> Self {
2261 super::host::set(self.node(), Prop::WindowControl(Some(control)));
2262 self
2263 }
2264
2265 fn window_resize(mut self, edge: crate::desktop::ResizeEdge) -> Self {
2268 super::host::set(self.node(), Prop::WindowResize(Some(edge)));
2269 self
2270 }
2271
2272 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
2280 super::host::bind_prop(self.node(), focusable, |focusable| {
2281 Prop::Focusable(Some(focusable))
2282 });
2283 self
2284 }
2285
2286 fn native_id(mut self, id: &str) -> Self {
2289 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
2290 self
2291 }
2292
2293 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2295 let s = f(StyleRefinement::default());
2296 self.style().extend_as(Variant::ACTIVE, s);
2297 self
2298 }
2299
2300 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2302 let s = f(StyleRefinement::default());
2303 self.style().extend_as(Variant::HOVER, s);
2304 self
2305 }
2306
2307 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2309 let s = f(StyleRefinement::default());
2310 self.style().extend_as(Variant::FOCUS, s);
2311 self
2312 }
2313
2314 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2319 let s = f(StyleRefinement::default());
2320 self.style().extend_as(Variant::FOCUS_VISIBLE, s);
2321 self
2322 }
2323
2324 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2329 let s = f(StyleRefinement::default());
2330 self.style().extend_as(Variant::FOCUS_WITHIN, s);
2331 self
2332 }
2333
2334 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2336 let s = f(StyleRefinement::default());
2337 self.style().extend_as(Variant::DISABLED, s);
2338 self
2339 }
2340
2341 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2343 self.node().bind_attr(disabled, |a, disabled| {
2344 a.disabled = disabled;
2345 a.state.disabled = disabled;
2346 });
2347 self
2348 }
2349
2350 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
2353 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
2354 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
2355 });
2356 self
2357 }
2358
2359 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
2363 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
2364 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
2365 });
2366 self
2367 }
2368
2369 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
2373 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
2374 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
2375 });
2376 self
2377 }
2378
2379 fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
2383 Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
2384 super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
2385 });
2386 self
2387 }
2388
2389 fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
2393 Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
2394 super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
2395 });
2396 self
2397 }
2398
2399 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
2405 self.node().bind_attr(checked, |a, checked| {
2406 project(a, crate::tailwind::state::CHECKED, checked)
2407 });
2408 self
2409 }
2410
2411 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
2417 self.node().bind_attr(indeterminate, |a, indeterminate| {
2418 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
2419 });
2420 self
2421 }
2422
2423 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2428 self.node().bind_attr(disabled, |a, disabled| {
2429 project(a, crate::tailwind::state::DISABLED, disabled)
2430 });
2431 self
2432 }
2433
2434 fn project_hovered(mut self, hovered: impl IntoReactive<bool>) -> Self {
2440 self.node().bind_attr(hovered, |a, hovered| {
2441 project(a, crate::tailwind::state::HOVERED, hovered)
2442 });
2443 self
2444 }
2445
2446 fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
2455 self.node().bind_attr(focused, |a, focused| {
2456 project(a, crate::tailwind::state::FOCUSED, focused)
2457 });
2458 self
2459 }
2460
2461 fn project_group_active(mut self, group: &'static str) -> Self {
2471 self.node().bind_attr(true, move |a, _: bool| {
2472 a.rare_mut().projected_active = Some(group)
2473 });
2474 self
2475 }
2476
2477 fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
2486 self.node().bind_attr(on, move |a, on| {
2487 if !on && a.rare.is_none() {
2488 return;
2489 }
2490 let data = &mut a.rare_mut().projected_data;
2491 let at = data.binary_search(&name);
2492 match (at, on) {
2493 (Err(i), true) => data.insert(i, name),
2494 (Ok(i), false) => {
2495 data.remove(i);
2496 }
2497 _ => {}
2498 }
2499 });
2500 self
2501 }
2502}
2503
2504fn project(a: &mut Attrs, bit: u16, on: bool) {
2506 if on {
2507 a.rare_mut().projected_states |= bit;
2508 } else if let Some(r) = &mut a.rare {
2509 r.projected_states &= !bit;
2510 }
2511}
2512
2513macro_rules! element {
2514 ($(#[$doc:meta])* $name:ident) => {
2515 $(#[$doc])*
2516 #[derive(Clone)]
2517 pub struct $name(ElNode);
2518
2519 impl Element for $name {
2520 fn node(&mut self) -> &mut ElNode {
2521 &mut self.0
2522 }
2523 }
2524
2525 impl IntoElement for $name {
2526 fn into_element(self) -> AnyElement {
2527 AnyElement(self.0)
2528 }
2529 }
2530
2531 impl Accessible for $name {}
2532
2533 impl IntoTooltip for $name {
2534 fn apply_tooltip(self, node: &mut ElNode) {
2535 self.into_element().apply_tooltip(node);
2536 }
2537 }
2538 };
2539}
2540
2541element! {
2542 View
2544}
2545
2546element! {
2547 Text
2549}
2550
2551element! {
2552 Image
2554}
2555
2556element! {
2557 SlotElement
2560}
2561
2562element! {
2563 ListElement
2565}
2566
2567impl Interactive for View {}
2568impl ParentElement for View {}
2569
2570impl View {
2571 pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2585 let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2586 t.and_then(|t| t.target()).map(super::FollowTarget)
2587 });
2588 super::host::bind_prop(&mut self.0, target, Prop::Follow);
2589 self
2590 }
2591
2592 pub fn follow_transition(
2598 mut self,
2599 transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2600 ) -> Self {
2601 super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2602 self
2603 }
2604}
2605impl Interactive for SlotElement {}
2606impl Interactive for Text {}
2607impl Interactive for Image {}
2608
2609impl ParentElement for Text {
2614 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2615 let at = self.0.children.len();
2616 child.__push_into(&mut self.0.children);
2617 for el in &mut self.0.children[at..] {
2618 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2619 }
2620 self
2621 }
2622
2623 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2624 self.0
2625 .children
2626 .extend(children.into_iter().map(|c| span(c.into_element().0)));
2627 self
2628 }
2629}
2630
2631fn span(mut el: ElNode) -> ElNode {
2634 if el.tag == Tag::Text
2635 && matches!(el.kind, ElKind::Plain)
2636 && el.key.is_none()
2637 && el.children.is_empty()
2638 && el.handlers.is_empty()
2639 && el.style.is_empty()
2640 && el.attrs == Attrs::default()
2641 && !el.is_bound()
2642 {
2643 el.kind = ElKind::Raw;
2644 }
2645 el
2646}
2647
2648impl Text {
2649 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2651 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2652 Prop::SelectionColor(Some(Color::from(c)))
2653 });
2654 self
2655 }
2656
2657 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2659 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2660 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2661 self
2662 }
2663
2664 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2667 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2668 self
2669 }
2670
2671 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2674 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2675 self
2676 }
2677}
2678
2679impl Image {
2680 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2683 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2684 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2685 uri: src.uri.to_arc(),
2686 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2687 scales: src.scales,
2688 data: src.data,
2689 })))
2690 });
2691 self
2692 }
2693
2694 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2696 Styled::tint_color(self, color)
2697 }
2698
2699 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2701 super::host::set(
2702 &mut self.0,
2703 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2704 );
2705 self
2706 }
2707
2708 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2710 super::host::bind_prop(&mut self.0, ms, |ms| {
2711 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
2712 });
2713 self
2714 }
2715
2716 pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
2718 self.on(
2719 EventKind::Load,
2720 events::typed(listener.into_listener(), events::pixel_size),
2721 )
2722 }
2723
2724 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
2726 self.on(
2727 EventKind::Error,
2728 events::typed(listener.into_listener(), events::message),
2729 )
2730 }
2731
2732 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
2734 self.on(
2735 EventKind::LoadStart,
2736 events::typed(listener.into_listener(), events::unit),
2737 )
2738 }
2739
2740 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
2742 self.on(
2743 EventKind::LoadEnd,
2744 events::typed(listener.into_listener(), events::unit),
2745 )
2746 }
2747
2748 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
2751 self.on(
2752 EventKind::Progress,
2753 events::typed(listener.into_listener(), events::image_progress),
2754 )
2755 }
2756}
2757
2758impl super::Scrollable for ListElement {}
2759
2760impl super::ListLayout for ListElement {
2761 fn config(&mut self) -> &mut ListConfig {
2762 match &mut self.0.kind {
2763 ElKind::List(list) => &mut list.config,
2764 _ => unreachable!("a ListElement is a list"),
2765 }
2766 }
2767
2768 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
2769 &mut self.0.bound_list
2770 }
2771}
2772
2773#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2776pub struct Slot {
2777 name: &'static str,
2778}
2779
2780impl Slot {
2781 pub(crate) fn new(name: &'static str) -> Self {
2782 Self { name }
2783 }
2784
2785 pub fn name(&self) -> &'static str {
2787 self.name
2788 }
2789
2790 pub fn element(self) -> SlotElement {
2792 let mut node = ElNode::new(Tag::View);
2793 node.kind = ElKind::Slot(self.name);
2794 SlotElement(node)
2795 }
2796}
2797
2798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2802pub struct Items {
2803 name: &'static str,
2804}
2805
2806impl Items {
2807 #[doc(hidden)]
2808 pub const fn __new(name: &'static str) -> Self {
2809 Self { name }
2810 }
2811}
2812
2813#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2817pub struct Child(ChildRef);
2818
2819#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2820enum ChildRef {
2821 Js(NodeId),
2822 Row,
2823}
2824
2825impl Child {
2826 pub(crate) fn js(id: NodeId) -> Self {
2827 Self(ChildRef::Js(id))
2828 }
2829
2830 pub(crate) fn row() -> Self {
2831 Self(ChildRef::Row)
2832 }
2833}
2834
2835impl IntoElement for Child {
2836 fn into_element(self) -> AnyElement {
2837 let mut node = ElNode::new(Tag::View);
2838 node.kind = match self.0 {
2839 ChildRef::Js(id) => ElKind::JsChild(id),
2840 ChildRef::Row => ElKind::Children,
2841 };
2842 AnyElement(node)
2843 }
2844}
2845
2846pub fn view() -> View {
2848 View(ElNode::new(Tag::View))
2849}
2850
2851pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2854 let mut node = ElNode::new(Tag::Text);
2855 match content.into_reactive() {
2856 Reactive::Static(content) => node.text = Some(content),
2857 Reactive::Bound(content) => {
2858 node.text = Some(SharedString::default());
2859 node.bound_text = Some(content);
2860 }
2861 }
2862 Text(node)
2863}
2864
2865pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2869 let mut node = ElNode::new(Tag::Image);
2870 node.bind_attr(src, |a, src| a.rare_mut().src = Some(src));
2871 Image(node)
2872}
2873
2874#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2877pub struct Children {
2878 present: bool,
2879}
2880
2881impl Children {
2882 pub(crate) fn new(present: bool) -> Self {
2883 Self { present }
2884 }
2885
2886 pub fn is_empty(&self) -> bool {
2888 !self.present
2889 }
2890}
2891
2892impl IntoElement for Children {
2893 fn into_element(self) -> AnyElement {
2894 let mut node = ElNode::new(Tag::View);
2895 node.kind = ElKind::Children;
2896 AnyElement(node)
2897 }
2898}
2899
2900pub struct ComponentElement<C: Component> {
2913 node: ElNode,
2914 _component: PhantomData<fn() -> C>,
2915}
2916
2917impl<C: Component> ComponentElement<C> {
2918 #[doc(hidden)]
2921 pub fn __new(props: C::Props) -> Self {
2922 Self::new(props)
2923 }
2924
2925 #[doc(hidden)]
2927 pub fn __props_mut(&mut self) -> &mut C::Props {
2928 match &mut self.node.kind {
2929 ElKind::Component(c) => c
2930 .props
2931 .as_any_mut()
2932 .downcast_mut::<C::Props>()
2933 .expect("a component element holds its component's props"),
2934 _ => unreachable!("a component element is a component's"),
2935 }
2936 }
2937
2938 pub(crate) fn new(props: C::Props) -> Self {
2939 let mut node = ElNode::new(Tag::View);
2940 node.kind = ElKind::Component(ComponentEl {
2941 name: super::component::name_of::<C>(),
2942 make: super::component::make_instance::<C>,
2943 spec: ComponentSpec::of::<C>,
2944 props: Box::new(props),
2945 on_event: Vec::new(),
2946 });
2947 Self {
2948 node,
2949 _component: PhantomData,
2950 }
2951 }
2952
2953 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2958 self.node
2959 .children
2960 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2961 let mut fill = ElNode::new(Tag::View);
2962 fill.kind = ElKind::Fill(slot);
2963 fill.children.push(content.into_element().0);
2964 self.node.children.push(fill);
2965 self
2966 }
2967
2968 pub fn items(mut self, list: super::VirtualList) -> Self {
2976 match <C::Props as super::Props>::ITEMS {
2977 Some(name) => self.node.children.push(list.into_items(name)),
2978 None => {
2979 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2980 }
2981 }
2982 self
2983 }
2984
2985 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2990 let s = f(StyleRefinement::default());
2991 self.node.style.extend_as(Variant::ACTIVE, s);
2992 self
2993 }
2994
2995 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2997 let s = f(StyleRefinement::default());
2998 self.node.style.extend_as(Variant::HOVER, s);
2999 self
3000 }
3001
3002 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3004 let s = f(StyleRefinement::default());
3005 self.node.style.extend_as(Variant::FOCUS, s);
3006 self
3007 }
3008
3009 pub fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3012 let s = f(StyleRefinement::default());
3013 self.node.style.extend_as(Variant::FOCUS_VISIBLE, s);
3014 self
3015 }
3016
3017 pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3020 let s = f(StyleRefinement::default());
3021 self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
3022 self
3023 }
3024
3025 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3028 let s = f(StyleRefinement::default());
3029 self.node.style.extend_as(Variant::DISABLED, s);
3030 self
3031 }
3032
3033 pub fn test_id(mut self, id: &str) -> Self {
3036 super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
3037 self
3038 }
3039
3040 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
3042 self.node.attrs.set_element_ref(handle.element().target());
3043 self
3044 }
3045
3046 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
3052 let listener = listener.into_listener();
3053 if let ElKind::Component(c) = &mut self.node.kind {
3054 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
3055 if let Some(event) = event.downcast_ref::<C::Event>() {
3056 inner(event);
3057 }
3058 }));
3059 }
3060 self
3061 }
3062
3063 #[doc(hidden)]
3067 pub fn __on_variant<T: ?Sized + 'static, M>(
3068 self,
3069 pick: fn(&C::Event) -> Option<&T>,
3070 listener: impl IntoListener<T, M>,
3071 ) -> Self {
3072 let listener = listener.into_listener();
3073 self.on_event(listener.wrap(move |inner, event: &C::Event| {
3074 if let Some(data) = pick(event) {
3075 inner(data);
3076 }
3077 }))
3078 }
3079}
3080
3081pub trait ComponentBuilder: Element {
3153 type Component: Component;
3155
3156 #[doc(hidden)]
3158 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
3159
3160 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3165 let s = f(StyleRefinement::default());
3166 self.node().style.extend_as(Variant::ACTIVE, s);
3167 self
3168 }
3169
3170 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3172 let s = f(StyleRefinement::default());
3173 self.node().style.extend_as(Variant::HOVER, s);
3174 self
3175 }
3176
3177 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3179 let s = f(StyleRefinement::default());
3180 self.node().style.extend_as(Variant::FOCUS, s);
3181 self
3182 }
3183
3184 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3187 let s = f(StyleRefinement::default());
3188 self.node().style.extend_as(Variant::FOCUS_VISIBLE, s);
3189 self
3190 }
3191
3192 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3195 let s = f(StyleRefinement::default());
3196 self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
3197 self
3198 }
3199
3200 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3203 let s = f(StyleRefinement::default());
3204 self.node().style.extend_as(Variant::DISABLED, s);
3205 self
3206 }
3207
3208 #[doc(hidden)]
3211 fn __listen(mut self, kind: EventKind, listener: Listener<EventPayload>) -> Self {
3212 self.node().handlers.push((kind, listener));
3213 self
3214 }
3215
3216 fn test_id(mut self, id: &str) -> Self {
3219 super::host::set(self.node(), Prop::TestId(Some(id.into())));
3220 self
3221 }
3222
3223 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
3227 let listener = events::typed(listener.into_listener(), events::layout);
3228 self.__listen(EventKind::Layout, listener)
3229 }
3230
3231 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3235 let listener = events::typed(listener.into_listener(), events::mouse);
3236 self.__listen(EventKind::MouseEnter, listener)
3237 }
3238
3239 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3242 let listener = events::typed(listener.into_listener(), events::mouse);
3243 self.__listen(EventKind::MouseLeave, listener)
3244 }
3245
3246 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3250 let listener = events::typed(listener.into_listener(), events::mouse);
3251 self.__listen(EventKind::MouseMove, listener)
3252 }
3253
3254 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3257 let listener = events::typed(listener.into_listener(), events::mouse);
3258 self.__listen(EventKind::MouseUp, listener)
3259 }
3260
3261 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
3266 let listener = events::typed(listener.into_listener(), events::context_menu);
3267 self.__listen(EventKind::ContextMenu, listener)
3268 }
3269
3270 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
3273 let listener = events::typed(listener.into_listener(), events::file_drag);
3274 self.__listen(EventKind::FileDragEnter, listener)
3275 }
3276
3277 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
3280 let listener = events::typed(listener.into_listener(), events::unit);
3281 self.__listen(EventKind::FileDragLeave, listener)
3282 }
3283
3284 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
3287 let listener = events::typed(listener.into_listener(), events::file_drop);
3288 self.__listen(EventKind::FileDrop, listener)
3289 }
3290
3291 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
3293 self.__element()
3294 .node
3295 .attrs
3296 .set_element_ref(handle.element().target());
3297 self
3298 }
3299}
3300
3301impl<C: Component> Element for ComponentElement<C> {
3302 fn node(&mut self) -> &mut ElNode {
3303 &mut self.node
3304 }
3305}
3306
3307impl<C: Component> ParentElement for ComponentElement<C> {}
3311
3312impl<C: Component> IntoElement for ComponentElement<C> {
3313 fn into_element(self) -> AnyElement {
3314 AnyElement(self.node)
3315 }
3316}
3317
3318#[cfg(test)]
3319mod file_listener_tests {
3320 use std::cell::Cell;
3321
3322 use super::*;
3323
3324 #[test]
3325 fn file_drag_enter_keeps_all_original_listener_forms() {
3326 let calls = Rc::new(Cell::new(0));
3327 let a = calls.clone();
3328 let b = calls.clone();
3329 let c = calls.clone();
3330 let d = calls.clone();
3331 let unit: Listener<()> = (move |_: &()| c.set(c.get() + 1)).into_listener();
3332 let nodes = [
3333 view().on_file_drag_enter(move || a.set(a.get() + 1)),
3334 view().on_file_drag_enter(move |_: &()| b.set(b.get() + 1)),
3335 view().on_file_drag_enter(unit),
3336 view().on_file_drag_enter(move |e: &events::FileDragEvent| {
3337 assert_eq!(e.uris, ["file:///tmp/a%20b.png"]);
3338 assert_eq!(e.mime_types, ["image/png"]);
3339 d.set(d.get() + 1);
3340 }),
3341 ];
3342 let payload = EventPayload::FileDrop(vec!["file:///tmp/a%20b.png".into()]);
3343 for mut node in nodes {
3344 let listener = node
3345 .node()
3346 .handlers
3347 .iter()
3348 .find(|(kind, _)| *kind == EventKind::FileDragEnter)
3349 .unwrap();
3350 listener.1.call(&payload);
3351 }
3352 assert_eq!(calls.get(), 4);
3353 }
3354}