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}
527
528impl Position {
529 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
532 Self { index, count }
533 }
534
535 pub(crate) fn fixed(index: usize, count: usize) -> Self {
537 Self::of(super::signal(index).node(), super::signal(count).node())
538 }
539
540 #[track_caller]
542 pub fn index(&self) -> usize {
543 self.index.with("a position", |i: &usize| *i)
544 }
545
546 #[track_caller]
548 pub fn count(&self) -> usize {
549 self.count.with("a position", |n: &usize| *n)
550 }
551
552 #[track_caller]
554 pub fn is_first(&self) -> bool {
555 self.index() == 0
556 }
557
558 #[track_caller]
560 pub fn is_last(&self) -> bool {
561 self.index() + 1 == self.count()
562 }
563}
564
565impl fmt::Debug for Position {
566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567 let (index, count) = super::untracked(|| (self.index(), self.count()));
568 write!(f, "Position({index} of {count})")
569 }
570}
571
572#[doc(hidden)]
575#[derive(Debug, Clone, Copy, Default, PartialEq)]
576pub struct ListConfig {
577 pub(crate) estimated: Option<f32>,
578 pub(crate) columns: Option<u32>,
579 pub(crate) horizontal: Option<bool>,
580 pub(crate) inverted: Option<bool>,
581 pub(crate) scrollbar_visible: Option<bool>,
582 pub(crate) content: Option<ListContentStyle>,
583 pub(crate) follow_end: Option<f32>,
584 pub(crate) alignment: Option<crate::ListAlignment>,
585 pub(crate) viewport: Option<crate::ListViewport>,
586}
587
588impl ListConfig {
589 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
591 if self.estimated != old.estimated {
592 out.push(Prop::EstimatedItemSize(Points(
593 self.estimated.unwrap_or(50.0),
594 )));
595 }
596 if self.columns != old.columns {
597 out.push(Prop::Columns(self.columns.unwrap_or(1)));
598 }
599 if self.horizontal != old.horizontal {
600 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
601 }
602 if self.inverted != old.inverted {
603 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
604 }
605 if self.scrollbar_visible != old.scrollbar_visible {
606 out.push(Prop::Scrollbar(
607 self.scrollbar_visible.unwrap_or(true).into(),
608 ));
609 }
610 if self.content != old.content {
611 out.push(Prop::ListContent(self.content.unwrap_or_default()));
612 }
613 if self.follow_end != old.follow_end {
614 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
615 }
616 if self.alignment != old.alignment {
617 out.push(Prop::ListAlignment(self.alignment.unwrap_or_default()));
618 }
619 if self.viewport != old.viewport {
620 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
621 }
622 }
623}
624
625#[derive(Clone)]
627pub(crate) struct ListEl {
628 pub(crate) name: &'static str,
629 pub(crate) config: ListConfig,
630 pub(crate) row: PlaceFn,
631}
632
633#[derive(Clone)]
635pub(crate) enum ElKind {
636 Plain,
637 Slot(&'static str),
639 Fill(&'static str),
642 Filled(&'static str),
645 Children,
647 JsChild(NodeId),
649 EachChild(PlaceFn),
651 List(Box<ListEl>),
653 VirtualList(Box<super::virtual_list::VirtualListEl>),
655 Raw,
658 Component(ComponentEl),
659 Region(super::flow::Region),
663}
664
665#[doc(hidden)]
667#[derive(Clone)]
668pub struct ElNode {
669 pub(crate) tag: Tag,
670 pub(crate) key: Option<SharedString>,
671 pub(crate) text: Option<SharedString>,
673 pub(crate) attrs: Attrs,
674 pub(crate) style: StyleRefinement,
675 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
676 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
678 pub(crate) children: Vec<ElNode>,
679 pub(crate) kind: ElKind,
680 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
682 pub(crate) bound_attrs: Vec<BoundAttrs>,
684 pub(crate) bound_list: Vec<BoundListConfig>,
686}
687
688#[doc(hidden)]
690pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
691
692crate::static_reactive!(AccessibilityState: AccessibilityState);
693crate::static_reactive!(EdgeInsets: EdgeInsets);
694crate::static_reactive!(Style: Style);
695crate::static_reactive!(PointerEvents: PointerEvents);
696crate::static_reactive!(KeyCapture: KeyCapture);
697
698pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
700
701impl ElNode {
702 pub(crate) fn bind_attr<T: 'static>(
705 &mut self,
706 value: impl IntoReactive<T>,
707 apply: impl Fn(&mut Attrs, T) + 'static,
708 ) {
709 match value.into_reactive() {
710 Reactive::Static(v) => apply(&mut self.attrs, v),
711 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
712 }
713 }
714
715 pub(crate) fn is_bound(&self) -> bool {
717 self.bound_text.is_some()
718 || !self.bound_attrs.is_empty()
719 || self.style.is_bound()
720 || !self.bound_list.is_empty()
721 }
722
723 pub(crate) fn resolved_attrs(&self) -> Attrs {
726 let mut attrs = self.attrs.clone();
727 for part in &self.bound_attrs {
728 part(&mut attrs);
729 }
730 attrs
731 }
732
733 pub(crate) fn resolve_once(&mut self) {
736 if !self.is_bound() {
737 return;
738 }
739 super::untracked(|| {
740 if let Some(text) = self.bound_text.take() {
741 self.text = Some(text());
742 }
743 if !self.bound_attrs.is_empty() {
744 self.attrs = self.resolved_attrs();
745 self.bound_attrs.clear();
746 }
747 if self.style.is_bound() {
748 self.style = self.style.resolved();
749 }
750 let parts = std::mem::take(&mut self.bound_list);
751 if let Some(config) = self.list_config() {
752 for part in &parts {
753 part(config);
754 }
755 }
756 });
757 }
758
759 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
761 match &mut self.kind {
762 ElKind::List(list) => Some(&mut list.config),
763 ElKind::VirtualList(list) => Some(&mut list.config),
764 _ => None,
765 }
766 }
767
768 pub(crate) fn empty_view() -> Self {
770 Self::new(Tag::View)
771 }
772
773 pub(crate) fn new(tag: Tag) -> Self {
774 Self {
775 tag,
776 key: None,
777 text: None,
778 attrs: Attrs::default(),
779 style: StyleRefinement::default(),
780 handlers: Vec::new(),
781 responder: None,
782 children: Vec::new(),
783 kind: ElKind::Plain,
784 bound_text: None,
785 bound_attrs: Vec::new(),
786 bound_list: Vec::new(),
787 }
788 }
789}
790
791pub struct AnyElement(pub(crate) ElNode);
793
794pub trait IntoElement {
796 fn into_element(self) -> AnyElement;
798}
799
800impl IntoElement for AnyElement {
801 fn into_element(self) -> AnyElement {
802 self
803 }
804}
805
806impl IntoElement for SharedString {
807 fn into_element(self) -> AnyElement {
808 text(self).into_element()
809 }
810}
811
812impl IntoElement for &'static str {
813 fn into_element(self) -> AnyElement {
814 text(self).into_element()
815 }
816}
817
818impl IntoElement for String {
819 fn into_element(self) -> AnyElement {
820 text(self).into_element()
821 }
822}
823
824#[diagnostic::on_unimplemented(
830 message = "`{Self}` is not an element",
831 label = "not an element",
832 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
833)]
834pub trait IntoChild<M> {
835 #[doc(hidden)]
837 fn __push_into(self, out: &mut Vec<ElNode>);
838}
839
840#[doc(hidden)]
842pub struct OneChild(());
843
844#[doc(hidden)]
846pub struct ManyChildren(());
847
848impl<T: IntoElement> IntoChild<OneChild> for T {
849 fn __push_into(self, out: &mut Vec<ElNode>) {
850 out.push(self.into_element().0);
851 }
852}
853
854impl<I: IntoIterator> IntoChild<ManyChildren> for I
855where
856 I::Item: IntoElement,
857{
858 fn __push_into(self, out: &mut Vec<ElNode>) {
859 out.extend(self.into_iter().map(|c| c.into_element().0));
860 }
861}
862
863pub trait FluentBuilder: Sized {
867 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
869 if condition { then(self) } else { self }
870 }
871
872 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
874 match option {
875 Some(v) => then(self, v),
876 None => self,
877 }
878 }
879
880 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
882 f(self)
883 }
884}
885
886impl<T: Element> FluentBuilder for T {}
887
888pub trait Element: IntoElement + Sized {
892 #[doc(hidden)]
893 fn node(&mut self) -> &mut ElNode;
894
895 fn key(mut self, key: impl Into<SharedString>) -> Self {
898 self.node().key = Some(key.into());
899 self
900 }
901
902 fn bind_opacity(self, value: &impl super::Animated) -> Self {
904 self.bind(crate::animation::AnimationProp::Opacity, value)
905 }
906
907 fn bind_background(self, value: &impl super::Animated) -> Self {
910 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
911 }
912
913 fn bind_border_color(self, value: &impl super::Animated) -> Self {
915 self.bind(crate::animation::AnimationProp::BorderColor, value)
916 }
917
918 fn bind_color(self, value: &impl super::Animated) -> Self {
920 self.bind(crate::animation::AnimationProp::Color, value)
921 }
922
923 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
926 if let Some(node) = value.animated_node().live() {
927 let decl = crate::StyleDecl::Animated(prop, node.id());
928 self.node().attrs.rare_mut().animated.push((decl, node));
929 }
930 self
931 }
932
933 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
938 self.bind(crate::animation::AnimationProp::StickyTop, value)
939 }
940
941 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
943 self.bind(crate::animation::AnimationProp::StickyLeft, value)
944 }
945
946 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
949 if let Some(node) = value.animated_node().live() {
950 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
951 self.node().attrs.rare_mut().animated.push((decl, node));
952 }
953 self
954 }
955
956 fn bind_motion(self, motion: &super::Motion) -> Self {
960 use crate::animation::MotionChannel::*;
961 let mut this = self.bind_opacity(&motion.value(Opacity));
962 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
963 if let Some(kind) = channel.transform() {
964 this = this.bind_transform(kind, &motion.value(channel));
965 }
966 }
967 let scale = motion.value(Scale);
968 this.bind_transform(
969 crate::TransformKind::ScaleX,
970 &scale.mul(&motion.value(ScaleX)),
971 )
972 .bind_transform(
973 crate::TransformKind::ScaleY,
974 &scale.mul(&motion.value(ScaleY)),
975 )
976 }
977
978 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
980 self.bind_transform(crate::TransformKind::TranslateX, value)
981 }
982
983 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
985 self.bind_transform(crate::TransformKind::TranslateY, value)
986 }
987
988 fn bind_scale(self, value: &impl super::Animated) -> Self {
990 self.bind_transform(crate::TransformKind::Scale, value)
991 }
992
993 fn bind_rotate(self, value: &impl super::Animated) -> Self {
995 self.bind_transform(crate::TransformKind::Rotate, value)
996 }
997
998 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
1001 self.node().attrs.set_element_ref(handle.target());
1002 self
1003 }
1004
1005 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1008 self.node().bind_attr(insets, |a, insets| {
1009 a.rare_mut().inset_padding = Some(insets)
1010 });
1011 self
1012 }
1013
1014 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1016 self.node()
1017 .bind_attr(insets, |a, insets| a.rare_mut().inset_margin = Some(insets));
1018 self
1019 }
1020
1021 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
1024 Style::apply(self.node(), style, Variant::default(), |a, patch| {
1025 a.inline = patch
1026 });
1027 self
1028 }
1029
1030 fn state_inline_style(mut self, style: impl Fn() -> Style + 'static) -> Self {
1035 Style::apply_bound(
1036 self.node(),
1037 Rc::new(style),
1038 Variant::default(),
1039 true,
1040 |a, patch| a.inline = patch,
1041 );
1042 self
1043 }
1044
1045 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
1050 self.node().bind_attr(area, |a, area| {
1051 if area || a.rare.is_some() {
1052 a.rare_mut().selectable_view = area;
1053 }
1054 });
1055 self
1056 }
1057
1058 fn selection_menu(mut self, items: impl IntoReactive<Vec<super::desktop::MenuItem>>) -> Self {
1079 super::host::bind_prop(self.node(), items, |items| {
1080 Prop::SelectionMenu(super::desktop::register_selection_menu(items))
1081 });
1082 self
1083 }
1084
1085 fn continues_text(mut self, continues: impl IntoReactive<bool>) -> Self {
1093 self.node().bind_attr(continues, |a, continues| {
1094 if continues || a.rare.is_some() {
1095 a.rare_mut().continues_text = continues;
1096 }
1097 });
1098 self
1099 }
1100
1101 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
1106 self.node().bind_attr(class, |a, class| a.class = class);
1107 self
1108 }
1109}
1110
1111#[derive(Debug, Clone, Default, PartialEq)]
1125pub struct Style(
1126 pub(crate) Option<std::rc::Rc<crate::StylePatch>>,
1127 pub(crate) StyleRefinement,
1130);
1131
1132impl Style {
1133 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
1137 let mut style = crate::Style::default();
1138 let mut patch = crate::StylePatch::default();
1139 for decl in decls {
1140 let key = match &decl {
1141 crate::StyleDecl::Set(key, _) => Some(*key),
1142 _ => None,
1143 };
1144 if patch.push(&mut style, decl).is_err()
1145 && let Some(key) = key
1146 {
1147 log::warn!("invalid value for style `{}`", key.name());
1148 }
1149 }
1150 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1151 }
1152
1153 pub fn with(self, key: crate::StyleKey, value: crate::PropertyValue) -> Self {
1156 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
1157 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
1158 style.1 = self.1;
1159 style
1160 }
1161
1162 pub fn then(&self, over: &Style) -> Self {
1166 if over.0.is_none() && over.1.is_empty() {
1167 return self.clone();
1168 }
1169 if self.0.is_none() && self.1.is_empty() {
1170 return over.clone();
1171 }
1172 let mut style = if self.0.is_none() {
1173 Self(over.0.clone(), StyleRefinement::default())
1174 } else if over.0.is_none() {
1175 Self(self.0.clone(), StyleRefinement::default())
1176 } else {
1177 Self::from_decls(self.decls().iter().chain(over.decls()).cloned())
1178 };
1179 let mut typed = self.1.clone();
1180 typed.extend_as(Variant::default(), over.1.clone());
1181 style.1 = typed;
1182 style
1183 }
1184
1185 pub fn background_color(&self) -> Option<crate::element::AdaptiveColor> {
1191 let typed = self.1.static_color(crate::StyleKey::BackgroundColor);
1192 let declared = || {
1193 self.decls().iter().rev().find_map(|decl| match decl {
1194 crate::StyleDecl::Set(
1195 crate::StyleKey::BackgroundColor,
1196 crate::PropertyValue::Color(color),
1197 ) => Some(color.map(crate::element::AdaptiveColor::from)),
1198 _ => None,
1199 })?
1200 };
1201 typed
1202 .or_else(declared)
1203 .filter(|c| *c != crate::element::AdaptiveColor::from(crate::Color::TRANSPARENT))
1204 }
1205
1206 pub fn decls(&self) -> &[crate::StyleDecl] {
1208 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
1209 }
1210
1211 pub(crate) fn apply(
1217 node: &mut ElNode,
1218 style: impl IntoReactive<Style>,
1219 variant: Variant,
1220 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1221 ) {
1222 match style.into_reactive() {
1223 Reactive::Static(Style(patch, typed)) => {
1224 attr(&mut node.attrs, patch);
1225 if !typed.is_empty() {
1226 node.style.extend_as(variant, typed);
1227 }
1228 }
1229 Reactive::Bound(f) => Self::apply_bound(node, f, variant, false, attr),
1230 }
1231 }
1232
1233 pub(crate) fn apply_bound(
1236 node: &mut ElNode,
1237 f: Rc<dyn Fn() -> Style>,
1238 variant: Variant,
1239 typed_later: bool,
1240 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1241 ) {
1242 let typed = typed_later || super::untracked(|| !f().1.is_empty());
1243 let patch = f.clone();
1244 node.bind_attr(move || patch().0, attr);
1245 if typed {
1246 node.style
1249 .bind(move |s| s.extend_as(variant, f().1.resolved()));
1250 }
1251 }
1252}
1253
1254impl From<crate::StylePatch> for Style {
1255 fn from(patch: crate::StylePatch) -> Self {
1256 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1257 }
1258}
1259
1260impl From<StyleRefinement> for Style {
1261 fn from(style: StyleRefinement) -> Self {
1262 Self(None, style)
1263 }
1264}
1265
1266impl JsValue for Style {
1267 fn ts_type(_types: &mut super::TsTypes) -> String {
1268 "StyleProp<ViewStyle>".into()
1269 }
1270
1271 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1274 if value.is_nullish() {
1275 return Ok(Self::default());
1276 }
1277 Ok(Self::from(value.host().style(value.raw())?))
1278 }
1279
1280 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1282 Err(PropError("a style does not convert back to JS".to_owned()))
1283 }
1284}
1285
1286#[derive(Debug, Clone, Default, PartialEq)]
1294#[non_exhaustive]
1295pub struct TextPartStyle(pub Style);
1296
1297impl From<Style> for TextPartStyle {
1298 fn from(style: Style) -> Self {
1299 Self(style)
1300 }
1301}
1302
1303impl From<StyleRefinement> for TextPartStyle {
1304 fn from(style: StyleRefinement) -> Self {
1305 Self(Style::from(style))
1306 }
1307}
1308
1309impl From<TextPartStyle> for Style {
1310 fn from(style: TextPartStyle) -> Self {
1311 style.0
1312 }
1313}
1314
1315impl JsValue for TextPartStyle {
1316 fn ts_type(_types: &mut super::TsTypes) -> String {
1317 "StyleProp<TextStyle>".into()
1318 }
1319
1320 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1321 Style::from_js(value).map(Self)
1322 }
1323
1324 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1325 self.0.to_js(host)
1326 }
1327}
1328
1329#[derive(Debug, Clone, Default, PartialEq)]
1335#[non_exhaustive]
1336pub struct InputPartStyle(pub Style);
1337
1338impl From<Style> for InputPartStyle {
1339 fn from(style: Style) -> Self {
1340 Self(style)
1341 }
1342}
1343
1344impl From<StyleRefinement> for InputPartStyle {
1345 fn from(style: StyleRefinement) -> Self {
1346 Self(Style::from(style))
1347 }
1348}
1349
1350impl From<InputPartStyle> for Style {
1351 fn from(style: InputPartStyle) -> Self {
1352 style.0
1353 }
1354}
1355
1356impl JsValue for InputPartStyle {
1357 fn ts_type(_types: &mut super::TsTypes) -> String {
1358 "StyleProp<InputStyle>".into()
1359 }
1360
1361 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1362 Style::from_js(value).map(Self)
1363 }
1364
1365 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1366 self.0.to_js(host)
1367 }
1368}
1369
1370impl<T: Element> Styled for T {
1371 fn style(&mut self) -> &mut StyleRefinement {
1372 &mut self.node().style
1373 }
1374}
1375
1376pub trait ParentElement: Element {
1378 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1381 child.__push_into(&mut self.node().children);
1382 self
1383 }
1384
1385 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1387 self.node()
1388 .children
1389 .extend(children.into_iter().map(|c| c.into_element().0));
1390 self
1391 }
1392
1393 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1396 if let Some(slot) = slot {
1397 let mut node = ElNode::new(Tag::View);
1398 node.kind = ElKind::Slot(slot.name);
1399 self.node().children.push(place(SlotElement(node)).0);
1400 }
1401 self
1402 }
1403
1404 fn children_each<R: IntoElement>(
1407 mut self,
1408 children: impl Into<Children>,
1409 place: impl Fn(Child, Position) -> R + 'static,
1410 ) -> Self {
1411 let _ = children.into();
1412 let mut node = ElNode::new(Tag::View);
1413 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1414 self.node().children.push(node);
1415 self
1416 }
1417
1418 fn list<R: IntoElement>(
1424 mut self,
1425 items: Items,
1426 config: impl FnOnce(ListElement) -> ListElement,
1427 row: impl Fn(Child, Position) -> R + 'static,
1428 ) -> Self {
1429 let mut node = ElNode::new(Tag::List);
1430 node.kind = ElKind::List(Box::new(ListEl {
1431 name: items.name,
1432 config: ListConfig::default(),
1433 row: Rc::new(move |content, at| row(content, at).into_element()),
1434 }));
1435 self.node().children.push(config(ListElement(node)).0);
1436 self
1437 }
1438}
1439
1440pub trait Accessible: Element {
1442 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1444 self.node().bind_attr(accessible, |a, accessible| {
1445 a.rare_mut().accessible = Some(accessible)
1446 });
1447 self
1448 }
1449
1450 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1452 self.node()
1453 .bind_attr(label, |a, label| a.label = Some(label));
1454 self
1455 }
1456
1457 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1460 self.node().bind_attr(label, |a, label| a.label = label);
1461 self
1462 }
1463
1464 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1466 self.node()
1467 .bind_attr(hint, |a, hint| a.rare_mut().hint = Some(hint));
1468 self
1469 }
1470
1471 fn accessibility_description(mut self, description: impl IntoReactive<SharedString>) -> Self {
1475 self.node().bind_attr(description, |a, description| {
1476 a.rare_mut().description = Some(description)
1477 });
1478 self
1479 }
1480
1481 fn optional_accessibility_description(
1485 mut self,
1486 description: impl IntoReactive<Option<SharedString>>,
1487 ) -> Self {
1488 self.node().bind_attr(description, |a, description| {
1489 if description.is_some() || a.rare.is_some() {
1490 a.rare_mut().description = description;
1491 }
1492 });
1493 self
1494 }
1495
1496 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1498 self.node().bind_attr(role, |a, role| a.role = role);
1499 self
1500 }
1501
1502 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1505 self.node().bind_attr(state, |a, state| {
1506 a.state = AccessibilityState {
1507 disabled: a.state.disabled,
1508 ..state
1509 };
1510 });
1511 self
1512 }
1513
1514 fn accessibility_level(mut self, level: impl IntoReactive<u32>) -> Self {
1518 self.node().bind_attr(level, |a, level| {
1519 super::host::set_in(
1520 &mut a.props,
1521 Prop::Accessibility(AccessibilityProp::Level((level > 0).then_some(level))),
1522 )
1523 });
1524 self
1525 }
1526
1527 fn accessibility_active_descendant(
1535 mut self,
1536 target: impl IntoReactive<Option<super::ElementRef>>,
1537 ) -> Self {
1538 self.node()
1539 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1540 super::host::set_in(
1541 &mut a.props,
1542 Prop::Accessibility(AccessibilityProp::ActiveDescendant(
1543 target.and_then(|t| t.element_target()),
1544 )),
1545 )
1546 });
1547 self
1548 }
1549
1550 fn accessibility_controls(
1554 mut self,
1555 target: impl IntoReactive<Option<super::ElementRef>>,
1556 ) -> Self {
1557 self.node()
1558 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1559 super::host::set_in(
1560 &mut a.props,
1561 Prop::Accessibility(AccessibilityProp::Controls(
1562 target.and_then(|t| t.element_target()),
1563 )),
1564 )
1565 });
1566 self
1567 }
1568
1569 fn accessibility_described_by(
1576 mut self,
1577 target: impl IntoReactive<Option<super::ElementRef>>,
1578 ) -> Self {
1579 self.node()
1580 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1581 super::host::set_in(
1582 &mut a.props,
1583 Prop::Accessibility(AccessibilityProp::DescribedBy(
1584 target.and_then(|t| t.element_target()),
1585 )),
1586 )
1587 });
1588 self
1589 }
1590
1591 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1595 self.node().bind_attr(value, |a, value| {
1596 if value.is_some() || a.rare.is_some() {
1597 a.rare_mut().value = value;
1598 }
1599 });
1600 self
1601 }
1602
1603 fn accessibility_elements_hidden(mut self, hidden: impl IntoReactive<bool>) -> Self {
1609 self.node().bind_attr(hidden, |a, hidden| {
1610 super::host::set_in(
1611 &mut a.props,
1612 Prop::Accessibility(AccessibilityProp::Hidden(hidden)),
1613 )
1614 });
1615 self
1616 }
1617
1618 fn accessibility_actions(mut self, actions: Vec<crate::AccessibilityActionDef>) -> Self {
1623 super::host::set(
1624 self.node(),
1625 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1626 );
1627 self
1628 }
1629}
1630
1631pub trait IntoTooltip {
1634 #[doc(hidden)]
1635 fn apply_tooltip(self, node: &mut ElNode);
1636}
1637
1638impl IntoTooltip for AnyElement {
1639 fn apply_tooltip(self, node: &mut ElNode) {
1640 let mut hint = ElNode::new(Tag::Overlay);
1642 hint.key = Some("tooltip".into());
1643 hint.attrs.pointer_events = PointerEvents::None;
1644 let gap = Points(4.0);
1645 for prop in [
1646 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1647 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1648 crate::OverlayProp::Offset(gap),
1649 crate::OverlayProp::Margin(gap),
1650 ] {
1651 super::host::set(&mut hint, Prop::Overlay(prop));
1652 }
1653 hint.children.push(self.0);
1654 node.children.push(hint);
1655 }
1656}
1657
1658impl<C: Component> IntoTooltip for ComponentElement<C> {
1659 fn apply_tooltip(self, node: &mut ElNode) {
1660 self.into_element().apply_tooltip(node);
1661 }
1662}
1663
1664#[doc(hidden)]
1669pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1670 let mut hint = hint.0;
1671 hint.key = Some("tooltip".into());
1672 node.children.push(hint);
1673}
1674
1675pub trait Interactive: Element {
1677 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1683 tooltip.apply_tooltip(self.node());
1684 self
1685 }
1686
1687 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
1691 self.on(
1692 EventKind::FileDragEnter,
1693 events::typed(listener.into_listener(), events::file_drag),
1694 )
1695 }
1696
1697 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1699 self.on(
1700 EventKind::FileDragLeave,
1701 events::typed(listener.into_listener(), events::unit),
1702 )
1703 }
1704
1705 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1707 self.on(
1708 EventKind::FileDrop,
1709 events::typed(listener.into_listener(), events::file_drop),
1710 )
1711 }
1712
1713 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1716 self.on(
1717 EventKind::MouseEnter,
1718 events::typed(listener.into_listener(), events::mouse),
1719 )
1720 }
1721
1722 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1725 self.on(
1726 EventKind::MouseLeave,
1727 events::typed(listener.into_listener(), events::mouse),
1728 )
1729 }
1730
1731 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1736 self.on(
1737 EventKind::MouseMove,
1738 events::typed(listener.into_listener(), events::mouse),
1739 )
1740 }
1741
1742 fn on_wheel<M>(self, listener: impl IntoListener<WheelEvent, M>) -> Self {
1750 self.on(
1751 EventKind::Wheel,
1752 events::typed(listener.into_listener(), events::wheel),
1753 )
1754 }
1755
1756 fn on_pinch<M>(self, listener: impl IntoListener<PinchEvent, M>) -> Self {
1767 self.on(
1768 EventKind::Pinch,
1769 events::typed(listener.into_listener(), events::touchpad_pinch),
1770 )
1771 }
1772
1773 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1778 self.on(
1779 EventKind::MouseUp,
1780 events::typed(listener.into_listener(), events::mouse),
1781 )
1782 }
1783
1784 fn on_key_down<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1792 self.on(
1793 EventKind::KeyDown,
1794 events::typed(listener.into_listener(), events::key_event),
1795 )
1796 }
1797
1798 fn on_key_up<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1804 self.on(
1805 EventKind::KeyUp,
1806 events::typed(listener.into_listener(), events::key_event),
1807 )
1808 }
1809
1810 fn capture_keys(mut self, capture: impl IntoReactive<KeyCapture>) -> Self {
1818 super::host::bind_prop(self.node(), capture, Prop::KeyCapture);
1819 self
1820 }
1821 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1826 self.on(
1827 EventKind::ContextMenu,
1828 events::typed(listener.into_listener(), events::context_menu),
1829 )
1830 }
1831
1832 fn on_text_selection_change<M>(
1841 self,
1842 listener: impl IntoListener<super::TextSelectionEvent, M>,
1843 ) -> Self {
1844 self.on(
1845 EventKind::SelectionChange,
1846 events::typed(listener.into_listener(), events::selected_text),
1847 )
1848 }
1849
1850 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1854 self.on(
1855 EventKind::Focus,
1856 events::typed(listener.into_listener(), events::unit),
1857 )
1858 }
1859
1860 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1862 self.on(
1863 EventKind::Blur,
1864 events::typed(listener.into_listener(), events::unit),
1865 )
1866 }
1867
1868 fn on_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1874 self.on(
1875 EventKind::Press,
1876 events::typed(listener.into_listener(), events::press),
1877 )
1878 }
1879
1880 fn on_long_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1882 self.on(
1883 EventKind::LongPress,
1884 events::typed(listener.into_listener(), events::press),
1885 )
1886 }
1887
1888 fn on_press_down<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1890 self.on(
1891 EventKind::PressDown,
1892 events::typed(listener.into_listener(), events::press),
1893 )
1894 }
1895
1896 fn on_press_up<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
1898 self.on(
1899 EventKind::PressUp,
1900 events::typed(listener.into_listener(), events::press),
1901 )
1902 }
1903
1904 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
1906 self.on(
1907 EventKind::Layout,
1908 events::typed(listener.into_listener(), events::layout),
1909 )
1910 }
1911
1912 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
1916 self.on(
1917 EventKind::Touch,
1918 events::typed(listener.into_listener(), events::touch),
1919 )
1920 }
1921
1922 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
1927 if let Some(pan) = claim.pan {
1928 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
1929 }
1930 super::responder::of(self.node()).claims.push(claim);
1931 self
1932 }
1933
1934 fn keep_touches(mut self, keep: bool) -> Self {
1939 super::responder::of(self.node()).keep = keep;
1940 self
1941 }
1942
1943 fn on_responder_grant<M>(
1945 mut self,
1946 listener: impl IntoListener<super::ResponderEvent, M>,
1947 ) -> Self {
1948 super::responder::of(self.node()).grant = Some(listener.into_listener());
1949 self
1950 }
1951
1952 fn on_responder_reject<M>(
1955 mut self,
1956 listener: impl IntoListener<super::ResponderEvent, M>,
1957 ) -> Self {
1958 super::responder::of(self.node()).reject = Some(listener.into_listener());
1959 self
1960 }
1961
1962 fn on_responder_start<M>(
1965 mut self,
1966 listener: impl IntoListener<super::ResponderEvent, M>,
1967 ) -> Self {
1968 super::responder::of(self.node()).start = Some(listener.into_listener());
1969 self
1970 }
1971
1972 fn on_responder_move<M>(
1974 mut self,
1975 listener: impl IntoListener<super::ResponderEvent, M>,
1976 ) -> Self {
1977 super::responder::of(self.node()).moved = Some(listener.into_listener());
1978 self
1979 }
1980
1981 fn on_responder_end<M>(
1983 mut self,
1984 listener: impl IntoListener<super::ResponderEvent, M>,
1985 ) -> Self {
1986 super::responder::of(self.node()).end = Some(listener.into_listener());
1987 self
1988 }
1989
1990 fn on_responder_release<M>(
1993 mut self,
1994 listener: impl IntoListener<super::ResponderEvent, M>,
1995 ) -> Self {
1996 super::responder::of(self.node()).release = Some(listener.into_listener());
1997 self
1998 }
1999
2000 fn on_responder_terminate<M>(
2003 mut self,
2004 listener: impl IntoListener<super::ResponderEvent, M>,
2005 ) -> Self {
2006 super::responder::of(self.node()).terminate = Some(listener.into_listener());
2007 self
2008 }
2009
2010 fn pan_values(
2015 mut self,
2016 x: Option<&super::AnimatedValue>,
2017 y: Option<&super::AnimatedValue>,
2018 ) -> Self {
2019 let x = x.and_then(|v| v.node().live());
2020 let y = y.and_then(|v| v.node().live());
2021 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
2022 super::host::set(self.node(), prop);
2023 if x.is_some() || y.is_some() {
2024 let bound = &mut self.node().attrs.rare_mut().bound;
2025 bound.extend(x);
2026 bound.extend(y);
2027 }
2028 self
2029 }
2030
2031 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
2034 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
2035 self
2036 }
2037
2038 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
2043 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
2044 self
2045 }
2046
2047 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
2052 if let Some(node) = scale.node().live() {
2053 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
2054 self.node().attrs.rare_mut().bound.push(node);
2055 }
2056 self
2057 }
2058
2059 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
2063 if let Some(node) = angle.node().live() {
2064 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
2065 self.node().attrs.rare_mut().bound.push(node);
2066 }
2067 self
2068 }
2069
2070 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2072 self.on(
2073 EventKind::PanStart,
2074 events::typed(listener.into_listener(), events::pan),
2075 )
2076 }
2077
2078 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2080 self.on(
2081 EventKind::PanEnd,
2082 events::typed(listener.into_listener(), events::pan),
2083 )
2084 }
2085
2086 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2088 self.on(
2089 EventKind::PinchStart,
2090 events::typed(listener.into_listener(), events::pinch),
2091 )
2092 }
2093
2094 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2096 self.on(
2097 EventKind::PinchEnd,
2098 events::typed(listener.into_listener(), events::pinch),
2099 )
2100 }
2101
2102 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2104 self.on(
2105 EventKind::RotationStart,
2106 events::typed(listener.into_listener(), events::rotation),
2107 )
2108 }
2109
2110 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2112 self.on(
2113 EventKind::RotationEnd,
2114 events::typed(listener.into_listener(), events::rotation),
2115 )
2116 }
2117
2118 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
2120 self.on(
2121 EventKind::AccessibilityAction,
2122 events::typed(listener.into_listener(), events::action),
2123 )
2124 }
2125
2126 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
2129 self.node().handlers.push((kind, listener.into_listener()));
2130 self
2131 }
2132
2133 fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
2135 super::host::bind_prop(self.node(), insets, Prop::HitSlop);
2136 self
2137 }
2138
2139 #[doc(hidden)]
2143 fn __link_href(mut self, href: impl IntoReactive<Option<SharedString>>) -> Self {
2144 super::host::bind_prop(self.node(), href, |href: Option<SharedString>| {
2145 Prop::Href(href.map(|href| href.to_arc()))
2146 });
2147 self
2148 }
2149
2150 fn long_press_delay(mut self, ms: f32) -> Self {
2152 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
2153 self
2154 }
2155
2156 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
2158 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
2159 self
2160 }
2161
2162 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
2164 super::host::set(self.node(), Prop::Elevation(elevation.into()));
2165 self
2166 }
2167
2168 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
2170 super::host::set(self.node(), Prop::BackdropMaterial(material));
2171 self
2172 }
2173
2174 fn macos_backdrop(mut self, backdrop: impl IntoReactive<Option<crate::MacOsBackdrop>>) -> Self {
2177 super::host::bind_prop(self.node(), backdrop, Prop::MacOsBackdrop);
2178 self
2179 }
2180
2181 fn test_id(mut self, id: &str) -> Self {
2183 super::host::set(self.node(), Prop::TestId(Some(id.into())));
2184 self
2185 }
2186
2187 fn web_element(mut self, element: crate::WebElement) -> Self {
2193 super::host::set(self.node(), Prop::WebElement(Some(element)));
2194 self
2195 }
2196
2197 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
2205 super::host::bind_prop(self.node(), enabled, |enabled| {
2206 Prop::WindowDrag(Some(enabled))
2207 });
2208 self
2209 }
2210
2211 fn window_control(mut self, control: crate::desktop::WindowControl) -> Self {
2216 super::host::set(self.node(), Prop::WindowControl(Some(control)));
2217 self
2218 }
2219
2220 fn window_resize(mut self, edge: crate::desktop::ResizeEdge) -> Self {
2223 super::host::set(self.node(), Prop::WindowResize(Some(edge)));
2224 self
2225 }
2226
2227 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
2235 super::host::bind_prop(self.node(), focusable, |focusable| {
2236 Prop::Focusable(Some(focusable))
2237 });
2238 self
2239 }
2240
2241 fn native_id(mut self, id: &str) -> Self {
2244 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
2245 self
2246 }
2247
2248 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2250 let s = f(StyleRefinement::default());
2251 self.style().extend_as(Variant::ACTIVE, s);
2252 self
2253 }
2254
2255 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2257 let s = f(StyleRefinement::default());
2258 self.style().extend_as(Variant::HOVER, s);
2259 self
2260 }
2261
2262 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2264 let s = f(StyleRefinement::default());
2265 self.style().extend_as(Variant::FOCUS, s);
2266 self
2267 }
2268
2269 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2274 let s = f(StyleRefinement::default());
2275 self.style().extend_as(Variant::FOCUS_VISIBLE, s);
2276 self
2277 }
2278
2279 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2284 let s = f(StyleRefinement::default());
2285 self.style().extend_as(Variant::FOCUS_WITHIN, s);
2286 self
2287 }
2288
2289 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2291 let s = f(StyleRefinement::default());
2292 self.style().extend_as(Variant::DISABLED, s);
2293 self
2294 }
2295
2296 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2298 self.node().bind_attr(disabled, |a, disabled| {
2299 a.disabled = disabled;
2300 a.state.disabled = disabled;
2301 });
2302 self
2303 }
2304
2305 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
2308 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
2309 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
2310 });
2311 self
2312 }
2313
2314 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
2318 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
2319 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
2320 });
2321 self
2322 }
2323
2324 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
2328 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
2329 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
2330 });
2331 self
2332 }
2333
2334 fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
2338 Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
2339 super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
2340 });
2341 self
2342 }
2343
2344 fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
2348 Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
2349 super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
2350 });
2351 self
2352 }
2353
2354 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
2360 self.node().bind_attr(checked, |a, checked| {
2361 project(a, crate::tailwind::state::CHECKED, checked)
2362 });
2363 self
2364 }
2365
2366 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
2372 self.node().bind_attr(indeterminate, |a, indeterminate| {
2373 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
2374 });
2375 self
2376 }
2377
2378 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2383 self.node().bind_attr(disabled, |a, disabled| {
2384 project(a, crate::tailwind::state::DISABLED, disabled)
2385 });
2386 self
2387 }
2388
2389 fn project_hovered(mut self, hovered: impl IntoReactive<bool>) -> Self {
2395 self.node().bind_attr(hovered, |a, hovered| {
2396 project(a, crate::tailwind::state::HOVERED, hovered)
2397 });
2398 self
2399 }
2400
2401 fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
2410 self.node().bind_attr(focused, |a, focused| {
2411 project(a, crate::tailwind::state::FOCUSED, focused)
2412 });
2413 self
2414 }
2415
2416 fn project_group_active(mut self, group: &'static str) -> Self {
2426 self.node().bind_attr(true, move |a, _: bool| {
2427 a.rare_mut().projected_active = Some(group)
2428 });
2429 self
2430 }
2431
2432 fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
2441 self.node().bind_attr(on, move |a, on| {
2442 if !on && a.rare.is_none() {
2443 return;
2444 }
2445 let data = &mut a.rare_mut().projected_data;
2446 let at = data.binary_search(&name);
2447 match (at, on) {
2448 (Err(i), true) => data.insert(i, name),
2449 (Ok(i), false) => {
2450 data.remove(i);
2451 }
2452 _ => {}
2453 }
2454 });
2455 self
2456 }
2457}
2458
2459fn project(a: &mut Attrs, bit: u16, on: bool) {
2461 if on {
2462 a.rare_mut().projected_states |= bit;
2463 } else if let Some(r) = &mut a.rare {
2464 r.projected_states &= !bit;
2465 }
2466}
2467
2468macro_rules! element {
2469 ($(#[$doc:meta])* $name:ident) => {
2470 $(#[$doc])*
2471 #[derive(Clone)]
2472 pub struct $name(ElNode);
2473
2474 impl Element for $name {
2475 fn node(&mut self) -> &mut ElNode {
2476 &mut self.0
2477 }
2478 }
2479
2480 impl IntoElement for $name {
2481 fn into_element(self) -> AnyElement {
2482 AnyElement(self.0)
2483 }
2484 }
2485
2486 impl Accessible for $name {}
2487
2488 impl IntoTooltip for $name {
2489 fn apply_tooltip(self, node: &mut ElNode) {
2490 self.into_element().apply_tooltip(node);
2491 }
2492 }
2493 };
2494}
2495
2496element! {
2497 View
2499}
2500
2501element! {
2502 Text
2504}
2505
2506element! {
2507 Image
2509}
2510
2511element! {
2512 SlotElement
2515}
2516
2517element! {
2518 ListElement
2520}
2521
2522impl Interactive for View {}
2523impl ParentElement for View {}
2524
2525impl View {
2526 pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2540 let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2541 t.and_then(|t| t.target()).map(super::FollowTarget)
2542 });
2543 super::host::bind_prop(&mut self.0, target, Prop::Follow);
2544 self
2545 }
2546
2547 pub fn follow_transition(
2553 mut self,
2554 transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2555 ) -> Self {
2556 super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2557 self
2558 }
2559}
2560impl Interactive for SlotElement {}
2561impl Interactive for Text {}
2562impl Interactive for Image {}
2563
2564impl ParentElement for Text {
2569 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2570 let at = self.0.children.len();
2571 child.__push_into(&mut self.0.children);
2572 for el in &mut self.0.children[at..] {
2573 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2574 }
2575 self
2576 }
2577
2578 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2579 self.0
2580 .children
2581 .extend(children.into_iter().map(|c| span(c.into_element().0)));
2582 self
2583 }
2584}
2585
2586fn span(mut el: ElNode) -> ElNode {
2589 if el.tag == Tag::Text
2590 && matches!(el.kind, ElKind::Plain)
2591 && el.key.is_none()
2592 && el.children.is_empty()
2593 && el.handlers.is_empty()
2594 && el.style.is_empty()
2595 && el.attrs == Attrs::default()
2596 && !el.is_bound()
2597 {
2598 el.kind = ElKind::Raw;
2599 }
2600 el
2601}
2602
2603impl Text {
2604 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2606 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2607 Prop::SelectionColor(Some(Color::from(c)))
2608 });
2609 self
2610 }
2611
2612 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2614 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2615 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2616 self
2617 }
2618
2619 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2622 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2623 self
2624 }
2625
2626 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2629 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2630 self
2631 }
2632}
2633
2634impl Image {
2635 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2638 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2639 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2640 uri: src.uri.to_arc(),
2641 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2642 scales: src.scales,
2643 data: src.data,
2644 })))
2645 });
2646 self
2647 }
2648
2649 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2651 Styled::tint_color(self, color)
2652 }
2653
2654 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2656 super::host::set(
2657 &mut self.0,
2658 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2659 );
2660 self
2661 }
2662
2663 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2665 super::host::bind_prop(&mut self.0, ms, |ms| {
2666 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
2667 });
2668 self
2669 }
2670
2671 pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
2673 self.on(
2674 EventKind::Load,
2675 events::typed(listener.into_listener(), events::pixel_size),
2676 )
2677 }
2678
2679 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
2681 self.on(
2682 EventKind::Error,
2683 events::typed(listener.into_listener(), events::message),
2684 )
2685 }
2686
2687 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
2689 self.on(
2690 EventKind::LoadStart,
2691 events::typed(listener.into_listener(), events::unit),
2692 )
2693 }
2694
2695 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
2697 self.on(
2698 EventKind::LoadEnd,
2699 events::typed(listener.into_listener(), events::unit),
2700 )
2701 }
2702
2703 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
2706 self.on(
2707 EventKind::Progress,
2708 events::typed(listener.into_listener(), events::image_progress),
2709 )
2710 }
2711}
2712
2713impl super::Scrollable for ListElement {}
2714
2715impl super::ListLayout for ListElement {
2716 fn config(&mut self) -> &mut ListConfig {
2717 match &mut self.0.kind {
2718 ElKind::List(list) => &mut list.config,
2719 _ => unreachable!("a ListElement is a list"),
2720 }
2721 }
2722
2723 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
2724 &mut self.0.bound_list
2725 }
2726}
2727
2728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2731pub struct Slot {
2732 name: &'static str,
2733}
2734
2735impl Slot {
2736 pub(crate) fn new(name: &'static str) -> Self {
2737 Self { name }
2738 }
2739
2740 pub fn name(&self) -> &'static str {
2742 self.name
2743 }
2744
2745 pub fn element(self) -> SlotElement {
2747 let mut node = ElNode::new(Tag::View);
2748 node.kind = ElKind::Slot(self.name);
2749 SlotElement(node)
2750 }
2751}
2752
2753#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2757pub struct Items {
2758 name: &'static str,
2759}
2760
2761impl Items {
2762 #[doc(hidden)]
2763 pub const fn __new(name: &'static str) -> Self {
2764 Self { name }
2765 }
2766}
2767
2768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2772pub struct Child(ChildRef);
2773
2774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2775enum ChildRef {
2776 Js(NodeId),
2777 Row,
2778}
2779
2780impl Child {
2781 pub(crate) fn js(id: NodeId) -> Self {
2782 Self(ChildRef::Js(id))
2783 }
2784
2785 pub(crate) fn row() -> Self {
2786 Self(ChildRef::Row)
2787 }
2788}
2789
2790impl IntoElement for Child {
2791 fn into_element(self) -> AnyElement {
2792 let mut node = ElNode::new(Tag::View);
2793 node.kind = match self.0 {
2794 ChildRef::Js(id) => ElKind::JsChild(id),
2795 ChildRef::Row => ElKind::Children,
2796 };
2797 AnyElement(node)
2798 }
2799}
2800
2801pub fn view() -> View {
2803 View(ElNode::new(Tag::View))
2804}
2805
2806pub fn text(content: impl IntoReactive<SharedString>) -> Text {
2809 let mut node = ElNode::new(Tag::Text);
2810 match content.into_reactive() {
2811 Reactive::Static(content) => node.text = Some(content),
2812 Reactive::Bound(content) => {
2813 node.text = Some(SharedString::default());
2814 node.bound_text = Some(content);
2815 }
2816 }
2817 Text(node)
2818}
2819
2820pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
2824 let mut node = ElNode::new(Tag::Image);
2825 node.bind_attr(src, |a, src| a.rare_mut().src = Some(src));
2826 Image(node)
2827}
2828
2829#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2832pub struct Children {
2833 present: bool,
2834}
2835
2836impl Children {
2837 pub(crate) fn new(present: bool) -> Self {
2838 Self { present }
2839 }
2840
2841 pub fn is_empty(&self) -> bool {
2843 !self.present
2844 }
2845}
2846
2847impl IntoElement for Children {
2848 fn into_element(self) -> AnyElement {
2849 let mut node = ElNode::new(Tag::View);
2850 node.kind = ElKind::Children;
2851 AnyElement(node)
2852 }
2853}
2854
2855pub struct ComponentElement<C: Component> {
2868 node: ElNode,
2869 _component: PhantomData<fn() -> C>,
2870}
2871
2872impl<C: Component> ComponentElement<C> {
2873 #[doc(hidden)]
2876 pub fn __new(props: C::Props) -> Self {
2877 Self::new(props)
2878 }
2879
2880 #[doc(hidden)]
2882 pub fn __props_mut(&mut self) -> &mut C::Props {
2883 match &mut self.node.kind {
2884 ElKind::Component(c) => c
2885 .props
2886 .as_any_mut()
2887 .downcast_mut::<C::Props>()
2888 .expect("a component element holds its component's props"),
2889 _ => unreachable!("a component element is a component's"),
2890 }
2891 }
2892
2893 pub(crate) fn new(props: C::Props) -> Self {
2894 let mut node = ElNode::new(Tag::View);
2895 node.kind = ElKind::Component(ComponentEl {
2896 name: super::component::name_of::<C>(),
2897 make: super::component::make_instance::<C>,
2898 spec: ComponentSpec::of::<C>,
2899 props: Box::new(props),
2900 on_event: Vec::new(),
2901 });
2902 Self {
2903 node,
2904 _component: PhantomData,
2905 }
2906 }
2907
2908 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
2913 self.node
2914 .children
2915 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
2916 let mut fill = ElNode::new(Tag::View);
2917 fill.kind = ElKind::Fill(slot);
2918 fill.children.push(content.into_element().0);
2919 self.node.children.push(fill);
2920 self
2921 }
2922
2923 pub fn items(mut self, list: super::VirtualList) -> Self {
2931 match <C::Props as super::Props>::ITEMS {
2932 Some(name) => self.node.children.push(list.into_items(name)),
2933 None => {
2934 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
2935 }
2936 }
2937 self
2938 }
2939
2940 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2945 let s = f(StyleRefinement::default());
2946 self.node.style.extend_as(Variant::ACTIVE, s);
2947 self
2948 }
2949
2950 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2952 let s = f(StyleRefinement::default());
2953 self.node.style.extend_as(Variant::HOVER, s);
2954 self
2955 }
2956
2957 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2959 let s = f(StyleRefinement::default());
2960 self.node.style.extend_as(Variant::FOCUS, s);
2961 self
2962 }
2963
2964 pub fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2967 let s = f(StyleRefinement::default());
2968 self.node.style.extend_as(Variant::FOCUS_VISIBLE, s);
2969 self
2970 }
2971
2972 pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2975 let s = f(StyleRefinement::default());
2976 self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
2977 self
2978 }
2979
2980 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2983 let s = f(StyleRefinement::default());
2984 self.node.style.extend_as(Variant::DISABLED, s);
2985 self
2986 }
2987
2988 pub fn test_id(mut self, id: &str) -> Self {
2991 super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
2992 self
2993 }
2994
2995 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
2997 self.node.attrs.set_element_ref(handle.element().target());
2998 self
2999 }
3000
3001 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
3007 let listener = listener.into_listener();
3008 if let ElKind::Component(c) = &mut self.node.kind {
3009 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
3010 if let Some(event) = event.downcast_ref::<C::Event>() {
3011 inner(event);
3012 }
3013 }));
3014 }
3015 self
3016 }
3017
3018 #[doc(hidden)]
3022 pub fn __on_variant<T: ?Sized + 'static, M>(
3023 self,
3024 pick: fn(&C::Event) -> Option<&T>,
3025 listener: impl IntoListener<T, M>,
3026 ) -> Self {
3027 let listener = listener.into_listener();
3028 self.on_event(listener.wrap(move |inner, event: &C::Event| {
3029 if let Some(data) = pick(event) {
3030 inner(data);
3031 }
3032 }))
3033 }
3034}
3035
3036pub trait ComponentBuilder: Element {
3108 type Component: Component;
3110
3111 #[doc(hidden)]
3113 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
3114
3115 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3120 let s = f(StyleRefinement::default());
3121 self.node().style.extend_as(Variant::ACTIVE, s);
3122 self
3123 }
3124
3125 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3127 let s = f(StyleRefinement::default());
3128 self.node().style.extend_as(Variant::HOVER, s);
3129 self
3130 }
3131
3132 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3134 let s = f(StyleRefinement::default());
3135 self.node().style.extend_as(Variant::FOCUS, s);
3136 self
3137 }
3138
3139 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3142 let s = f(StyleRefinement::default());
3143 self.node().style.extend_as(Variant::FOCUS_VISIBLE, s);
3144 self
3145 }
3146
3147 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3150 let s = f(StyleRefinement::default());
3151 self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
3152 self
3153 }
3154
3155 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3158 let s = f(StyleRefinement::default());
3159 self.node().style.extend_as(Variant::DISABLED, s);
3160 self
3161 }
3162
3163 #[doc(hidden)]
3166 fn __listen(mut self, kind: EventKind, listener: Listener<EventPayload>) -> Self {
3167 self.node().handlers.push((kind, listener));
3168 self
3169 }
3170
3171 fn test_id(mut self, id: &str) -> Self {
3174 super::host::set(self.node(), Prop::TestId(Some(id.into())));
3175 self
3176 }
3177
3178 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
3182 let listener = events::typed(listener.into_listener(), events::layout);
3183 self.__listen(EventKind::Layout, listener)
3184 }
3185
3186 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3190 let listener = events::typed(listener.into_listener(), events::mouse);
3191 self.__listen(EventKind::MouseEnter, listener)
3192 }
3193
3194 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3197 let listener = events::typed(listener.into_listener(), events::mouse);
3198 self.__listen(EventKind::MouseLeave, listener)
3199 }
3200
3201 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3205 let listener = events::typed(listener.into_listener(), events::mouse);
3206 self.__listen(EventKind::MouseMove, listener)
3207 }
3208
3209 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3212 let listener = events::typed(listener.into_listener(), events::mouse);
3213 self.__listen(EventKind::MouseUp, listener)
3214 }
3215
3216 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
3221 let listener = events::typed(listener.into_listener(), events::context_menu);
3222 self.__listen(EventKind::ContextMenu, listener)
3223 }
3224
3225 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
3228 let listener = events::typed(listener.into_listener(), events::file_drag);
3229 self.__listen(EventKind::FileDragEnter, listener)
3230 }
3231
3232 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
3235 let listener = events::typed(listener.into_listener(), events::unit);
3236 self.__listen(EventKind::FileDragLeave, listener)
3237 }
3238
3239 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
3242 let listener = events::typed(listener.into_listener(), events::file_drop);
3243 self.__listen(EventKind::FileDrop, listener)
3244 }
3245
3246 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
3248 self.__element()
3249 .node
3250 .attrs
3251 .set_element_ref(handle.element().target());
3252 self
3253 }
3254}
3255
3256impl<C: Component> Element for ComponentElement<C> {
3257 fn node(&mut self) -> &mut ElNode {
3258 &mut self.node
3259 }
3260}
3261
3262impl<C: Component> ParentElement for ComponentElement<C> {}
3266
3267impl<C: Component> IntoElement for ComponentElement<C> {
3268 fn into_element(self) -> AnyElement {
3269 AnyElement(self.node)
3270 }
3271}
3272
3273#[cfg(test)]
3274mod file_listener_tests {
3275 use std::cell::Cell;
3276
3277 use super::*;
3278
3279 #[test]
3280 fn file_drag_enter_keeps_all_original_listener_forms() {
3281 let calls = Rc::new(Cell::new(0));
3282 let a = calls.clone();
3283 let b = calls.clone();
3284 let c = calls.clone();
3285 let d = calls.clone();
3286 let unit: Listener<()> = (move |_: &()| c.set(c.get() + 1)).into_listener();
3287 let nodes = [
3288 view().on_file_drag_enter(move || a.set(a.get() + 1)),
3289 view().on_file_drag_enter(move |_: &()| b.set(b.get() + 1)),
3290 view().on_file_drag_enter(unit),
3291 view().on_file_drag_enter(move |e: &events::FileDragEvent| {
3292 assert_eq!(e.uris, ["file:///tmp/a%20b.png"]);
3293 assert_eq!(e.mime_types, ["image/png"]);
3294 d.set(d.get() + 1);
3295 }),
3296 ];
3297 let payload = EventPayload::FileDrop(vec!["file:///tmp/a%20b.png".into()]);
3298 for mut node in nodes {
3299 let listener = node
3300 .node()
3301 .handlers
3302 .iter()
3303 .find(|(kind, _)| *kind == EventKind::FileDragEnter)
3304 .unwrap();
3305 listener.1.call(&payload);
3306 }
3307 assert_eq!(calls.get(), 4);
3308 }
3309}