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, LiveRegion, MouseEvent, NativeProp, NodeId, PanActivation, PinchEvent,
16 PointerEvents, Points, PressEvent, Prop, Size, Tag, TouchEvent, WheelEvent,
17 geometry::{Axis, 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 pub(crate) window_commands: Vec<crate::desktop::DesktopCommand>,
255}
256
257impl RareAttrs {
258 pub(crate) fn is_empty(&self) -> bool {
259 self.accessible.is_none()
260 && self.hint.is_none()
261 && self.description.is_none()
262 && self.value.is_none()
263 && self.src.is_none()
264 && self.inset_padding.is_none()
265 && self.inset_margin.is_none()
266 && self.drawing.is_none()
267 && self.element_ref.is_none()
268 && self.animated.is_empty()
269 && self.bound.is_empty()
270 && !self.selectable_view
271 && !self.continues_text
272 && self.projected_states == 0
273 && self.projected_data.is_empty()
274 && self.projected_active.is_none()
275 && self.render.is_none()
276 && self.window.is_none()
277 }
278
279 pub(crate) fn boxed(self) -> Option<Box<Self>> {
280 (!self.is_empty()).then(|| Box::new(self))
281 }
282}
283
284#[doc(hidden)]
286#[derive(Debug, Clone, Default)]
287pub struct Attrs {
288 pub(crate) disabled: bool,
289 pub(crate) role: AccessibilityRole,
290 pub(crate) state: AccessibilityState,
291 pub(crate) pointer_events: PointerEvents,
293 pub(crate) label: Option<SharedString>,
294 pub(crate) inline: Option<std::rc::Rc<crate::StylePatch>>,
296 pub(crate) class: Option<SharedString>,
299 pub(crate) props: Vec<Prop>,
302 pub(crate) rare: Option<Box<RareAttrs>>,
303}
304
305impl PartialEq for Attrs {
306 fn eq(&self, other: &Self) -> bool {
307 self.disabled == other.disabled
308 && self.role == other.role
309 && self.state == other.state
310 && self.pointer_events == other.pointer_events
311 && self.label == other.label
312 && self.inline == other.inline
313 && self.class == other.class
314 && self.props == other.props
315 && match (&self.rare, &other.rare) {
316 (None, None) => true,
317 (Some(a), None) => a.is_empty(),
318 (None, Some(b)) => b.is_empty(),
319 (Some(a), Some(b)) => a == b,
320 }
321 }
322}
323
324impl Attrs {
325 #[inline]
326 pub(crate) fn rare_mut(&mut self) -> &mut RareAttrs {
327 self.rare.get_or_insert_with(Box::default)
328 }
329
330 #[inline]
331 pub(crate) fn animated(&self) -> &[(crate::StyleDecl, super::LiveNode)] {
332 self.rare.as_deref().map_or(&[], |r| r.animated.as_slice())
333 }
334
335 #[cfg(test)]
336 #[inline]
337 pub(crate) fn bound(&self) -> &[super::LiveNode] {
338 self.rare.as_deref().map_or(&[], |r| r.bound.as_slice())
339 }
340
341 #[inline]
342 pub(crate) fn element_ref(&self) -> Option<&super::element_ref::RefTarget> {
343 self.rare.as_ref().and_then(|r| r.element_ref.as_ref())
344 }
345
346 #[inline]
347 pub(crate) fn set_element_ref(&mut self, target: Option<super::element_ref::RefTarget>) {
348 if target.is_some() || self.rare.is_some() {
349 self.rare_mut().element_ref = target;
350 }
351 }
352
353 #[inline]
354 pub(crate) fn take_element_ref(&mut self) -> Option<super::element_ref::RefTarget> {
355 self.rare.as_mut().and_then(|r| r.element_ref.take())
356 }
357
358 #[inline]
359 pub(crate) fn insets(&self) -> (Option<EdgeInsets>, Option<EdgeInsets>) {
360 match &self.rare {
361 Some(r) => (r.inset_padding, r.inset_margin),
362 None => (None, None),
363 }
364 }
365
366 #[inline]
367 pub(crate) fn set_insets(&mut self, insets: (Option<EdgeInsets>, Option<EdgeInsets>)) {
368 if insets != (None, None) || self.rare.is_some() {
369 let r = self.rare_mut();
370 r.inset_padding = insets.0;
371 r.inset_margin = insets.1;
372 }
373 }
374
375 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
377 use AccessibilityProp as A;
378 if self.disabled != old.disabled {
379 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
380 }
381 let check_rare = self.rare.is_some() || old.rare.is_some();
382 let default_rare;
383 let (sr, or) = if check_rare {
384 default_rare = RareAttrs::default();
385 (
386 self.rare.as_deref().unwrap_or(&default_rare),
387 old.rare.as_deref().unwrap_or(&default_rare),
388 )
389 } else {
390 default_rare = RareAttrs::default();
391 (&default_rare, &default_rare)
392 };
393 if check_rare && sr.accessible != or.accessible {
394 out.push(Prop::Accessibility(A::Accessible(sr.accessible)));
395 }
396 if self.label != old.label {
397 out.push(Prop::Accessibility(A::Label(
398 self.label.as_ref().map(SharedString::to_arc),
399 )));
400 }
401 if check_rare && sr.hint != or.hint {
402 out.push(Prop::Accessibility(A::Hint(
403 sr.hint.as_ref().map(SharedString::to_arc),
404 )));
405 }
406 if check_rare && sr.description != or.description {
407 out.push(Prop::Accessibility(A::Description(
408 sr.description.as_ref().map(SharedString::to_arc),
409 )));
410 }
411 if self.role != old.role {
412 out.push(Prop::Accessibility(A::Role(self.role)));
413 }
414 if self.state != old.state {
415 out.push(Prop::Accessibility(A::State(self.state)));
416 }
417 if check_rare && sr.value != or.value {
418 out.push(Prop::Accessibility(A::Value(sr.value.clone())));
419 }
420 if self.pointer_events != old.pointer_events {
421 out.push(Prop::PointerEvents(self.pointer_events));
422 }
423 if check_rare {
424 if sr.src != or.src {
425 out.push(Prop::Source(sr.src.as_ref().map(|src| ImageSource {
426 uri: src.uri.to_arc(),
427 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
428 scales: src.scales,
429 data: src.data.clone(),
430 })));
431 }
432 if sr.inset_padding != or.inset_padding {
433 out.push(Prop::InsetPadding(sr.inset_padding.unwrap_or_default()));
434 }
435 if sr.inset_margin != or.inset_margin {
436 out.push(Prop::InsetMargin(sr.inset_margin.unwrap_or_default()));
437 }
438 if sr.selectable_view != or.selectable_view {
439 out.push(Prop::SelectableView(sr.selectable_view));
440 }
441 if sr.continues_text != or.continues_text {
442 out.push(Prop::ContinuesText(sr.continues_text));
443 }
444 if sr.projected_states != or.projected_states {
445 out.push(Prop::ProjectedStates(sr.projected_states));
446 }
447 if sr.projected_data != or.projected_data {
448 out.push(Prop::ProjectedData(sr.projected_data.as_slice().into()));
449 }
450 if sr.projected_active != or.projected_active {
451 out.push(Prop::ProjectedActive(sr.projected_active));
452 }
453 }
454 for prop in &old.props {
457 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
458 && let Some(reset) = super::host::reset(prop)
459 {
460 out.push(reset);
461 }
462 }
463 for prop in &self.props {
464 if !old.props.contains(prop) {
465 out.push(prop.clone());
466 }
467 }
468 }
469}
470
471pub(crate) trait AnyProps {
473 fn as_any(&self) -> &dyn Any;
474 fn as_any_mut(&mut self) -> &mut dyn Any;
475 fn clone_box(&self) -> Box<dyn AnyProps>;
476}
477
478impl<P: Clone + 'static> AnyProps for P {
479 fn as_any(&self) -> &dyn Any {
480 self
481 }
482
483 fn as_any_mut(&mut self) -> &mut dyn Any {
484 self
485 }
486
487 fn clone_box(&self) -> Box<dyn AnyProps> {
488 Box::new(self.clone())
489 }
490}
491
492pub(crate) struct ComponentEl {
494 pub(crate) name: &'static str,
495 pub(crate) make: fn() -> Box<dyn AnyInstance>,
498 pub(crate) spec: fn() -> ComponentSpec,
500 pub(crate) props: Box<dyn AnyProps>,
501 pub(crate) on_event: Vec<Listener<dyn Any>>,
503 pub(crate) by_name: Option<std::any::TypeId>,
507}
508
509impl Clone for ComponentEl {
510 fn clone(&self) -> Self {
511 Self {
512 name: self.name,
513 make: self.make,
514 spec: self.spec,
515 props: self.props.clone_box(),
516 on_event: self.on_event.clone(),
517 by_name: self.by_name,
518 }
519 }
520}
521
522pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
524
525#[derive(Clone, Copy)]
531pub struct Position {
532 index: super::reactive::Node,
533 count: super::reactive::Node,
534 rows: Option<super::reactive::Node>,
539}
540
541impl Position {
542 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
545 Self {
546 index,
547 count,
548 rows: None,
549 }
550 }
551
552 pub(crate) fn of_row(
555 index: super::reactive::Node,
556 count: super::reactive::Node,
557 rows: Option<super::reactive::Node>,
558 ) -> Self {
559 Self { index, count, rows }
560 }
561
562 pub(crate) fn fixed(index: usize, count: usize) -> Self {
564 Self::of(super::signal(index).node(), super::signal(count).node())
565 }
566
567 #[track_caller]
569 pub fn index(&self) -> usize {
570 if let Some(rows) = self.rows
571 && rows.is_outdated()
572 {
573 let before = self.index.with_untracked("a position", |i: &usize| *i);
574 rows.bring_up_to_date();
575 if !self.index.is_live() {
579 return before;
580 }
581 }
582 self.index.with("a position", |i: &usize| *i)
583 }
584
585 #[track_caller]
587 pub fn count(&self) -> usize {
588 if let Some(rows) = self.rows {
589 rows.bring_up_to_date();
590 }
591 self.count.with("a position", |n: &usize| *n)
592 }
593
594 #[track_caller]
596 pub fn is_first(&self) -> bool {
597 self.index() == 0
598 }
599
600 #[track_caller]
602 pub fn is_last(&self) -> bool {
603 self.index() + 1 == self.count()
604 }
605}
606
607impl fmt::Debug for Position {
608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 let (index, count) = super::untracked(|| (self.index(), self.count()));
610 write!(f, "Position({index} of {count})")
611 }
612}
613
614#[doc(hidden)]
617#[derive(Debug, Clone, Copy, Default, PartialEq)]
618pub struct ListConfig {
619 pub(crate) estimated: Option<f32>,
620 pub(crate) columns: Option<u32>,
621 pub(crate) horizontal: Option<bool>,
622 pub(crate) inverted: Option<bool>,
623 pub(crate) scrollbar_visible: Option<bool>,
624 pub(crate) content: Option<ListContentStyle>,
625 pub(crate) follow_end: Option<f32>,
626 pub(crate) alignment: Option<crate::ListAlignment>,
627 pub(crate) viewport: Option<crate::ListViewport>,
628}
629
630impl ListConfig {
631 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
633 if self.estimated != old.estimated {
634 out.push(Prop::EstimatedItemSize(Points(
635 self.estimated.unwrap_or(50.0),
636 )));
637 }
638 if self.columns != old.columns {
639 out.push(Prop::Columns(self.columns.unwrap_or(1)));
640 }
641 if self.horizontal != old.horizontal {
642 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
643 }
644 if self.inverted != old.inverted {
645 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
646 }
647 if self.scrollbar_visible != old.scrollbar_visible {
648 out.push(Prop::Scrollbar(
649 self.scrollbar_visible.unwrap_or(true).into(),
650 ));
651 }
652 if self.content != old.content {
653 out.push(Prop::ListContent(self.content.unwrap_or_default()));
654 }
655 if self.follow_end != old.follow_end {
656 out.push(Prop::FollowEnd(self.follow_end.map(Points)));
657 }
658 if self.alignment != old.alignment {
659 out.push(Prop::ListAlignment(self.alignment.unwrap_or_default()));
660 }
661 if self.viewport != old.viewport {
662 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
663 }
664 }
665}
666
667#[derive(Clone)]
669pub(crate) struct ListEl {
670 pub(crate) name: &'static str,
671 pub(crate) config: ListConfig,
672 pub(crate) row: PlaceFn,
673}
674
675#[derive(Clone)]
677pub(crate) enum ElKind {
678 Plain,
679 Slot(&'static str),
681 Fill(&'static str),
684 Filled(&'static str),
687 Children,
689 JsChild(NodeId),
691 EachChild(PlaceFn),
693 List(Box<ListEl>),
695 VirtualList(Box<super::virtual_list::VirtualListEl>),
697 Raw,
700 Component(ComponentEl),
701 Region(super::flow::Region),
705}
706
707#[doc(hidden)]
709#[derive(Clone)]
710pub struct ElNode {
711 pub(crate) tag: Tag,
712 pub(crate) key: Option<SharedString>,
713 pub(crate) text: Option<SharedString>,
715 pub(crate) attrs: Attrs,
716 pub(crate) style: StyleRefinement,
717 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
718 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
720 pub(crate) children: Vec<ElNode>,
721 pub(crate) kind: ElKind,
722 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
724 pub(crate) bound_attrs: Vec<BoundAttrs>,
726 pub(crate) bound_list: Vec<BoundListConfig>,
728}
729
730#[doc(hidden)]
732pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
733
734crate::static_reactive!(AccessibilityState: AccessibilityState);
735crate::static_reactive!(EdgeInsets: EdgeInsets);
736crate::static_reactive!(Style: Style);
737crate::static_reactive!(PointerEvents: PointerEvents);
738crate::static_reactive!(KeyCapture: KeyCapture);
739
740pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
742
743impl ElNode {
744 pub(crate) fn bind_attr<T: 'static>(
747 &mut self,
748 value: impl IntoReactive<T>,
749 apply: impl Fn(&mut Attrs, T) + 'static,
750 ) {
751 match value.into_reactive() {
752 Reactive::Static(v) => apply(&mut self.attrs, v),
753 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
754 }
755 }
756
757 pub(crate) fn is_bound(&self) -> bool {
759 self.bound_text.is_some()
760 || !self.bound_attrs.is_empty()
761 || self.style.is_bound()
762 || !self.bound_list.is_empty()
763 }
764
765 pub(crate) fn resolved_attrs(&self) -> Attrs {
768 let mut attrs = self.attrs.clone();
769 for part in &self.bound_attrs {
770 part(&mut attrs);
771 }
772 attrs
773 }
774
775 pub(crate) fn resolve_once(&mut self) {
778 if !self.is_bound() {
779 return;
780 }
781 super::untracked(|| {
782 if let Some(text) = self.bound_text.take() {
783 self.text = Some(text());
784 }
785 if !self.bound_attrs.is_empty() {
786 self.attrs = self.resolved_attrs();
787 self.bound_attrs.clear();
788 }
789 if self.style.is_bound() {
790 self.style = self.style.resolved();
791 }
792 let parts = std::mem::take(&mut self.bound_list);
793 if let Some(config) = self.list_config() {
794 for part in &parts {
795 part(config);
796 }
797 }
798 });
799 }
800
801 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
803 match &mut self.kind {
804 ElKind::List(list) => Some(&mut list.config),
805 ElKind::VirtualList(list) => Some(&mut list.config),
806 _ => None,
807 }
808 }
809
810 pub(crate) fn empty_view() -> Self {
812 Self::new(Tag::View)
813 }
814
815 pub(crate) fn new(tag: Tag) -> Self {
816 Self {
817 tag,
818 key: None,
819 text: None,
820 attrs: Attrs::default(),
821 style: StyleRefinement::default(),
822 handlers: Vec::new(),
823 responder: None,
824 children: Vec::new(),
825 kind: ElKind::Plain,
826 bound_text: None,
827 bound_attrs: Vec::new(),
828 bound_list: Vec::new(),
829 }
830 }
831}
832
833pub struct AnyElement(pub(crate) ElNode);
835
836pub trait IntoElement {
838 fn into_element(self) -> AnyElement;
840}
841
842impl IntoElement for AnyElement {
843 fn into_element(self) -> AnyElement {
844 self
845 }
846}
847
848impl IntoElement for SharedString {
849 fn into_element(self) -> AnyElement {
850 text(self).into_element()
851 }
852}
853
854impl IntoElement for &'static str {
855 fn into_element(self) -> AnyElement {
856 text(self).into_element()
857 }
858}
859
860impl IntoElement for String {
861 fn into_element(self) -> AnyElement {
862 text(self).into_element()
863 }
864}
865
866#[diagnostic::on_unimplemented(
872 message = "`{Self}` is not an element",
873 label = "not an element",
874 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
875)]
876pub trait IntoChild<M> {
877 #[doc(hidden)]
879 fn __push_into(self, out: &mut Vec<ElNode>);
880}
881
882#[doc(hidden)]
884pub struct OneChild(());
885
886#[doc(hidden)]
888pub struct ManyChildren(());
889
890impl<T: IntoElement> IntoChild<OneChild> for T {
891 fn __push_into(self, out: &mut Vec<ElNode>) {
892 out.push(self.into_element().0);
893 }
894}
895
896impl<I: IntoIterator> IntoChild<ManyChildren> for I
897where
898 I::Item: IntoElement,
899{
900 fn __push_into(self, out: &mut Vec<ElNode>) {
901 out.extend(self.into_iter().map(|c| c.into_element().0));
902 }
903}
904
905pub trait FluentBuilder: Sized {
909 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
911 if condition { then(self) } else { self }
912 }
913
914 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
916 match option {
917 Some(v) => then(self, v),
918 None => self,
919 }
920 }
921
922 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
924 f(self)
925 }
926}
927
928impl<T: Element> FluentBuilder for T {}
929
930pub trait Element: IntoElement + Sized {
934 #[doc(hidden)]
935 fn node(&mut self) -> &mut ElNode;
936
937 fn key(mut self, key: impl Into<SharedString>) -> Self {
940 self.node().key = Some(key.into());
941 self
942 }
943
944 fn bind_opacity(self, value: &impl super::Animated) -> Self {
946 self.bind(crate::animation::AnimationProp::Opacity, value)
947 }
948
949 fn bind_background(self, value: &impl super::Animated) -> Self {
952 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
953 }
954
955 fn bind_border_color(self, value: &impl super::Animated) -> Self {
957 self.bind(crate::animation::AnimationProp::BorderColor, value)
958 }
959
960 fn bind_color(self, value: &impl super::Animated) -> Self {
962 self.bind(crate::animation::AnimationProp::Color, value)
963 }
964
965 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
968 if let Some(node) = value.animated_node().live() {
969 let decl = crate::StyleDecl::Animated(prop, node.id());
970 self.node().attrs.rare_mut().animated.push((decl, node));
971 }
972 self
973 }
974
975 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
980 self.bind(crate::animation::AnimationProp::StickyTop, value)
981 }
982
983 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
985 self.bind(crate::animation::AnimationProp::StickyLeft, value)
986 }
987
988 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
991 if let Some(node) = value.animated_node().live() {
992 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
993 self.node().attrs.rare_mut().animated.push((decl, node));
994 }
995 self
996 }
997
998 fn bind_motion(self, motion: &super::Motion) -> Self {
1002 use crate::animation::MotionChannel::*;
1003 let mut this = self.bind_opacity(&motion.value(Opacity));
1004 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
1005 if let Some(kind) = channel.transform() {
1006 this = this.bind_transform(kind, &motion.value(channel));
1007 }
1008 }
1009 let scale = motion.value(Scale);
1010 this.bind_transform(
1011 crate::TransformKind::ScaleX,
1012 &scale.mul(&motion.value(ScaleX)),
1013 )
1014 .bind_transform(
1015 crate::TransformKind::ScaleY,
1016 &scale.mul(&motion.value(ScaleY)),
1017 )
1018 }
1019
1020 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
1022 self.bind_transform(crate::TransformKind::TranslateX, value)
1023 }
1024
1025 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
1027 self.bind_transform(crate::TransformKind::TranslateY, value)
1028 }
1029
1030 fn bind_scale(self, value: &impl super::Animated) -> Self {
1032 self.bind_transform(crate::TransformKind::Scale, value)
1033 }
1034
1035 fn bind_rotate(self, value: &impl super::Animated) -> Self {
1037 self.bind_transform(crate::TransformKind::Rotate, value)
1038 }
1039
1040 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
1043 self.node().attrs.set_element_ref(handle.target());
1044 self
1045 }
1046
1047 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1050 self.node().bind_attr(insets, |a, insets| {
1051 a.rare_mut().inset_padding = Some(insets)
1052 });
1053 self
1054 }
1055
1056 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1058 self.node()
1059 .bind_attr(insets, |a, insets| a.rare_mut().inset_margin = Some(insets));
1060 self
1061 }
1062
1063 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
1066 Style::apply(self.node(), style, Variant::default(), |a, patch| {
1067 a.inline = patch
1068 });
1069 self
1070 }
1071
1072 fn state_inline_style(mut self, style: impl Fn() -> Style + 'static) -> Self {
1077 Style::apply_bound(
1078 self.node(),
1079 Rc::new(style),
1080 Variant::default(),
1081 true,
1082 |a, patch| a.inline = patch,
1083 );
1084 self
1085 }
1086
1087 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
1092 self.node().bind_attr(area, |a, area| {
1093 if area || a.rare.is_some() {
1094 a.rare_mut().selectable_view = area;
1095 }
1096 });
1097 self
1098 }
1099
1100 fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
1107 super::host::bind_prop(self.node(), color, |c: Hsla| {
1108 Prop::SelectionColor(Some(Color::from(c)))
1109 });
1110 self
1111 }
1112
1113 fn selection_menu(mut self, items: impl IntoReactive<Vec<super::desktop::MenuItem>>) -> Self {
1134 super::host::bind_prop(self.node(), items, |items| {
1135 Prop::SelectionMenu(super::desktop::register_selection_menu(items))
1136 });
1137 self
1138 }
1139
1140 fn continues_text(mut self, continues: impl IntoReactive<bool>) -> Self {
1148 self.node().bind_attr(continues, |a, continues| {
1149 if continues || a.rare.is_some() {
1150 a.rare_mut().continues_text = continues;
1151 }
1152 });
1153 self
1154 }
1155
1156 fn copy_text(mut self, text: impl IntoReactive<SharedString>) -> Self {
1171 super::host::bind_prop(self.node(), text, |text: SharedString| {
1172 Prop::CopyText(Some(text.to_arc()))
1173 });
1174 self
1175 }
1176
1177 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
1182 self.node().bind_attr(class, |a, class| a.class = class);
1183 self
1184 }
1185}
1186
1187#[derive(Debug, Clone, Default, PartialEq)]
1201pub struct Style(
1202 pub(crate) Option<std::rc::Rc<crate::StylePatch>>,
1203 pub(crate) StyleRefinement,
1206);
1207
1208impl Style {
1209 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
1213 let mut style = crate::Style::default();
1214 let mut patch = crate::StylePatch::default();
1215 for decl in decls {
1216 let key = match &decl {
1217 crate::StyleDecl::Set(key, _) => Some(*key),
1218 _ => None,
1219 };
1220 if patch.push(&mut style, decl).is_err()
1221 && let Some(key) = key
1222 {
1223 log::warn!("invalid value for style `{}`", key.name());
1224 }
1225 }
1226 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1227 }
1228
1229 pub fn with(self, key: crate::StyleKey, value: crate::PropertyValue) -> Self {
1232 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
1233 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
1234 style.1 = self.1;
1235 style
1236 }
1237
1238 pub fn then(&self, over: &Style) -> Self {
1242 if over.0.is_none() && over.1.is_empty() {
1243 return self.clone();
1244 }
1245 if self.0.is_none() && self.1.is_empty() {
1246 return over.clone();
1247 }
1248 let mut style = if self.0.is_none() {
1249 Self(over.0.clone(), StyleRefinement::default())
1250 } else if over.0.is_none() {
1251 Self(self.0.clone(), StyleRefinement::default())
1252 } else {
1253 Self::from_decls(self.decls().iter().chain(over.decls()).cloned())
1254 };
1255 let mut typed = self.1.clone();
1256 typed.extend_as(Variant::default(), over.1.clone());
1257 style.1 = typed;
1258 style
1259 }
1260
1261 pub fn background_color(&self) -> Option<crate::element::AdaptiveColor> {
1267 let typed = self.1.static_color(crate::StyleKey::BackgroundColor);
1268 let declared = || {
1269 self.decls().iter().rev().find_map(|decl| match decl {
1270 crate::StyleDecl::Set(
1271 crate::StyleKey::BackgroundColor,
1272 crate::PropertyValue::Color(color),
1273 ) => Some(color.map(crate::element::AdaptiveColor::from)),
1274 _ => None,
1275 })?
1276 };
1277 typed
1278 .or_else(declared)
1279 .filter(|c| *c != crate::element::AdaptiveColor::from(crate::Color::TRANSPARENT))
1280 }
1281
1282 pub fn decls(&self) -> &[crate::StyleDecl] {
1284 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
1285 }
1286
1287 pub(crate) fn apply(
1293 node: &mut ElNode,
1294 style: impl IntoReactive<Style>,
1295 variant: Variant,
1296 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1297 ) {
1298 match style.into_reactive() {
1299 Reactive::Static(Style(patch, typed)) => {
1300 attr(&mut node.attrs, patch);
1301 if !typed.is_empty() {
1302 node.style.extend_as(variant, typed);
1303 }
1304 }
1305 Reactive::Bound(f) => Self::apply_bound(node, f, variant, false, attr),
1306 }
1307 }
1308
1309 pub(crate) fn apply_bound(
1312 node: &mut ElNode,
1313 f: Rc<dyn Fn() -> Style>,
1314 variant: Variant,
1315 typed_later: bool,
1316 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1317 ) {
1318 let typed = typed_later || super::untracked(|| !f().1.is_empty());
1319 let patch = f.clone();
1320 node.bind_attr(move || patch().0, attr);
1321 if typed {
1322 node.style
1325 .bind(move |s| s.extend_as(variant, f().1.resolved()));
1326 }
1327 }
1328}
1329
1330impl From<crate::StylePatch> for Style {
1331 fn from(patch: crate::StylePatch) -> Self {
1332 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1333 }
1334}
1335
1336impl From<StyleRefinement> for Style {
1337 fn from(style: StyleRefinement) -> Self {
1338 Self(None, style)
1339 }
1340}
1341
1342impl JsValue for Style {
1343 fn ts_type(_types: &mut super::TsTypes) -> String {
1344 "StyleProp<ViewStyle>".into()
1345 }
1346
1347 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1350 if value.is_nullish() {
1351 return Ok(Self::default());
1352 }
1353 Ok(Self::from(value.host().style(value.raw())?))
1354 }
1355
1356 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1358 Err(PropError("a style does not convert back to JS".to_owned()))
1359 }
1360}
1361
1362#[derive(Debug, Clone, Default, PartialEq)]
1370#[non_exhaustive]
1371pub struct TextPartStyle(pub Style);
1372
1373impl From<Style> for TextPartStyle {
1374 fn from(style: Style) -> Self {
1375 Self(style)
1376 }
1377}
1378
1379impl From<StyleRefinement> for TextPartStyle {
1380 fn from(style: StyleRefinement) -> Self {
1381 Self(Style::from(style))
1382 }
1383}
1384
1385impl From<TextPartStyle> for Style {
1386 fn from(style: TextPartStyle) -> Self {
1387 style.0
1388 }
1389}
1390
1391impl JsValue for TextPartStyle {
1392 fn ts_type(_types: &mut super::TsTypes) -> String {
1393 "StyleProp<TextStyle>".into()
1394 }
1395
1396 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1397 Style::from_js(value).map(Self)
1398 }
1399
1400 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1401 self.0.to_js(host)
1402 }
1403}
1404
1405#[derive(Debug, Clone, Default, PartialEq)]
1411#[non_exhaustive]
1412pub struct InputPartStyle(pub Style);
1413
1414impl From<Style> for InputPartStyle {
1415 fn from(style: Style) -> Self {
1416 Self(style)
1417 }
1418}
1419
1420impl From<StyleRefinement> for InputPartStyle {
1421 fn from(style: StyleRefinement) -> Self {
1422 Self(Style::from(style))
1423 }
1424}
1425
1426impl From<InputPartStyle> for Style {
1427 fn from(style: InputPartStyle) -> Self {
1428 style.0
1429 }
1430}
1431
1432impl JsValue for InputPartStyle {
1433 fn ts_type(_types: &mut super::TsTypes) -> String {
1434 "StyleProp<InputStyle>".into()
1435 }
1436
1437 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1438 Style::from_js(value).map(Self)
1439 }
1440
1441 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1442 self.0.to_js(host)
1443 }
1444}
1445
1446impl<T: Element> Styled for T {
1447 fn style(&mut self) -> &mut StyleRefinement {
1448 &mut self.node().style
1449 }
1450}
1451
1452pub trait ParentElement: Element {
1454 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1457 child.__push_into(&mut self.node().children);
1458 self
1459 }
1460
1461 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1463 self.node()
1464 .children
1465 .extend(children.into_iter().map(|c| c.into_element().0));
1466 self
1467 }
1468
1469 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1472 if let Some(slot) = slot {
1473 let mut node = ElNode::new(Tag::View);
1474 node.kind = ElKind::Slot(slot.name);
1475 self.node().children.push(place(SlotElement(node)).0);
1476 }
1477 self
1478 }
1479
1480 fn children_each<R: IntoElement>(
1483 mut self,
1484 children: impl Into<Children>,
1485 place: impl Fn(Child, Position) -> R + 'static,
1486 ) -> Self {
1487 let _ = children.into();
1488 let mut node = ElNode::new(Tag::View);
1489 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1490 self.node().children.push(node);
1491 self
1492 }
1493
1494 fn list<R: IntoElement>(
1500 mut self,
1501 items: Items,
1502 config: impl FnOnce(ListElement) -> ListElement,
1503 row: impl Fn(Child, Position) -> R + 'static,
1504 ) -> Self {
1505 let mut node = ElNode::new(Tag::List);
1506 node.kind = ElKind::List(Box::new(ListEl {
1507 name: items.name,
1508 config: ListConfig::default(),
1509 row: Rc::new(move |content, at| row(content, at).into_element()),
1510 }));
1511 self.node().children.push(config(ListElement(node)).0);
1512 self
1513 }
1514}
1515
1516pub trait Accessible: Element {
1518 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1520 self.node().bind_attr(accessible, |a, accessible| {
1521 a.rare_mut().accessible = Some(accessible)
1522 });
1523 self
1524 }
1525
1526 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1528 self.node()
1529 .bind_attr(label, |a, label| a.label = Some(label));
1530 self
1531 }
1532
1533 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1536 self.node().bind_attr(label, |a, label| a.label = label);
1537 self
1538 }
1539
1540 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1542 self.node()
1543 .bind_attr(hint, |a, hint| a.rare_mut().hint = Some(hint));
1544 self
1545 }
1546
1547 fn optional_hint(mut self, hint: impl IntoReactive<Option<SharedString>>) -> Self {
1550 self.node().bind_attr(hint, |a, hint| {
1551 if hint.is_some() || a.rare.is_some() {
1552 a.rare_mut().hint = hint;
1553 }
1554 });
1555 self
1556 }
1557
1558 fn accessibility_description(mut self, description: impl IntoReactive<SharedString>) -> Self {
1562 self.node().bind_attr(description, |a, description| {
1563 a.rare_mut().description = Some(description)
1564 });
1565 self
1566 }
1567
1568 fn optional_accessibility_description(
1572 mut self,
1573 description: impl IntoReactive<Option<SharedString>>,
1574 ) -> Self {
1575 self.node().bind_attr(description, |a, description| {
1576 if description.is_some() || a.rare.is_some() {
1577 a.rare_mut().description = description;
1578 }
1579 });
1580 self
1581 }
1582
1583 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1585 self.node().bind_attr(role, |a, role| a.role = role);
1586 self
1587 }
1588
1589 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1592 self.node().bind_attr(state, |a, state| {
1593 a.state = AccessibilityState {
1594 disabled: a.state.disabled,
1595 ..state
1596 };
1597 });
1598 self
1599 }
1600
1601 fn accessibility_level(mut self, level: impl IntoReactive<u32>) -> Self {
1605 self.node().bind_attr(level, |a, level| {
1606 super::host::set_in(
1607 &mut a.props,
1608 Prop::Accessibility(AccessibilityProp::Level((level > 0).then_some(level))),
1609 )
1610 });
1611 self
1612 }
1613
1614 fn accessibility_orientation(mut self, orientation: impl IntoReactive<Option<Axis>>) -> Self {
1619 self.node().bind_attr(orientation, |a, orientation| {
1620 super::host::set_in(
1621 &mut a.props,
1622 Prop::Accessibility(AccessibilityProp::Orientation(orientation)),
1623 )
1624 });
1625 self
1626 }
1627
1628 fn accessibility_live_region(mut self, region: impl IntoReactive<LiveRegion>) -> Self {
1633 self.node().bind_attr(region, |a, region| {
1634 super::host::set_in(
1635 &mut a.props,
1636 Prop::Accessibility(AccessibilityProp::LiveRegion(region)),
1637 )
1638 });
1639 self
1640 }
1641
1642 fn accessibility_active_descendant(
1650 mut self,
1651 target: impl IntoReactive<Option<super::ElementRef>>,
1652 ) -> Self {
1653 self.node()
1654 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1655 super::host::set_in(
1656 &mut a.props,
1657 Prop::Accessibility(AccessibilityProp::ActiveDescendant(
1658 target.and_then(|t| t.element_target()),
1659 )),
1660 )
1661 });
1662 self
1663 }
1664
1665 fn accessibility_controls(
1669 mut self,
1670 target: impl IntoReactive<Option<super::ElementRef>>,
1671 ) -> Self {
1672 self.node()
1673 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1674 super::host::set_in(
1675 &mut a.props,
1676 Prop::Accessibility(AccessibilityProp::Controls(
1677 target.and_then(|t| t.element_target()),
1678 )),
1679 )
1680 });
1681 self
1682 }
1683
1684 fn accessibility_described_by(
1691 self,
1692 target: impl IntoReactive<Option<super::ElementRef>>,
1693 ) -> Self {
1694 let target = target.into_reactive();
1695 self.accessibility_described_by_target(move || {
1696 target.get().and_then(|t| t.element_target())
1697 })
1698 }
1699
1700 #[doc(hidden)]
1704 fn accessibility_described_by_target(
1705 mut self,
1706 target: impl IntoReactive<Option<super::ElementTarget>>,
1707 ) -> Self {
1708 self.node()
1709 .bind_attr(target, |a, target: Option<super::ElementTarget>| {
1710 super::host::set_in(
1711 &mut a.props,
1712 Prop::Accessibility(AccessibilityProp::DescribedBy(target)),
1713 )
1714 });
1715 self
1716 }
1717
1718 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1722 self.node().bind_attr(value, |a, value| {
1723 if value.is_some() || a.rare.is_some() {
1724 a.rare_mut().value = value;
1725 }
1726 });
1727 self
1728 }
1729
1730 fn accessibility_elements_hidden(mut self, hidden: impl IntoReactive<bool>) -> Self {
1736 self.node().bind_attr(hidden, |a, hidden| {
1737 super::host::set_in(
1738 &mut a.props,
1739 Prop::Accessibility(AccessibilityProp::Hidden(hidden)),
1740 )
1741 });
1742 self
1743 }
1744
1745 fn accessibility_actions(
1753 mut self,
1754 actions: impl IntoReactive<Vec<crate::AccessibilityActionDef>>,
1755 ) -> Self {
1756 self.node().bind_attr(actions, |a, actions| {
1757 super::host::set_in(
1758 &mut a.props,
1759 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1760 )
1761 });
1762 self
1763 }
1764}
1765
1766pub trait IntoTooltip {
1769 #[doc(hidden)]
1770 fn apply_tooltip(self, node: &mut ElNode);
1771}
1772
1773impl IntoTooltip for AnyElement {
1774 fn apply_tooltip(self, node: &mut ElNode) {
1775 let mut hint = ElNode::new(Tag::Overlay);
1777 hint.key = Some("tooltip".into());
1778 hint.attrs.pointer_events = PointerEvents::None;
1779 let gap = Points(4.0);
1780 for prop in [
1781 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1782 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1783 crate::OverlayProp::Offset(gap),
1784 crate::OverlayProp::Margin(gap),
1785 ] {
1786 super::host::set(&mut hint, Prop::Overlay(prop));
1787 }
1788 hint.children.push(self.0);
1789 node.children.push(hint);
1790 }
1791}
1792
1793impl<C: Component> IntoTooltip for ComponentElement<C> {
1794 fn apply_tooltip(self, node: &mut ElNode) {
1795 self.into_element().apply_tooltip(node);
1796 }
1797}
1798
1799#[doc(hidden)]
1804pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1805 let mut hint = hint.0;
1806 hint.key = Some("tooltip".into());
1807 node.children.push(hint);
1808}
1809
1810pub trait Interactive: Element {
1812 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1818 tooltip.apply_tooltip(self.node());
1819 self
1820 }
1821
1822 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
1826 self.on(
1827 EventKind::FileDragEnter,
1828 events::typed(listener.into_listener(), events::file_drag),
1829 )
1830 }
1831
1832 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1834 self.on(
1835 EventKind::FileDragLeave,
1836 events::typed(listener.into_listener(), events::unit),
1837 )
1838 }
1839
1840 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1842 self.on(
1843 EventKind::FileDrop,
1844 events::typed(listener.into_listener(), events::file_drop),
1845 )
1846 }
1847
1848 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1851 self.on(
1852 EventKind::MouseEnter,
1853 events::typed(listener.into_listener(), events::mouse),
1854 )
1855 }
1856
1857 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1860 self.on(
1861 EventKind::MouseLeave,
1862 events::typed(listener.into_listener(), events::mouse),
1863 )
1864 }
1865
1866 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1871 self.on(
1872 EventKind::MouseMove,
1873 events::typed(listener.into_listener(), events::mouse),
1874 )
1875 }
1876
1877 fn on_wheel<M>(self, listener: impl IntoListener<WheelEvent, M>) -> Self {
1885 self.on(
1886 EventKind::Wheel,
1887 events::typed(listener.into_listener(), events::wheel),
1888 )
1889 }
1890
1891 fn on_pinch<M>(self, listener: impl IntoListener<PinchEvent, M>) -> Self {
1902 self.on(
1903 EventKind::Pinch,
1904 events::typed(listener.into_listener(), events::touchpad_pinch),
1905 )
1906 }
1907
1908 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1913 self.on(
1914 EventKind::MouseUp,
1915 events::typed(listener.into_listener(), events::mouse),
1916 )
1917 }
1918
1919 fn on_key_down<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1927 self.on(
1928 EventKind::KeyDown,
1929 events::typed(listener.into_listener(), events::key_event),
1930 )
1931 }
1932
1933 fn on_key_up<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
1939 self.on(
1940 EventKind::KeyUp,
1941 events::typed(listener.into_listener(), events::key_event),
1942 )
1943 }
1944
1945 fn capture_keys(mut self, capture: impl IntoReactive<KeyCapture>) -> Self {
1953 super::host::bind_prop(self.node(), capture, Prop::KeyCapture);
1954 self
1955 }
1956 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
1961 self.on(
1962 EventKind::ContextMenu,
1963 events::typed(listener.into_listener(), events::context_menu),
1964 )
1965 }
1966
1967 fn on_text_selection_change<M>(
1976 self,
1977 listener: impl IntoListener<super::TextSelectionEvent, M>,
1978 ) -> Self {
1979 self.on(
1980 EventKind::SelectionChange,
1981 events::typed(listener.into_listener(), events::selected_text),
1982 )
1983 }
1984
1985 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
1989 self.on(
1990 EventKind::Focus,
1991 events::typed(listener.into_listener(), events::unit),
1992 )
1993 }
1994
1995 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
1997 self.on(
1998 EventKind::Blur,
1999 events::typed(listener.into_listener(), events::unit),
2000 )
2001 }
2002
2003 fn on_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2009 self.on(
2010 EventKind::Press,
2011 events::typed(listener.into_listener(), events::press),
2012 )
2013 }
2014
2015 fn on_long_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2017 self.on(
2018 EventKind::LongPress,
2019 events::typed(listener.into_listener(), events::press),
2020 )
2021 }
2022
2023 fn on_press_down<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2025 self.on(
2026 EventKind::PressDown,
2027 events::typed(listener.into_listener(), events::press),
2028 )
2029 }
2030
2031 fn on_press_up<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2033 self.on(
2034 EventKind::PressUp,
2035 events::typed(listener.into_listener(), events::press),
2036 )
2037 }
2038
2039 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
2041 self.on(
2042 EventKind::Layout,
2043 events::typed(listener.into_listener(), events::layout),
2044 )
2045 }
2046
2047 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
2051 self.on(
2052 EventKind::Touch,
2053 events::typed(listener.into_listener(), events::touch),
2054 )
2055 }
2056
2057 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
2062 if let Some(pan) = claim.pan {
2063 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
2064 }
2065 super::responder::of(self.node()).claims.push(claim);
2066 self
2067 }
2068
2069 fn pan_activation(mut self, activation: PanActivation) -> Self {
2078 super::host::set(self.node(), Prop::PanActivation(Some(activation)));
2079 self
2080 }
2081
2082 fn keep_touches(mut self, keep: bool) -> Self {
2087 super::responder::of(self.node()).keep = keep;
2088 self
2089 }
2090
2091 fn on_responder_grant<M>(
2093 mut self,
2094 listener: impl IntoListener<super::ResponderEvent, M>,
2095 ) -> Self {
2096 super::responder::of(self.node()).grant = Some(listener.into_listener());
2097 self
2098 }
2099
2100 fn on_responder_reject<M>(
2103 mut self,
2104 listener: impl IntoListener<super::ResponderEvent, M>,
2105 ) -> Self {
2106 super::responder::of(self.node()).reject = Some(listener.into_listener());
2107 self
2108 }
2109
2110 fn on_responder_start<M>(
2113 mut self,
2114 listener: impl IntoListener<super::ResponderEvent, M>,
2115 ) -> Self {
2116 super::responder::of(self.node()).start = Some(listener.into_listener());
2117 self
2118 }
2119
2120 fn on_responder_move<M>(
2122 mut self,
2123 listener: impl IntoListener<super::ResponderEvent, M>,
2124 ) -> Self {
2125 super::responder::of(self.node()).moved = Some(listener.into_listener());
2126 self
2127 }
2128
2129 fn on_responder_end<M>(
2131 mut self,
2132 listener: impl IntoListener<super::ResponderEvent, M>,
2133 ) -> Self {
2134 super::responder::of(self.node()).end = Some(listener.into_listener());
2135 self
2136 }
2137
2138 fn on_responder_release<M>(
2141 mut self,
2142 listener: impl IntoListener<super::ResponderEvent, M>,
2143 ) -> Self {
2144 super::responder::of(self.node()).release = Some(listener.into_listener());
2145 self
2146 }
2147
2148 fn on_responder_terminate<M>(
2151 mut self,
2152 listener: impl IntoListener<super::ResponderEvent, M>,
2153 ) -> Self {
2154 super::responder::of(self.node()).terminate = Some(listener.into_listener());
2155 self
2156 }
2157
2158 fn pan_values(
2163 mut self,
2164 x: Option<&super::AnimatedValue>,
2165 y: Option<&super::AnimatedValue>,
2166 ) -> Self {
2167 let x = x.and_then(|v| v.node().live());
2168 let y = y.and_then(|v| v.node().live());
2169 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
2170 super::host::set(self.node(), prop);
2171 if x.is_some() || y.is_some() {
2172 let bound = &mut self.node().attrs.rare_mut().bound;
2173 bound.extend(x);
2174 bound.extend(y);
2175 }
2176 self
2177 }
2178
2179 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
2182 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
2183 self
2184 }
2185
2186 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
2191 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
2192 self
2193 }
2194
2195 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
2200 if let Some(node) = scale.node().live() {
2201 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
2202 self.node().attrs.rare_mut().bound.push(node);
2203 }
2204 self
2205 }
2206
2207 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
2211 if let Some(node) = angle.node().live() {
2212 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
2213 self.node().attrs.rare_mut().bound.push(node);
2214 }
2215 self
2216 }
2217
2218 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2220 self.on(
2221 EventKind::PanStart,
2222 events::typed(listener.into_listener(), events::pan),
2223 )
2224 }
2225
2226 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2228 self.on(
2229 EventKind::PanEnd,
2230 events::typed(listener.into_listener(), events::pan),
2231 )
2232 }
2233
2234 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2236 self.on(
2237 EventKind::PinchStart,
2238 events::typed(listener.into_listener(), events::pinch),
2239 )
2240 }
2241
2242 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2244 self.on(
2245 EventKind::PinchEnd,
2246 events::typed(listener.into_listener(), events::pinch),
2247 )
2248 }
2249
2250 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2252 self.on(
2253 EventKind::RotationStart,
2254 events::typed(listener.into_listener(), events::rotation),
2255 )
2256 }
2257
2258 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2260 self.on(
2261 EventKind::RotationEnd,
2262 events::typed(listener.into_listener(), events::rotation),
2263 )
2264 }
2265
2266 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
2268 self.on(
2269 EventKind::AccessibilityAction,
2270 events::typed(listener.into_listener(), events::action),
2271 )
2272 }
2273
2274 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
2277 self.node().handlers.push((kind, listener.into_listener()));
2278 self
2279 }
2280
2281 fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
2283 super::host::bind_prop(self.node(), insets, Prop::HitSlop);
2284 self
2285 }
2286
2287 #[doc(hidden)]
2291 fn __link_href(mut self, href: impl IntoReactive<Option<SharedString>>) -> Self {
2292 super::host::bind_prop(self.node(), href, |href: Option<SharedString>| {
2293 Prop::Href(href.map(|href| href.to_arc()))
2294 });
2295 self
2296 }
2297
2298 fn long_press_delay(mut self, ms: f32) -> Self {
2300 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
2301 self
2302 }
2303
2304 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
2306 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
2307 self
2308 }
2309
2310 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
2312 super::host::set(self.node(), Prop::Elevation(elevation.into()));
2313 self
2314 }
2315
2316 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
2318 super::host::set(self.node(), Prop::BackdropMaterial(material));
2319 self
2320 }
2321
2322 fn scroll_edge_element(
2330 mut self,
2331 scroll_view: impl IntoReactive<Option<super::ElementRef>>,
2332 edge: crate::ScrollEdge,
2333 ) -> Self {
2334 let target =
2335 scroll_view
2336 .into_reactive()
2337 .map(move |scroll_view: Option<super::ElementRef>| {
2338 let scroll_view = scroll_view?.element_target()?;
2339 Some(super::ScrollEdgeTarget { scroll_view, edge })
2340 });
2341 super::host::bind_prop(self.node(), target, Prop::ScrollEdgeElement);
2342 self
2343 }
2344
2345 fn macos_backdrop(mut self, backdrop: impl IntoReactive<Option<crate::MacOsBackdrop>>) -> Self {
2348 super::host::bind_prop(self.node(), backdrop, Prop::MacOsBackdrop);
2349 self
2350 }
2351
2352 fn windows_backdrop(
2356 mut self,
2357 backdrop: impl IntoReactive<Option<crate::WindowsBackdrop>>,
2358 ) -> Self {
2359 super::host::bind_prop(self.node(), backdrop, Prop::WindowsBackdrop);
2360 self
2361 }
2362
2363 fn test_id(mut self, id: &str) -> Self {
2365 super::host::set(self.node(), Prop::TestId(Some(id.into())));
2366 self
2367 }
2368
2369 fn web_element(mut self, element: crate::WebElement) -> Self {
2375 super::host::set(self.node(), Prop::WebElement(Some(element)));
2376 self
2377 }
2378
2379 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
2387 super::host::bind_prop(self.node(), enabled, |enabled| {
2388 Prop::WindowDrag(Some(enabled))
2389 });
2390 self
2391 }
2392
2393 fn window_control(mut self, control: crate::desktop::WindowControl) -> Self {
2398 super::host::set(self.node(), Prop::WindowControl(Some(control)));
2399 self
2400 }
2401
2402 fn window_resize(mut self, edge: crate::desktop::ResizeEdge) -> Self {
2405 super::host::set(self.node(), Prop::WindowResize(Some(edge)));
2406 self
2407 }
2408
2409 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
2417 super::host::bind_prop(self.node(), focusable, |focusable| {
2418 Prop::Focusable(Some(focusable))
2419 });
2420 self
2421 }
2422
2423 fn native_id(mut self, id: &str) -> Self {
2426 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
2427 self
2428 }
2429
2430 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2432 let s = f(StyleRefinement::default());
2433 self.style().extend_as(Variant::ACTIVE, s);
2434 self
2435 }
2436
2437 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2439 let s = f(StyleRefinement::default());
2440 self.style().extend_as(Variant::HOVER, s);
2441 self
2442 }
2443
2444 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2446 let s = f(StyleRefinement::default());
2447 self.style().extend_as(Variant::FOCUS, s);
2448 self
2449 }
2450
2451 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2456 let s = f(StyleRefinement::default());
2457 self.style().extend_as(Variant::FOCUS_VISIBLE, s);
2458 self
2459 }
2460
2461 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2466 let s = f(StyleRefinement::default());
2467 self.style().extend_as(Variant::FOCUS_WITHIN, s);
2468 self
2469 }
2470
2471 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2473 let s = f(StyleRefinement::default());
2474 self.style().extend_as(Variant::DISABLED, s);
2475 self
2476 }
2477
2478 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2480 self.node().bind_attr(disabled, |a, disabled| {
2481 a.disabled = disabled;
2482 a.state.disabled = disabled;
2483 });
2484 self
2485 }
2486
2487 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
2490 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
2491 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
2492 });
2493 self
2494 }
2495
2496 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
2500 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
2501 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
2502 });
2503 self
2504 }
2505
2506 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
2510 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
2511 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
2512 });
2513 self
2514 }
2515
2516 fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
2520 Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
2521 super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
2522 });
2523 self
2524 }
2525
2526 fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
2530 Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
2531 super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
2532 });
2533 self
2534 }
2535
2536 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
2542 self.node().bind_attr(checked, |a, checked| {
2543 project(a, crate::tailwind::state::CHECKED, checked)
2544 });
2545 self
2546 }
2547
2548 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
2554 self.node().bind_attr(indeterminate, |a, indeterminate| {
2555 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
2556 });
2557 self
2558 }
2559
2560 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2565 self.node().bind_attr(disabled, |a, disabled| {
2566 project(a, crate::tailwind::state::DISABLED, disabled)
2567 });
2568 self
2569 }
2570
2571 fn project_hovered(mut self, hovered: impl IntoReactive<bool>) -> Self {
2577 self.node().bind_attr(hovered, |a, hovered| {
2578 project(a, crate::tailwind::state::HOVERED, hovered)
2579 });
2580 self
2581 }
2582
2583 fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
2592 self.node().bind_attr(focused, |a, focused| {
2593 project(a, crate::tailwind::state::FOCUSED, focused)
2594 });
2595 self
2596 }
2597
2598 fn project_group_active(mut self, group: &'static str) -> Self {
2608 self.node().bind_attr(true, move |a, _: bool| {
2609 a.rare_mut().projected_active = Some(group)
2610 });
2611 self
2612 }
2613
2614 fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
2623 self.node().bind_attr(on, move |a, on| {
2624 if !on && a.rare.is_none() {
2625 return;
2626 }
2627 let data = &mut a.rare_mut().projected_data;
2628 let at = data.binary_search(&name);
2629 match (at, on) {
2630 (Err(i), true) => data.insert(i, name),
2631 (Ok(i), false) => {
2632 data.remove(i);
2633 }
2634 _ => {}
2635 }
2636 });
2637 self
2638 }
2639}
2640
2641fn project(a: &mut Attrs, bit: u16, on: bool) {
2643 if on {
2644 a.rare_mut().projected_states |= bit;
2645 } else if let Some(r) = &mut a.rare {
2646 r.projected_states &= !bit;
2647 }
2648}
2649
2650macro_rules! element {
2651 ($(#[$doc:meta])* $name:ident) => {
2652 $(#[$doc])*
2653 #[derive(Clone)]
2654 pub struct $name(ElNode);
2655
2656 impl Element for $name {
2657 fn node(&mut self) -> &mut ElNode {
2658 &mut self.0
2659 }
2660 }
2661
2662 impl IntoElement for $name {
2663 fn into_element(self) -> AnyElement {
2664 AnyElement(self.0)
2665 }
2666 }
2667
2668 impl Accessible for $name {}
2669
2670 impl IntoTooltip for $name {
2671 fn apply_tooltip(self, node: &mut ElNode) {
2672 self.into_element().apply_tooltip(node);
2673 }
2674 }
2675 };
2676}
2677
2678element! {
2679 View
2681}
2682
2683element! {
2684 Text
2686}
2687
2688element! {
2689 Image
2691}
2692
2693element! {
2694 SlotElement
2697}
2698
2699element! {
2700 ListElement
2702}
2703
2704impl Interactive for View {}
2705impl ParentElement for View {}
2706
2707impl View {
2708 pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2727 let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2728 t.and_then(|t| t.target()).map(super::FollowTarget)
2729 });
2730 super::host::bind_prop(&mut self.0, target, Prop::Follow);
2731 self
2732 }
2733
2734 pub fn follow_transition(
2740 mut self,
2741 transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2742 ) -> Self {
2743 super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2744 self
2745 }
2746}
2747impl Interactive for SlotElement {}
2748impl Interactive for Text {}
2749impl Interactive for Image {}
2750
2751impl ParentElement for Text {
2756 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2757 let at = self.0.children.len();
2758 child.__push_into(&mut self.0.children);
2759 for el in &mut self.0.children[at..] {
2760 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2761 }
2762 self
2763 }
2764
2765 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2766 self.0
2767 .children
2768 .extend(children.into_iter().map(|c| span(c.into_element().0)));
2769 self
2770 }
2771}
2772
2773fn span(mut el: ElNode) -> ElNode {
2776 if el.tag == Tag::Text
2777 && matches!(el.kind, ElKind::Plain)
2778 && el.key.is_none()
2779 && el.children.is_empty()
2780 && el.handlers.is_empty()
2781 && el.style.is_empty()
2782 && el.attrs == Attrs::default()
2783 && !el.is_bound()
2784 {
2785 el.kind = ElKind::Raw;
2786 }
2787 el
2788}
2789
2790impl Text {
2791 pub fn on_text_layout(mut self, listener: impl Fn(&crate::TextGeometry) + 'static) -> Self {
2797 self.0.handlers.push((
2798 EventKind::TextLayout,
2799 super::Listener::from(move |payload: &EventPayload| {
2800 if let EventPayload::TextLayout(_) = payload
2801 && let Some(geometry) = crate::text::GeometryScope::current()
2802 {
2803 listener(&geometry);
2804 }
2805 }),
2806 ));
2807 self
2808 }
2809
2810 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2812 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2813 Prop::SelectionColor(Some(Color::from(c)))
2814 });
2815 self
2816 }
2817
2818 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2820 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2821 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2822 self
2823 }
2824
2825 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2828 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2829 self
2830 }
2831
2832 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2835 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2836 self
2837 }
2838}
2839
2840impl Image {
2841 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2844 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2845 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2846 uri: src.uri.to_arc(),
2847 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2848 scales: src.scales,
2849 data: src.data,
2850 })))
2851 });
2852 self
2853 }
2854
2855 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2857 Styled::tint_color(self, color)
2858 }
2859
2860 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2862 super::host::set(
2863 &mut self.0,
2864 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2865 );
2866 self
2867 }
2868
2869 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2871 super::host::bind_prop(&mut self.0, ms, |ms| {
2872 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
2873 });
2874 self
2875 }
2876
2877 pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
2879 self.on(
2880 EventKind::Load,
2881 events::typed(listener.into_listener(), events::pixel_size),
2882 )
2883 }
2884
2885 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
2887 self.on(
2888 EventKind::Error,
2889 events::typed(listener.into_listener(), events::message),
2890 )
2891 }
2892
2893 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
2895 self.on(
2896 EventKind::LoadStart,
2897 events::typed(listener.into_listener(), events::unit),
2898 )
2899 }
2900
2901 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
2903 self.on(
2904 EventKind::LoadEnd,
2905 events::typed(listener.into_listener(), events::unit),
2906 )
2907 }
2908
2909 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
2912 self.on(
2913 EventKind::Progress,
2914 events::typed(listener.into_listener(), events::image_progress),
2915 )
2916 }
2917}
2918
2919impl super::Scrollable for ListElement {}
2920
2921impl super::ListLayout for ListElement {
2922 fn config(&mut self) -> &mut ListConfig {
2923 match &mut self.0.kind {
2924 ElKind::List(list) => &mut list.config,
2925 _ => unreachable!("a ListElement is a list"),
2926 }
2927 }
2928
2929 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
2930 &mut self.0.bound_list
2931 }
2932}
2933
2934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2937pub struct Slot {
2938 name: &'static str,
2939}
2940
2941impl Slot {
2942 pub(crate) fn new(name: &'static str) -> Self {
2943 Self { name }
2944 }
2945
2946 pub fn name(&self) -> &'static str {
2948 self.name
2949 }
2950
2951 pub fn element(self) -> SlotElement {
2953 let mut node = ElNode::new(Tag::View);
2954 node.kind = ElKind::Slot(self.name);
2955 SlotElement(node)
2956 }
2957}
2958
2959#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2963pub struct Items {
2964 name: &'static str,
2965}
2966
2967impl Items {
2968 #[doc(hidden)]
2969 pub const fn __new(name: &'static str) -> Self {
2970 Self { name }
2971 }
2972}
2973
2974#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2978pub struct Child(ChildRef);
2979
2980#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2981enum ChildRef {
2982 Js(NodeId),
2983 Row,
2984}
2985
2986impl Child {
2987 pub(crate) fn js(id: NodeId) -> Self {
2988 Self(ChildRef::Js(id))
2989 }
2990
2991 pub(crate) fn row() -> Self {
2992 Self(ChildRef::Row)
2993 }
2994}
2995
2996impl IntoElement for Child {
2997 fn into_element(self) -> AnyElement {
2998 let mut node = ElNode::new(Tag::View);
2999 node.kind = match self.0 {
3000 ChildRef::Js(id) => ElKind::JsChild(id),
3001 ChildRef::Row => ElKind::Children,
3002 };
3003 AnyElement(node)
3004 }
3005}
3006
3007pub fn view() -> View {
3009 View(ElNode::new(Tag::View))
3010}
3011
3012pub fn text(content: impl IntoReactive<SharedString>) -> Text {
3015 let mut node = ElNode::new(Tag::Text);
3016 match content.into_reactive() {
3017 Reactive::Static(content) => node.text = Some(content),
3018 Reactive::Bound(content) => {
3019 node.text = Some(SharedString::default());
3020 node.bound_text = Some(content);
3021 }
3022 }
3023 Text(node)
3024}
3025
3026pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
3030 let mut node = ElNode::new(Tag::Image);
3031 node.bind_attr(src, |a, src| a.rare_mut().src = Some(src));
3032 Image(node)
3033}
3034
3035#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3038pub struct Children {
3039 present: bool,
3040}
3041
3042impl Children {
3043 pub(crate) fn new(present: bool) -> Self {
3044 Self { present }
3045 }
3046
3047 pub fn is_empty(&self) -> bool {
3049 !self.present
3050 }
3051}
3052
3053impl IntoElement for Children {
3054 fn into_element(self) -> AnyElement {
3055 let mut node = ElNode::new(Tag::View);
3056 node.kind = ElKind::Children;
3057 AnyElement(node)
3058 }
3059}
3060
3061pub struct ComponentElement<C: Component> {
3074 node: ElNode,
3075 _component: PhantomData<fn() -> C>,
3076}
3077
3078impl<C: Component> ComponentElement<C> {
3079 #[doc(hidden)]
3082 pub fn __new(props: C::Props) -> Self {
3083 Self::new(props)
3084 }
3085
3086 #[doc(hidden)]
3088 pub fn __props_mut(&mut self) -> &mut C::Props {
3089 match &mut self.node.kind {
3090 ElKind::Component(c) => c
3091 .props
3092 .as_any_mut()
3093 .downcast_mut::<C::Props>()
3094 .expect("a component element holds its component's props"),
3095 _ => unreachable!("a component element is a component's"),
3096 }
3097 }
3098
3099 pub(crate) fn new(props: C::Props) -> Self {
3100 let mut node = ElNode::new(Tag::View);
3101 node.kind = ElKind::Component(ComponentEl {
3102 name: super::component::name_of::<C>(),
3103 make: super::component::make_instance::<C>,
3104 spec: ComponentSpec::of::<C>,
3105 props: Box::new(props),
3106 on_event: Vec::new(),
3107 by_name: None,
3108 });
3109 Self {
3110 node,
3111 _component: PhantomData,
3112 }
3113 }
3114
3115 pub fn by_name(props: C::Props) -> Self {
3124 if cfg!(not(target_arch = "wasm32")) {
3125 return Self::new(props);
3126 }
3127 Self::named(props)
3128 }
3129
3130 pub(crate) fn named(props: C::Props) -> Self {
3132 let mut node = ElNode::new(Tag::View);
3133 node.kind = ElKind::Component(ComponentEl {
3134 name: super::component::name_of::<C>(),
3135 make: super::component::missing_instance,
3136 spec: super::component::missing_spec,
3137 props: Box::new(props),
3138 on_event: Vec::new(),
3139 by_name: Some(std::any::TypeId::of::<C>()),
3140 });
3141 Self {
3142 node,
3143 _component: PhantomData,
3144 }
3145 }
3146
3147 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
3152 self.node
3153 .children
3154 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
3155 let mut fill = ElNode::new(Tag::View);
3156 fill.kind = ElKind::Fill(slot);
3157 fill.children.push(content.into_element().0);
3158 self.node.children.push(fill);
3159 self
3160 }
3161
3162 pub fn items(mut self, list: super::VirtualList) -> Self {
3170 match <C::Props as super::Props>::ITEMS {
3171 Some(name) => self.node.children.push(list.into_items(name)),
3172 None => {
3173 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
3174 }
3175 }
3176 self
3177 }
3178
3179 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3184 let s = f(StyleRefinement::default());
3185 self.node.style.extend_as(Variant::ACTIVE, s);
3186 self
3187 }
3188
3189 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3191 let s = f(StyleRefinement::default());
3192 self.node.style.extend_as(Variant::HOVER, s);
3193 self
3194 }
3195
3196 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3198 let s = f(StyleRefinement::default());
3199 self.node.style.extend_as(Variant::FOCUS, s);
3200 self
3201 }
3202
3203 pub fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3206 let s = f(StyleRefinement::default());
3207 self.node.style.extend_as(Variant::FOCUS_VISIBLE, s);
3208 self
3209 }
3210
3211 pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3214 let s = f(StyleRefinement::default());
3215 self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
3216 self
3217 }
3218
3219 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3222 let s = f(StyleRefinement::default());
3223 self.node.style.extend_as(Variant::DISABLED, s);
3224 self
3225 }
3226
3227 pub fn test_id(mut self, id: &str) -> Self {
3230 super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
3231 self
3232 }
3233
3234 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
3236 self.node.attrs.set_element_ref(handle.element().target());
3237 self
3238 }
3239
3240 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
3246 let listener = listener.into_listener();
3247 if let ElKind::Component(c) = &mut self.node.kind {
3248 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
3249 if let Some(event) = event.downcast_ref::<C::Event>() {
3250 inner(event);
3251 }
3252 }));
3253 }
3254 self
3255 }
3256
3257 #[doc(hidden)]
3261 pub fn __on_variant<T: ?Sized + 'static, M>(
3262 self,
3263 pick: fn(&C::Event) -> Option<&T>,
3264 listener: impl IntoListener<T, M>,
3265 ) -> Self {
3266 let listener = listener.into_listener();
3267 self.on_event(listener.wrap(move |inner, event: &C::Event| {
3268 if let Some(data) = pick(event) {
3269 inner(data);
3270 }
3271 }))
3272 }
3273}
3274
3275pub trait ComponentBuilder: Element {
3347 type Component: Component;
3349
3350 #[doc(hidden)]
3352 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
3353
3354 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3359 let s = f(StyleRefinement::default());
3360 self.node().style.extend_as(Variant::ACTIVE, s);
3361 self
3362 }
3363
3364 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3366 let s = f(StyleRefinement::default());
3367 self.node().style.extend_as(Variant::HOVER, s);
3368 self
3369 }
3370
3371 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3373 let s = f(StyleRefinement::default());
3374 self.node().style.extend_as(Variant::FOCUS, s);
3375 self
3376 }
3377
3378 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3381 let s = f(StyleRefinement::default());
3382 self.node().style.extend_as(Variant::FOCUS_VISIBLE, s);
3383 self
3384 }
3385
3386 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3389 let s = f(StyleRefinement::default());
3390 self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
3391 self
3392 }
3393
3394 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3397 let s = f(StyleRefinement::default());
3398 self.node().style.extend_as(Variant::DISABLED, s);
3399 self
3400 }
3401
3402 #[doc(hidden)]
3405 fn __listen(mut self, kind: EventKind, listener: Listener<EventPayload>) -> Self {
3406 self.node().handlers.push((kind, listener));
3407 self
3408 }
3409
3410 fn test_id(mut self, id: &str) -> Self {
3413 super::host::set(self.node(), Prop::TestId(Some(id.into())));
3414 self
3415 }
3416
3417 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
3421 let listener = events::typed(listener.into_listener(), events::layout);
3422 self.__listen(EventKind::Layout, listener)
3423 }
3424
3425 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3429 let listener = events::typed(listener.into_listener(), events::mouse);
3430 self.__listen(EventKind::MouseEnter, listener)
3431 }
3432
3433 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3436 let listener = events::typed(listener.into_listener(), events::mouse);
3437 self.__listen(EventKind::MouseLeave, listener)
3438 }
3439
3440 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3444 let listener = events::typed(listener.into_listener(), events::mouse);
3445 self.__listen(EventKind::MouseMove, listener)
3446 }
3447
3448 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3451 let listener = events::typed(listener.into_listener(), events::mouse);
3452 self.__listen(EventKind::MouseUp, listener)
3453 }
3454
3455 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
3460 let listener = events::typed(listener.into_listener(), events::context_menu);
3461 self.__listen(EventKind::ContextMenu, listener)
3462 }
3463
3464 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
3467 let listener = events::typed(listener.into_listener(), events::file_drag);
3468 self.__listen(EventKind::FileDragEnter, listener)
3469 }
3470
3471 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
3474 let listener = events::typed(listener.into_listener(), events::unit);
3475 self.__listen(EventKind::FileDragLeave, listener)
3476 }
3477
3478 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
3481 let listener = events::typed(listener.into_listener(), events::file_drop);
3482 self.__listen(EventKind::FileDrop, listener)
3483 }
3484
3485 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
3487 self.__element()
3488 .node
3489 .attrs
3490 .set_element_ref(handle.element().target());
3491 self
3492 }
3493}
3494
3495impl<C: Component> Element for ComponentElement<C> {
3496 fn node(&mut self) -> &mut ElNode {
3497 &mut self.node
3498 }
3499}
3500
3501impl<C: Component> ParentElement for ComponentElement<C> {}
3505
3506impl<C: Component> IntoElement for ComponentElement<C> {
3507 fn into_element(self) -> AnyElement {
3508 AnyElement(self.node)
3509 }
3510}
3511
3512#[cfg(test)]
3513mod file_listener_tests {
3514 use std::cell::Cell;
3515
3516 use super::*;
3517
3518 #[test]
3519 fn file_drag_enter_keeps_all_original_listener_forms() {
3520 let calls = Rc::new(Cell::new(0));
3521 let a = calls.clone();
3522 let b = calls.clone();
3523 let c = calls.clone();
3524 let d = calls.clone();
3525 let unit: Listener<()> = (move |_: &()| c.set(c.get() + 1)).into_listener();
3526 let nodes = [
3527 view().on_file_drag_enter(move || a.set(a.get() + 1)),
3528 view().on_file_drag_enter(move |_: &()| b.set(b.get() + 1)),
3529 view().on_file_drag_enter(unit),
3530 view().on_file_drag_enter(move |e: &events::FileDragEvent| {
3531 assert_eq!(e.uris, ["file:///tmp/a%20b.png"]);
3532 assert_eq!(e.mime_types, ["image/png"]);
3533 d.set(d.get() + 1);
3534 }),
3535 ];
3536 let payload = EventPayload::FileDrop(vec!["file:///tmp/a%20b.png".into()]);
3537 for mut node in nodes {
3538 let listener = node
3539 .node()
3540 .handlers
3541 .iter()
3542 .find(|(kind, _)| *kind == EventKind::FileDragEnter)
3543 .unwrap();
3544 listener.1.call(&payload);
3545 }
3546 assert_eq!(calls.get(), 4);
3547 }
3548}