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) pass_position: bool,
240 pub(crate) projected_states: u16,
243 pub(crate) projected_data: Vec<&'static str>,
246 pub(crate) projected_active: Option<&'static str>,
249 pub(crate) render: Option<super::renderer::RenderAt>,
252 pub(crate) window: Option<Box<crate::desktop::WindowOptions>>,
255 pub(crate) window_commands: Vec<crate::desktop::DesktopCommand>,
258}
259
260impl RareAttrs {
261 pub(crate) fn is_empty(&self) -> bool {
262 self.accessible.is_none()
263 && self.hint.is_none()
264 && self.description.is_none()
265 && self.value.is_none()
266 && self.src.is_none()
267 && self.inset_padding.is_none()
268 && self.inset_margin.is_none()
269 && self.drawing.is_none()
270 && self.element_ref.is_none()
271 && self.animated.is_empty()
272 && self.bound.is_empty()
273 && !self.selectable_view
274 && !self.continues_text
275 && !self.pass_position
276 && self.projected_states == 0
277 && self.projected_data.is_empty()
278 && self.projected_active.is_none()
279 && self.render.is_none()
280 && self.window.is_none()
281 }
282
283 pub(crate) fn boxed(self) -> Option<Box<Self>> {
284 (!self.is_empty()).then(|| Box::new(self))
285 }
286}
287
288#[doc(hidden)]
290#[derive(Debug, Clone, Default)]
291pub struct Attrs {
292 pub(crate) disabled: bool,
293 pub(crate) role: AccessibilityRole,
294 pub(crate) state: AccessibilityState,
295 pub(crate) pointer_events: PointerEvents,
297 pub(crate) label: Option<SharedString>,
298 pub(crate) inline: Option<std::rc::Rc<crate::StylePatch>>,
300 pub(crate) class: Option<SharedString>,
303 pub(crate) props: Vec<Prop>,
306 pub(crate) rare: Option<Box<RareAttrs>>,
307}
308
309impl PartialEq for Attrs {
310 fn eq(&self, other: &Self) -> bool {
311 self.disabled == other.disabled
312 && self.role == other.role
313 && self.state == other.state
314 && self.pointer_events == other.pointer_events
315 && self.label == other.label
316 && self.inline == other.inline
317 && self.class == other.class
318 && self.props == other.props
319 && match (&self.rare, &other.rare) {
320 (None, None) => true,
321 (Some(a), None) => a.is_empty(),
322 (None, Some(b)) => b.is_empty(),
323 (Some(a), Some(b)) => a == b,
324 }
325 }
326}
327
328impl Attrs {
329 #[inline]
330 pub(crate) fn rare_mut(&mut self) -> &mut RareAttrs {
331 self.rare.get_or_insert_with(Box::default)
332 }
333
334 #[inline]
335 pub(crate) fn animated(&self) -> &[(crate::StyleDecl, super::LiveNode)] {
336 self.rare.as_deref().map_or(&[], |r| r.animated.as_slice())
337 }
338
339 #[cfg(test)]
340 #[inline]
341 pub(crate) fn bound(&self) -> &[super::LiveNode] {
342 self.rare.as_deref().map_or(&[], |r| r.bound.as_slice())
343 }
344
345 #[inline]
346 pub(crate) fn element_ref(&self) -> Option<&super::element_ref::RefTarget> {
347 self.rare.as_ref().and_then(|r| r.element_ref.as_ref())
348 }
349
350 #[inline]
351 pub(crate) fn set_element_ref(&mut self, target: Option<super::element_ref::RefTarget>) {
352 if target.is_some() || self.rare.is_some() {
353 self.rare_mut().element_ref = target;
354 }
355 }
356
357 #[inline]
358 pub(crate) fn take_element_ref(&mut self) -> Option<super::element_ref::RefTarget> {
359 self.rare.as_mut().and_then(|r| r.element_ref.take())
360 }
361
362 #[inline]
363 pub(crate) fn insets(&self) -> (Option<EdgeInsets>, Option<EdgeInsets>) {
364 match &self.rare {
365 Some(r) => (r.inset_padding, r.inset_margin),
366 None => (None, None),
367 }
368 }
369
370 #[inline]
371 pub(crate) fn set_insets(&mut self, insets: (Option<EdgeInsets>, Option<EdgeInsets>)) {
372 if insets != (None, None) || self.rare.is_some() {
373 let r = self.rare_mut();
374 r.inset_padding = insets.0;
375 r.inset_margin = insets.1;
376 }
377 }
378
379 pub(crate) fn changes(&self, old: &Attrs, out: &mut Vec<Prop>) {
381 use AccessibilityProp as A;
382 if self.disabled != old.disabled {
383 out.push(Prop::Native(NativeProp::Disabled(self.disabled)));
384 }
385 let check_rare = self.rare.is_some() || old.rare.is_some();
386 let default_rare;
387 let (sr, or) = if check_rare {
388 default_rare = RareAttrs::default();
389 (
390 self.rare.as_deref().unwrap_or(&default_rare),
391 old.rare.as_deref().unwrap_or(&default_rare),
392 )
393 } else {
394 default_rare = RareAttrs::default();
395 (&default_rare, &default_rare)
396 };
397 if check_rare && sr.accessible != or.accessible {
398 out.push(Prop::Accessibility(A::Accessible(sr.accessible)));
399 }
400 if self.label != old.label {
401 out.push(Prop::Accessibility(A::Label(
402 self.label.as_ref().map(SharedString::to_arc),
403 )));
404 }
405 if check_rare && sr.hint != or.hint {
406 out.push(Prop::Accessibility(A::Hint(
407 sr.hint.as_ref().map(SharedString::to_arc),
408 )));
409 }
410 if check_rare && sr.description != or.description {
411 out.push(Prop::Accessibility(A::Description(
412 sr.description.as_ref().map(SharedString::to_arc),
413 )));
414 }
415 if self.role != old.role {
416 out.push(Prop::Accessibility(A::Role(self.role)));
417 }
418 if self.state != old.state {
419 out.push(Prop::Accessibility(A::State(self.state)));
420 }
421 if check_rare && sr.value != or.value {
422 out.push(Prop::Accessibility(A::Value(sr.value.clone())));
423 }
424 if self.pointer_events != old.pointer_events {
425 out.push(Prop::PointerEvents(self.pointer_events));
426 }
427 if check_rare {
428 if sr.src != or.src {
429 out.push(Prop::Source(sr.src.as_ref().map(|src| ImageSource {
430 uri: src.uri.to_arc(),
431 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
432 scales: src.scales,
433 data: src.data.clone(),
434 })));
435 }
436 if sr.inset_padding != or.inset_padding {
437 out.push(Prop::InsetPadding(sr.inset_padding.unwrap_or_default()));
438 }
439 if sr.inset_margin != or.inset_margin {
440 out.push(Prop::InsetMargin(sr.inset_margin.unwrap_or_default()));
441 }
442 if sr.selectable_view != or.selectable_view {
443 out.push(Prop::SelectableView(sr.selectable_view));
444 }
445 if sr.continues_text != or.continues_text {
446 out.push(Prop::ContinuesText(sr.continues_text));
447 }
448 if sr.pass_position != or.pass_position {
449 out.push(Prop::PassPosition(sr.pass_position));
450 }
451 if sr.projected_states != or.projected_states {
452 out.push(Prop::ProjectedStates(sr.projected_states));
453 }
454 if sr.projected_data != or.projected_data {
455 out.push(Prop::ProjectedData(sr.projected_data.as_slice().into()));
456 }
457 if sr.projected_active != or.projected_active {
458 out.push(Prop::ProjectedActive(sr.projected_active));
459 }
460 }
461 for prop in &old.props {
464 if !self.props.iter().any(|p| super::host::same_kind(p, prop))
465 && let Some(reset) = super::host::reset(prop)
466 {
467 out.push(reset);
468 }
469 }
470 for prop in &self.props {
471 if !old.props.contains(prop) {
472 out.push(prop.clone());
473 }
474 }
475 }
476}
477
478pub(crate) trait AnyProps {
480 fn as_any(&self) -> &dyn Any;
481 fn as_any_mut(&mut self) -> &mut dyn Any;
482 fn clone_box(&self) -> Box<dyn AnyProps>;
483}
484
485impl<P: Clone + 'static> AnyProps for P {
486 fn as_any(&self) -> &dyn Any {
487 self
488 }
489
490 fn as_any_mut(&mut self) -> &mut dyn Any {
491 self
492 }
493
494 fn clone_box(&self) -> Box<dyn AnyProps> {
495 Box::new(self.clone())
496 }
497}
498
499pub(crate) struct ComponentEl {
501 pub(crate) name: &'static str,
502 pub(crate) make: fn() -> Box<dyn AnyInstance>,
505 pub(crate) spec: fn() -> ComponentSpec,
507 pub(crate) props: Box<dyn AnyProps>,
508 pub(crate) on_event: Vec<Listener<dyn Any>>,
510 pub(crate) by_name: Option<std::any::TypeId>,
514}
515
516impl Clone for ComponentEl {
517 fn clone(&self) -> Self {
518 Self {
519 name: self.name,
520 make: self.make,
521 spec: self.spec,
522 props: self.props.clone_box(),
523 on_event: self.on_event.clone(),
524 by_name: self.by_name,
525 }
526 }
527}
528
529pub(crate) type PlaceFn = Rc<dyn Fn(Child, Position) -> AnyElement>;
531
532#[derive(Clone, Copy)]
538pub struct Position {
539 index: super::reactive::Node,
540 count: super::reactive::Node,
541 rows: Option<super::reactive::Node>,
546}
547
548impl Position {
549 pub(crate) fn of(index: super::reactive::Node, count: super::reactive::Node) -> Self {
552 Self {
553 index,
554 count,
555 rows: None,
556 }
557 }
558
559 pub(crate) fn of_row(
562 index: super::reactive::Node,
563 count: super::reactive::Node,
564 rows: Option<super::reactive::Node>,
565 ) -> Self {
566 Self { index, count, rows }
567 }
568
569 pub(crate) fn fixed(index: usize, count: usize) -> Self {
571 Self::of(super::signal(index).node(), super::signal(count).node())
572 }
573
574 #[track_caller]
576 pub fn index(&self) -> usize {
577 if let Some(rows) = self.rows
578 && rows.is_outdated()
579 {
580 let before = self.index.with_untracked("a position", |i: &usize| *i);
581 rows.bring_up_to_date();
582 if !self.index.is_live() {
586 return before;
587 }
588 }
589 self.index.with("a position", |i: &usize| *i)
590 }
591
592 #[track_caller]
594 pub fn count(&self) -> usize {
595 if let Some(rows) = self.rows {
596 rows.bring_up_to_date();
597 }
598 self.count.with("a position", |n: &usize| *n)
599 }
600
601 #[track_caller]
603 pub fn is_first(&self) -> bool {
604 self.index() == 0
605 }
606
607 #[track_caller]
609 pub fn is_last(&self) -> bool {
610 self.index() + 1 == self.count()
611 }
612}
613
614impl fmt::Debug for Position {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 let (index, count) = super::untracked(|| (self.index(), self.count()));
617 write!(f, "Position({index} of {count})")
618 }
619}
620
621#[doc(hidden)]
624#[derive(Debug, Clone, Copy, Default, PartialEq)]
625pub struct ListConfig {
626 pub(crate) estimated: Option<f32>,
627 pub(crate) columns: Option<u32>,
628 pub(crate) horizontal: Option<bool>,
629 pub(crate) inverted: Option<bool>,
630 pub(crate) scrollbar_visible: Option<bool>,
631 pub(crate) content: Option<ListContentStyle>,
632 pub(crate) follow_end: Option<f32>,
633 pub(crate) follow_end_animated: Option<bool>,
634 pub(crate) alignment: Option<crate::ListAlignment>,
635 pub(crate) viewport: Option<crate::ListViewport>,
636}
637
638impl ListConfig {
639 pub(crate) fn changes(&self, old: &ListConfig, out: &mut Vec<Prop>) {
641 if self.estimated != old.estimated {
642 out.push(Prop::EstimatedItemSize(Points(
643 self.estimated.unwrap_or(50.0),
644 )));
645 }
646 if self.columns != old.columns {
647 out.push(Prop::Columns(self.columns.unwrap_or(1)));
648 }
649 if self.horizontal != old.horizontal {
650 out.push(Prop::Horizontal(self.horizontal.unwrap_or(false)));
651 }
652 if self.inverted != old.inverted {
653 out.push(Prop::Inverted(self.inverted.unwrap_or(false)));
654 }
655 if self.scrollbar_visible != old.scrollbar_visible {
656 out.push(Prop::Scrollbar(
657 self.scrollbar_visible.unwrap_or(true).into(),
658 ));
659 }
660 if self.content != old.content {
661 out.push(Prop::ListContent(self.content.unwrap_or_default()));
662 }
663 if self.follow_end != old.follow_end || self.follow_end_animated != old.follow_end_animated
664 {
665 out.push(Prop::FollowEnd(
666 self.follow_end.map(Points),
667 self.follow_end_animated.unwrap_or(false),
668 ));
669 }
670 if self.alignment != old.alignment {
671 out.push(Prop::ListAlignment(self.alignment.unwrap_or_default()));
672 }
673 if self.viewport != old.viewport {
674 out.push(Prop::ListViewport(self.viewport.unwrap_or_default()));
675 }
676 }
677}
678
679#[derive(Clone)]
681pub(crate) struct ListEl {
682 pub(crate) name: &'static str,
683 pub(crate) config: ListConfig,
684 pub(crate) row: PlaceFn,
685}
686
687#[derive(Clone)]
689pub(crate) enum ElKind {
690 Plain,
691 Slot(&'static str),
693 Fill(&'static str),
696 Tooltip,
700 Filled(&'static str),
703 Children,
705 JsChild(NodeId),
707 EachChild(PlaceFn),
709 List(Box<ListEl>),
711 VirtualList(Box<super::virtual_list::VirtualListEl>),
713 Raw,
716 Component(ComponentEl),
717 Region(super::flow::Region),
721}
722
723#[doc(hidden)]
725#[derive(Clone)]
726pub struct ElNode {
727 pub(crate) tag: Tag,
728 pub(crate) key: Option<SharedString>,
729 pub(crate) text: Option<SharedString>,
731 pub(crate) attrs: Attrs,
732 pub(crate) style: StyleRefinement,
733 pub(crate) handlers: Vec<(EventKind, Listener<EventPayload>)>,
734 pub(crate) responder: Option<Rc<super::responder::ResponderEl>>,
736 pub(crate) children: Vec<ElNode>,
737 pub(crate) kind: ElKind,
738 pub(crate) bound_text: Option<Rc<dyn Fn() -> SharedString>>,
740 pub(crate) bound_attrs: Vec<BoundAttrs>,
742 pub(crate) bound_list: Vec<BoundListConfig>,
744}
745
746#[doc(hidden)]
748pub type BoundListConfig = Rc<dyn Fn(&mut ListConfig)>;
749
750crate::static_reactive!(AccessibilityState: AccessibilityState);
751crate::static_reactive!(EdgeInsets: EdgeInsets);
752crate::static_reactive!(Style: Style);
753crate::static_reactive!(PointerEvents: PointerEvents);
754crate::static_reactive!(KeyCapture: KeyCapture);
755
756pub(crate) type BoundAttrs = Rc<dyn Fn(&mut Attrs)>;
758
759impl ElNode {
760 pub(crate) fn bind_attr<T: 'static>(
763 &mut self,
764 value: impl IntoReactive<T>,
765 apply: impl Fn(&mut Attrs, T) + 'static,
766 ) {
767 match value.into_reactive() {
768 Reactive::Static(v) => apply(&mut self.attrs, v),
769 Reactive::Bound(f) => self.bound_attrs.push(Rc::new(move |a| apply(a, f()))),
770 }
771 }
772
773 pub(crate) fn is_bound(&self) -> bool {
775 self.bound_text.is_some()
776 || !self.bound_attrs.is_empty()
777 || self.style.is_bound()
778 || !self.bound_list.is_empty()
779 }
780
781 pub(crate) fn resolved_attrs(&self) -> Attrs {
784 let mut attrs = self.attrs.clone();
785 for part in &self.bound_attrs {
786 part(&mut attrs);
787 }
788 attrs
789 }
790
791 pub(crate) fn resolve_once(&mut self) {
794 if !self.is_bound() {
795 return;
796 }
797 super::untracked(|| {
798 if let Some(text) = self.bound_text.take() {
799 self.text = Some(text());
800 }
801 if !self.bound_attrs.is_empty() {
802 self.attrs = self.resolved_attrs();
803 self.bound_attrs.clear();
804 }
805 if self.style.is_bound() {
806 self.style = self.style.resolved();
807 }
808 let parts = std::mem::take(&mut self.bound_list);
809 if let Some(config) = self.list_config() {
810 for part in &parts {
811 part(config);
812 }
813 }
814 });
815 }
816
817 pub(crate) fn list_config(&mut self) -> Option<&mut ListConfig> {
819 match &mut self.kind {
820 ElKind::List(list) => Some(&mut list.config),
821 ElKind::VirtualList(list) => Some(&mut list.config),
822 _ => None,
823 }
824 }
825
826 pub(crate) fn empty_view() -> Self {
828 Self::new(Tag::View)
829 }
830
831 pub(crate) fn new(tag: Tag) -> Self {
832 Self {
833 tag,
834 key: None,
835 text: None,
836 attrs: Attrs::default(),
837 style: StyleRefinement::default(),
838 handlers: Vec::new(),
839 responder: None,
840 children: Vec::new(),
841 kind: ElKind::Plain,
842 bound_text: None,
843 bound_attrs: Vec::new(),
844 bound_list: Vec::new(),
845 }
846 }
847}
848
849pub struct AnyElement(pub(crate) ElNode);
851
852pub trait IntoElement {
854 fn into_element(self) -> AnyElement;
856}
857
858impl IntoElement for AnyElement {
859 fn into_element(self) -> AnyElement {
860 self
861 }
862}
863
864impl IntoElement for SharedString {
865 fn into_element(self) -> AnyElement {
866 text(self).into_element()
867 }
868}
869
870impl IntoElement for &'static str {
871 fn into_element(self) -> AnyElement {
872 text(self).into_element()
873 }
874}
875
876impl IntoElement for String {
877 fn into_element(self) -> AnyElement {
878 text(self).into_element()
879 }
880}
881
882#[diagnostic::on_unimplemented(
888 message = "`{Self}` is not an element",
889 label = "not an element",
890 note = "elements are host elements (`view()`, `text(..)`, ...), components' elements, strings, and an `Option`, a `Vec`, an array or an iterator of elements"
891)]
892pub trait IntoChild<M> {
893 #[doc(hidden)]
895 fn __push_into(self, out: &mut Vec<ElNode>);
896}
897
898#[doc(hidden)]
900pub struct OneChild(());
901
902#[doc(hidden)]
904pub struct ManyChildren(());
905
906impl<T: IntoElement> IntoChild<OneChild> for T {
907 fn __push_into(self, out: &mut Vec<ElNode>) {
908 out.push(self.into_element().0);
909 }
910}
911
912impl<I: IntoIterator> IntoChild<ManyChildren> for I
913where
914 I::Item: IntoElement,
915{
916 fn __push_into(self, out: &mut Vec<ElNode>) {
917 out.extend(self.into_iter().map(|c| c.into_element().0));
918 }
919}
920
921pub trait FluentBuilder: Sized {
925 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
927 if condition { then(self) } else { self }
928 }
929
930 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
932 match option {
933 Some(v) => then(self, v),
934 None => self,
935 }
936 }
937
938 fn map(self, f: impl FnOnce(Self) -> Self) -> Self {
940 f(self)
941 }
942}
943
944impl<T: Element> FluentBuilder for T {}
945
946pub trait Element: IntoElement + Sized {
950 #[doc(hidden)]
951 fn node(&mut self) -> &mut ElNode;
952
953 fn key(mut self, key: impl Into<SharedString>) -> Self {
956 self.node().key = Some(key.into());
957 self
958 }
959
960 fn bind_opacity(self, value: &impl super::Animated) -> Self {
962 self.bind(crate::animation::AnimationProp::Opacity, value)
963 }
964
965 fn bind_background(self, value: &impl super::Animated) -> Self {
968 self.bind(crate::animation::AnimationProp::BackgroundColor, value)
969 }
970
971 fn bind_border_color(self, value: &impl super::Animated) -> Self {
973 self.bind(crate::animation::AnimationProp::BorderColor, value)
974 }
975
976 fn bind_color(self, value: &impl super::Animated) -> Self {
978 self.bind(crate::animation::AnimationProp::Color, value)
979 }
980
981 fn bind(mut self, prop: crate::animation::AnimationProp, value: &impl super::Animated) -> Self {
984 if let Some(node) = value.animated_node().live() {
985 let decl = crate::StyleDecl::Animated(prop, node.id());
986 self.node().attrs.rare_mut().animated.push((decl, node));
987 }
988 self
989 }
990
991 fn bind_sticky_top(self, value: &impl super::Animated) -> Self {
996 self.bind(crate::animation::AnimationProp::StickyTop, value)
997 }
998
999 fn bind_sticky_left(self, value: &impl super::Animated) -> Self {
1001 self.bind(crate::animation::AnimationProp::StickyLeft, value)
1002 }
1003
1004 fn bind_transform(mut self, kind: crate::TransformKind, value: &impl super::Animated) -> Self {
1007 if let Some(node) = value.animated_node().live() {
1008 let decl = crate::StyleDecl::Transform(kind, kind.identity(), Some(node.id()));
1009 self.node().attrs.rare_mut().animated.push((decl, node));
1010 }
1011 self
1012 }
1013
1014 fn bind_motion(self, motion: &super::Motion) -> Self {
1018 use crate::animation::MotionChannel::*;
1019 let mut this = self.bind_opacity(&motion.value(Opacity));
1020 for channel in [TranslateX, TranslateY, Rotate, RotateX, RotateY] {
1021 if let Some(kind) = channel.transform() {
1022 this = this.bind_transform(kind, &motion.value(channel));
1023 }
1024 }
1025 let scale = motion.value(Scale);
1026 this.bind_transform(
1027 crate::TransformKind::ScaleX,
1028 &scale.mul(&motion.value(ScaleX)),
1029 )
1030 .bind_transform(
1031 crate::TransformKind::ScaleY,
1032 &scale.mul(&motion.value(ScaleY)),
1033 )
1034 }
1035
1036 fn bind_translate_x(self, value: &impl super::Animated) -> Self {
1038 self.bind_transform(crate::TransformKind::TranslateX, value)
1039 }
1040
1041 fn bind_translate_y(self, value: &impl super::Animated) -> Self {
1043 self.bind_transform(crate::TransformKind::TranslateY, value)
1044 }
1045
1046 fn bind_scale(self, value: &impl super::Animated) -> Self {
1048 self.bind_transform(crate::TransformKind::Scale, value)
1049 }
1050
1051 fn bind_rotate(self, value: &impl super::Animated) -> Self {
1053 self.bind_transform(crate::TransformKind::Rotate, value)
1054 }
1055
1056 fn element_ref(mut self, handle: &super::ElementRef) -> Self {
1059 self.node().attrs.set_element_ref(handle.target());
1060 self
1061 }
1062
1063 fn inset_padding(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1066 self.node().bind_attr(insets, |a, insets| {
1067 a.rare_mut().inset_padding = Some(insets)
1068 });
1069 self
1070 }
1071
1072 fn inset_margin(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
1074 self.node()
1075 .bind_attr(insets, |a, insets| a.rare_mut().inset_margin = Some(insets));
1076 self
1077 }
1078
1079 fn inline_style(mut self, style: impl IntoReactive<Style>) -> Self {
1082 Style::apply(self.node(), style, Variant::default(), |a, patch| {
1083 a.inline = patch
1084 });
1085 self
1086 }
1087
1088 fn state_inline_style(mut self, style: impl Fn() -> Style + 'static) -> Self {
1093 Style::apply_bound(
1094 self.node(),
1095 Rc::new(style),
1096 Variant::default(),
1097 true,
1098 |a, patch| a.inline = patch,
1099 );
1100 self
1101 }
1102
1103 fn selectable(mut self, area: impl IntoReactive<bool>) -> Self {
1108 self.node().bind_attr(area, |a, area| {
1109 if area || a.rare.is_some() {
1110 a.rare_mut().selectable_view = area;
1111 }
1112 });
1113 self
1114 }
1115
1116 fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
1123 super::host::bind_prop(self.node(), color, |c: Hsla| {
1124 Prop::SelectionColor(Some(Color::from(c)))
1125 });
1126 self
1127 }
1128
1129 fn selection_menu(mut self, items: impl IntoReactive<Vec<super::desktop::MenuItem>>) -> Self {
1150 super::host::bind_prop(self.node(), items, |items| {
1151 Prop::SelectionMenu(super::desktop::register_selection_menu(items))
1152 });
1153 self
1154 }
1155
1156 fn continues_text(mut self, continues: impl IntoReactive<bool>) -> Self {
1164 self.node().bind_attr(continues, |a, continues| {
1165 if continues || a.rare.is_some() {
1166 a.rare_mut().continues_text = continues;
1167 }
1168 });
1169 self
1170 }
1171
1172 #[doc(hidden)]
1180 fn __pass_position(mut self, pass: impl IntoReactive<bool>) -> Self {
1181 self.node().bind_attr(pass, |a, pass| {
1182 if pass || a.rare.is_some() {
1183 a.rare_mut().pass_position = pass;
1184 }
1185 });
1186 self
1187 }
1188
1189 fn copy_text(mut self, text: impl IntoReactive<SharedString>) -> Self {
1204 super::host::bind_prop(self.node(), text, |text: SharedString| {
1205 Prop::CopyText(Some(text.to_arc()))
1206 });
1207 self
1208 }
1209
1210 #[doc(hidden)]
1215 fn clears_keyboard(mut self, clears: impl IntoReactive<bool>) -> Self {
1216 super::host::bind_prop(self.node(), clears, Prop::ClearsKeyboard);
1217 self
1218 }
1219
1220 fn app_class(mut self, class: impl IntoReactive<Option<SharedString>>) -> Self {
1225 self.node().bind_attr(class, |a, class| a.class = class);
1226 self
1227 }
1228}
1229
1230#[derive(Debug, Clone, Default, PartialEq)]
1244pub struct Style(
1245 pub(crate) Option<std::rc::Rc<crate::StylePatch>>,
1246 pub(crate) StyleRefinement,
1249);
1250
1251impl Style {
1252 pub fn from_decls(decls: impl IntoIterator<Item = crate::StyleDecl>) -> Self {
1256 let mut style = crate::Style::default();
1257 let mut patch = crate::StylePatch::default();
1258 for decl in decls {
1259 let key = match &decl {
1260 crate::StyleDecl::Set(key, _) => Some(*key),
1261 _ => None,
1262 };
1263 if patch.push(&mut style, decl).is_err()
1264 && let Some(key) = key
1265 {
1266 log::warn!("invalid value for style `{}`", key.name());
1267 }
1268 }
1269 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1270 }
1271
1272 pub fn with(self, key: crate::StyleKey, value: crate::PropertyValue) -> Self {
1275 let decls = self.0.iter().flat_map(|p| p.decls().iter().cloned());
1276 let mut style = Self::from_decls(decls.chain([crate::StyleDecl::Set(key, value)]));
1277 style.1 = self.1;
1278 style
1279 }
1280
1281 pub fn then(&self, over: &Style) -> Self {
1285 if over.0.is_none() && over.1.is_empty() {
1286 return self.clone();
1287 }
1288 if self.0.is_none() && self.1.is_empty() {
1289 return over.clone();
1290 }
1291 let mut style = if self.0.is_none() {
1292 Self(over.0.clone(), StyleRefinement::default())
1293 } else if over.0.is_none() {
1294 Self(self.0.clone(), StyleRefinement::default())
1295 } else {
1296 Self::from_decls(self.decls().iter().chain(over.decls()).cloned())
1297 };
1298 let mut typed = self.1.clone();
1299 typed.extend_as(Variant::default(), over.1.clone());
1300 style.1 = typed;
1301 style
1302 }
1303
1304 pub fn background_color(&self) -> Option<crate::element::AdaptiveColor> {
1310 let typed = self.1.static_color(crate::StyleKey::BackgroundColor);
1311 let declared = || {
1312 self.decls().iter().rev().find_map(|decl| match decl {
1313 crate::StyleDecl::Set(
1314 crate::StyleKey::BackgroundColor,
1315 crate::PropertyValue::Color(color),
1316 ) => Some(color.map(crate::element::AdaptiveColor::from)),
1317 _ => None,
1318 })?
1319 };
1320 typed
1321 .or_else(declared)
1322 .filter(|c| *c != crate::element::AdaptiveColor::from(crate::Color::TRANSPARENT))
1323 }
1324
1325 #[doc(hidden)]
1331 pub fn max_height_at_most(&self, cap: Points, basis: Points) -> Self {
1332 use taffy::CompactLength;
1333 let declared = self.decls().iter().rev().find_map(|decl| match decl {
1334 crate::StyleDecl::Set(crate::StyleKey::MaxHeight, crate::PropertyValue::Lpa(v)) => {
1335 let raw = v.into_raw();
1336 Some(match raw.tag() {
1337 CompactLength::LENGTH_TAG => Some(raw.value()),
1338 CompactLength::PERCENT_TAG => Some(basis.0 * raw.value()),
1339 _ => None,
1340 })
1341 }
1342 _ => None,
1343 });
1344 if declared.flatten().is_some_and(|height| height <= cap.0) {
1345 return self.clone();
1346 }
1347 self.clone().with(
1348 crate::StyleKey::MaxHeight,
1349 crate::PropertyValue::Lpa(taffy::LengthPercentageAuto::length(cap.0.max(0.0))),
1350 )
1351 }
1352
1353 pub fn decls(&self) -> &[crate::StyleDecl] {
1355 self.0.as_deref().map_or(&[], crate::StylePatch::decls)
1356 }
1357
1358 pub fn is_typed(&self) -> bool {
1364 !self.1.is_empty()
1365 }
1366
1367 pub(crate) fn apply(
1373 node: &mut ElNode,
1374 style: impl IntoReactive<Style>,
1375 variant: Variant,
1376 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1377 ) {
1378 match style.into_reactive() {
1379 Reactive::Static(Style(patch, typed)) => {
1380 attr(&mut node.attrs, patch);
1381 if !typed.is_empty() {
1382 node.style.extend_as(variant, typed);
1383 }
1384 }
1385 Reactive::Bound(f) => Self::apply_bound(node, f, variant, false, attr),
1386 }
1387 }
1388
1389 pub(crate) fn apply_bound(
1392 node: &mut ElNode,
1393 f: Rc<dyn Fn() -> Style>,
1394 variant: Variant,
1395 typed_later: bool,
1396 attr: impl Fn(&mut Attrs, Option<std::rc::Rc<crate::StylePatch>>) + 'static,
1397 ) {
1398 let typed = typed_later || super::untracked(|| !f().1.is_empty());
1399 let patch = f.clone();
1400 node.bind_attr(move || patch().0, attr);
1401 if typed {
1402 node.style
1405 .bind(move |s| s.extend_as(variant, f().1.resolved()));
1406 }
1407 }
1408}
1409
1410impl From<crate::StylePatch> for Style {
1411 fn from(patch: crate::StylePatch) -> Self {
1412 Self(Some(std::rc::Rc::new(patch)), StyleRefinement::default())
1413 }
1414}
1415
1416impl From<StyleRefinement> for Style {
1417 fn from(style: StyleRefinement) -> Self {
1418 Self(None, style)
1419 }
1420}
1421
1422impl JsValue for Style {
1423 fn ts_type(_types: &mut super::TsTypes) -> String {
1424 "StyleProp<ViewStyle>".into()
1425 }
1426
1427 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1430 if value.is_nullish() {
1431 return Ok(Self::default());
1432 }
1433 Ok(Self::from(value.host().style(value.raw())?))
1434 }
1435
1436 fn to_js<'a>(&self, _host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1438 Err(PropError("a style does not convert back to JS".to_owned()))
1439 }
1440}
1441
1442#[derive(Debug, Clone, Default, PartialEq)]
1450#[non_exhaustive]
1451pub struct TextPartStyle(pub Style);
1452
1453impl From<Style> for TextPartStyle {
1454 fn from(style: Style) -> Self {
1455 Self(style)
1456 }
1457}
1458
1459impl From<StyleRefinement> for TextPartStyle {
1460 fn from(style: StyleRefinement) -> Self {
1461 Self(Style::from(style))
1462 }
1463}
1464
1465impl From<TextPartStyle> for Style {
1466 fn from(style: TextPartStyle) -> Self {
1467 style.0
1468 }
1469}
1470
1471impl JsValue for TextPartStyle {
1472 fn ts_type(_types: &mut super::TsTypes) -> String {
1473 "StyleProp<TextStyle>".into()
1474 }
1475
1476 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1477 Style::from_js(value).map(Self)
1478 }
1479
1480 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1481 self.0.to_js(host)
1482 }
1483}
1484
1485#[derive(Debug, Clone, Default, PartialEq)]
1491#[non_exhaustive]
1492pub struct InputPartStyle(pub Style);
1493
1494impl From<Style> for InputPartStyle {
1495 fn from(style: Style) -> Self {
1496 Self(style)
1497 }
1498}
1499
1500impl From<StyleRefinement> for InputPartStyle {
1501 fn from(style: StyleRefinement) -> Self {
1502 Self(Style::from(style))
1503 }
1504}
1505
1506impl From<InputPartStyle> for Style {
1507 fn from(style: InputPartStyle) -> Self {
1508 style.0
1509 }
1510}
1511
1512impl JsValue for InputPartStyle {
1513 fn ts_type(_types: &mut super::TsTypes) -> String {
1514 "StyleProp<InputStyle>".into()
1515 }
1516
1517 fn from_js(value: super::JsIn<'_>) -> Result<Self, PropError> {
1518 Style::from_js(value).map(Self)
1519 }
1520
1521 fn to_js<'a>(&self, host: &'a dyn super::JsHost) -> Result<super::JsOwned<'a>, PropError> {
1522 self.0.to_js(host)
1523 }
1524}
1525
1526impl<T: Element> Styled for T {
1527 fn style(&mut self) -> &mut StyleRefinement {
1528 &mut self.node().style
1529 }
1530}
1531
1532pub trait ParentElement: Element {
1534 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
1537 child.__push_into(&mut self.node().children);
1538 self
1539 }
1540
1541 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
1543 self.node()
1544 .children
1545 .extend(children.into_iter().map(|c| c.into_element().0));
1546 self
1547 }
1548
1549 fn slot(mut self, slot: Option<Slot>, place: impl FnOnce(SlotElement) -> SlotElement) -> Self {
1552 if let Some(slot) = slot {
1553 let mut node = ElNode::new(Tag::View);
1554 node.kind = ElKind::Slot(slot.name);
1555 self.node().children.push(place(SlotElement(node)).0);
1556 }
1557 self
1558 }
1559
1560 fn children_each<R: IntoElement>(
1563 mut self,
1564 children: impl Into<Children>,
1565 place: impl Fn(Child, Position) -> R + 'static,
1566 ) -> Self {
1567 let _ = children.into();
1568 let mut node = ElNode::new(Tag::View);
1569 node.kind = ElKind::EachChild(Rc::new(move |child, at| place(child, at).into_element()));
1570 self.node().children.push(node);
1571 self
1572 }
1573
1574 fn list<R: IntoElement>(
1580 mut self,
1581 items: Items,
1582 config: impl FnOnce(ListElement) -> ListElement,
1583 row: impl Fn(Child, Position) -> R + 'static,
1584 ) -> Self {
1585 let mut node = ElNode::new(Tag::List);
1586 node.kind = ElKind::List(Box::new(ListEl {
1587 name: items.name,
1588 config: ListConfig::default(),
1589 row: Rc::new(move |content, at| row(content, at).into_element()),
1590 }));
1591 self.node().children.push(config(ListElement(node)).0);
1592 self
1593 }
1594}
1595
1596pub trait Accessible: Element {
1598 fn accessible(mut self, accessible: impl IntoReactive<bool>) -> Self {
1600 self.node().bind_attr(accessible, |a, accessible| {
1601 a.rare_mut().accessible = Some(accessible)
1602 });
1603 self
1604 }
1605
1606 fn label(mut self, label: impl IntoReactive<SharedString>) -> Self {
1608 self.node()
1609 .bind_attr(label, |a, label| a.label = Some(label));
1610 self
1611 }
1612
1613 fn optional_label(mut self, label: impl IntoReactive<Option<SharedString>>) -> Self {
1616 self.node().bind_attr(label, |a, label| a.label = label);
1617 self
1618 }
1619
1620 fn hint(mut self, hint: impl IntoReactive<SharedString>) -> Self {
1622 self.node()
1623 .bind_attr(hint, |a, hint| a.rare_mut().hint = Some(hint));
1624 self
1625 }
1626
1627 fn optional_hint(mut self, hint: impl IntoReactive<Option<SharedString>>) -> Self {
1630 self.node().bind_attr(hint, |a, hint| {
1631 if hint.is_some() || a.rare.is_some() {
1632 a.rare_mut().hint = hint;
1633 }
1634 });
1635 self
1636 }
1637
1638 fn accessibility_description(mut self, description: impl IntoReactive<SharedString>) -> Self {
1642 self.node().bind_attr(description, |a, description| {
1643 a.rare_mut().description = Some(description)
1644 });
1645 self
1646 }
1647
1648 fn optional_accessibility_description(
1652 mut self,
1653 description: impl IntoReactive<Option<SharedString>>,
1654 ) -> Self {
1655 self.node().bind_attr(description, |a, description| {
1656 if description.is_some() || a.rare.is_some() {
1657 a.rare_mut().description = description;
1658 }
1659 });
1660 self
1661 }
1662
1663 fn role(mut self, role: impl IntoReactive<AccessibilityRole>) -> Self {
1665 self.node().bind_attr(role, |a, role| a.role = role);
1666 self
1667 }
1668
1669 fn accessibility_state(mut self, state: impl IntoReactive<AccessibilityState>) -> Self {
1672 self.node().bind_attr(state, |a, state| {
1673 a.state = AccessibilityState {
1674 disabled: a.state.disabled,
1675 ..state
1676 };
1677 });
1678 self
1679 }
1680
1681 fn accessibility_level(mut self, level: impl IntoReactive<u32>) -> Self {
1685 self.node().bind_attr(level, |a, level| {
1686 super::host::set_in(
1687 &mut a.props,
1688 Prop::Accessibility(AccessibilityProp::Level((level > 0).then_some(level))),
1689 )
1690 });
1691 self
1692 }
1693
1694 fn accessibility_orientation(mut self, orientation: impl IntoReactive<Option<Axis>>) -> Self {
1699 self.node().bind_attr(orientation, |a, orientation| {
1700 super::host::set_in(
1701 &mut a.props,
1702 Prop::Accessibility(AccessibilityProp::Orientation(orientation)),
1703 )
1704 });
1705 self
1706 }
1707
1708 fn accessibility_live_region(mut self, region: impl IntoReactive<LiveRegion>) -> Self {
1713 self.node().bind_attr(region, |a, region| {
1714 super::host::set_in(
1715 &mut a.props,
1716 Prop::Accessibility(AccessibilityProp::LiveRegion(region)),
1717 )
1718 });
1719 self
1720 }
1721
1722 fn accessibility_active_descendant(
1730 mut self,
1731 target: impl IntoReactive<Option<super::ElementRef>>,
1732 ) -> Self {
1733 self.node()
1734 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1735 super::host::set_in(
1736 &mut a.props,
1737 Prop::Accessibility(AccessibilityProp::ActiveDescendant(
1738 target.and_then(|t| t.element_target()),
1739 )),
1740 )
1741 });
1742 self
1743 }
1744
1745 fn accessibility_controls(
1749 mut self,
1750 target: impl IntoReactive<Option<super::ElementRef>>,
1751 ) -> Self {
1752 self.node()
1753 .bind_attr(target, |a, target: Option<super::ElementRef>| {
1754 super::host::set_in(
1755 &mut a.props,
1756 Prop::Accessibility(AccessibilityProp::Controls(
1757 target.and_then(|t| t.element_target()),
1758 )),
1759 )
1760 });
1761 self
1762 }
1763
1764 fn accessibility_described_by(
1771 self,
1772 target: impl IntoReactive<Option<super::ElementRef>>,
1773 ) -> Self {
1774 let target = target.into_reactive();
1775 self.accessibility_described_by_target(move || {
1776 target.get().and_then(|t| t.element_target())
1777 })
1778 }
1779
1780 #[doc(hidden)]
1784 fn accessibility_described_by_target(
1785 mut self,
1786 target: impl IntoReactive<Option<super::ElementTarget>>,
1787 ) -> Self {
1788 self.node()
1789 .bind_attr(target, |a, target: Option<super::ElementTarget>| {
1790 if target.is_none() {
1795 a.props.retain(|p| {
1796 !matches!(p, Prop::Accessibility(AccessibilityProp::DescribedBy(_)))
1797 });
1798 return;
1799 }
1800 super::host::set_in(
1801 &mut a.props,
1802 Prop::Accessibility(AccessibilityProp::DescribedBy(target)),
1803 )
1804 });
1805 self
1806 }
1807
1808 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
1812 self.node().bind_attr(value, |a, value| {
1813 if value.is_some() || a.rare.is_some() {
1814 a.rare_mut().value = value;
1815 }
1816 });
1817 self
1818 }
1819
1820 fn accessibility_elements_hidden(mut self, hidden: impl IntoReactive<bool>) -> Self {
1826 self.node().bind_attr(hidden, |a, hidden| {
1827 super::host::set_in(
1828 &mut a.props,
1829 Prop::Accessibility(AccessibilityProp::Hidden(hidden)),
1830 )
1831 });
1832 self
1833 }
1834
1835 fn accessibility_actions(
1843 mut self,
1844 actions: impl IntoReactive<Vec<crate::AccessibilityActionDef>>,
1845 ) -> Self {
1846 self.node().bind_attr(actions, |a, actions| {
1847 super::host::set_in(
1848 &mut a.props,
1849 Prop::Accessibility(AccessibilityProp::Actions(actions)),
1850 )
1851 });
1852 self
1853 }
1854}
1855
1856pub trait IntoTooltip {
1859 #[doc(hidden)]
1860 fn apply_tooltip(self, node: &mut ElNode);
1861}
1862
1863impl IntoTooltip for AnyElement {
1864 fn apply_tooltip(self, node: &mut ElNode) {
1865 let mut hint = ElNode::new(Tag::Overlay);
1867 hint.key = Some("tooltip".into());
1868 hint.attrs.pointer_events = PointerEvents::None;
1869 let gap = Points(4.0);
1870 for prop in [
1871 crate::OverlayProp::Hint(Some(crate::overlay::HINT_DELAY)),
1872 crate::OverlayProp::Placement(crate::overlay::Placement::Top),
1873 crate::OverlayProp::Offset(gap),
1874 crate::OverlayProp::Margin(gap),
1875 ] {
1876 super::host::set(&mut hint, Prop::Overlay(prop));
1877 }
1878 hint.children.push(self.0);
1879 node.children.push(hint);
1880 }
1881}
1882
1883impl<C: Component> IntoTooltip for ComponentElement<C> {
1884 fn apply_tooltip(self, node: &mut ElNode) {
1885 self.into_element().apply_tooltip(node);
1886 }
1887}
1888
1889#[doc(hidden)]
1894pub fn __hint_tooltip(node: &mut ElNode, hint: AnyElement) {
1895 let mut hint = hint.0;
1896 hint.key = Some("tooltip".into());
1897 node.children.push(hint);
1898}
1899
1900struct GivenHost(ElNode);
1904
1905impl Element for GivenHost {
1906 fn node(&mut self) -> &mut ElNode {
1907 &mut self.0
1908 }
1909}
1910
1911impl IntoElement for GivenHost {
1912 fn into_element(self) -> AnyElement {
1913 AnyElement(self.0)
1914 }
1915}
1916
1917impl Accessible for GivenHost {}
1918impl Interactive for GivenHost {}
1919
1920fn give_host(node: &mut ElNode, set: impl FnOnce(GivenHost) -> GivenHost) {
1923 let taken = std::mem::replace(node, ElNode::new(Tag::View));
1924 *node = set(GivenHost(taken)).0;
1925}
1926
1927fn give_tooltip(node: &mut ElNode, tooltip: impl IntoTooltip) {
1931 let mut given = ElNode::new(Tag::View);
1932 given.kind = ElKind::Tooltip;
1933 tooltip.apply_tooltip(&mut given);
1934 node.children.retain(|c| !matches!(c.kind, ElKind::Tooltip));
1935 node.children.push(given);
1936}
1937
1938pub trait Interactive: Element {
1940 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
1946 tooltip.apply_tooltip(self.node());
1947 self
1948 }
1949
1950 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
1954 self.on(
1955 EventKind::FileDragEnter,
1956 events::typed(listener.into_listener(), events::file_drag),
1957 )
1958 }
1959
1960 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
1962 self.on(
1963 EventKind::FileDragLeave,
1964 events::typed(listener.into_listener(), events::unit),
1965 )
1966 }
1967
1968 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
1970 self.on(
1971 EventKind::FileDrop,
1972 events::typed(listener.into_listener(), events::file_drop),
1973 )
1974 }
1975
1976 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1979 self.on(
1980 EventKind::MouseEnter,
1981 events::typed(listener.into_listener(), events::mouse),
1982 )
1983 }
1984
1985 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1988 self.on(
1989 EventKind::MouseLeave,
1990 events::typed(listener.into_listener(), events::mouse),
1991 )
1992 }
1993
1994 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
1999 self.on(
2000 EventKind::MouseMove,
2001 events::typed(listener.into_listener(), events::mouse),
2002 )
2003 }
2004
2005 fn on_wheel<M>(self, listener: impl IntoListener<WheelEvent, M>) -> Self {
2013 self.on(
2014 EventKind::Wheel,
2015 events::typed(listener.into_listener(), events::wheel),
2016 )
2017 }
2018
2019 fn on_pinch<M>(self, listener: impl IntoListener<PinchEvent, M>) -> Self {
2030 self.on(
2031 EventKind::Pinch,
2032 events::typed(listener.into_listener(), events::touchpad_pinch),
2033 )
2034 }
2035
2036 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
2041 self.on(
2042 EventKind::MouseUp,
2043 events::typed(listener.into_listener(), events::mouse),
2044 )
2045 }
2046
2047 fn on_key_down<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
2055 self.on(
2056 EventKind::KeyDown,
2057 events::typed(listener.into_listener(), events::key_event),
2058 )
2059 }
2060
2061 fn on_key_up<M>(self, listener: impl IntoListener<KeyEvent, M>) -> Self {
2067 self.on(
2068 EventKind::KeyUp,
2069 events::typed(listener.into_listener(), events::key_event),
2070 )
2071 }
2072
2073 fn capture_keys(mut self, capture: impl IntoReactive<KeyCapture>) -> Self {
2081 super::host::bind_prop(self.node(), capture, Prop::KeyCapture);
2082 self
2083 }
2084 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
2089 self.on(
2090 EventKind::ContextMenu,
2091 events::typed(listener.into_listener(), events::context_menu),
2092 )
2093 }
2094
2095 fn on_text_selection_change<M>(
2105 self,
2106 listener: impl IntoListener<super::TextSelectionEvent, M>,
2107 ) -> Self {
2108 self.on(
2109 EventKind::SelectionChange,
2110 events::typed(listener.into_listener(), events::selected_text),
2111 )
2112 }
2113
2114 fn on_focus<M>(self, listener: impl IntoListener<(), M>) -> Self {
2118 self.on(
2119 EventKind::Focus,
2120 events::typed(listener.into_listener(), events::unit),
2121 )
2122 }
2123
2124 fn on_blur<M>(self, listener: impl IntoListener<(), M>) -> Self {
2126 self.on(
2127 EventKind::Blur,
2128 events::typed(listener.into_listener(), events::unit),
2129 )
2130 }
2131
2132 fn on_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2138 self.on(
2139 EventKind::Press,
2140 events::typed(listener.into_listener(), events::press),
2141 )
2142 }
2143
2144 fn on_long_press<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2146 self.on(
2147 EventKind::LongPress,
2148 events::typed(listener.into_listener(), events::press),
2149 )
2150 }
2151
2152 fn on_press_down<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2154 self.on(
2155 EventKind::PressDown,
2156 events::typed(listener.into_listener(), events::press),
2157 )
2158 }
2159
2160 fn on_press_up<M>(self, listener: impl IntoListener<PressEvent, M>) -> Self {
2162 self.on(
2163 EventKind::PressUp,
2164 events::typed(listener.into_listener(), events::press),
2165 )
2166 }
2167
2168 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
2170 self.on(
2171 EventKind::Layout,
2172 events::typed(listener.into_listener(), events::layout),
2173 )
2174 }
2175
2176 fn on_touch<M>(self, listener: impl IntoListener<TouchEvent, M>) -> Self {
2180 self.on(
2181 EventKind::Touch,
2182 events::typed(listener.into_listener(), events::touch),
2183 )
2184 }
2185
2186 fn claim_touches(mut self, claim: super::TouchClaim) -> Self {
2191 if let Some(pan) = claim.pan {
2192 super::host::set(self.node(), Prop::PanActivation(Some(pan)));
2193 }
2194 super::responder::of(self.node()).claims.push(claim);
2195 self
2196 }
2197
2198 fn pan_activation(mut self, activation: PanActivation) -> Self {
2207 super::host::set(self.node(), Prop::PanActivation(Some(activation)));
2208 self
2209 }
2210
2211 fn keep_touches(mut self, keep: bool) -> Self {
2216 super::responder::of(self.node()).keep = keep;
2217 self
2218 }
2219
2220 fn on_responder_grant<M>(
2222 mut self,
2223 listener: impl IntoListener<super::ResponderEvent, M>,
2224 ) -> Self {
2225 super::responder::of(self.node()).grant = Some(listener.into_listener());
2226 self
2227 }
2228
2229 fn on_responder_reject<M>(
2232 mut self,
2233 listener: impl IntoListener<super::ResponderEvent, M>,
2234 ) -> Self {
2235 super::responder::of(self.node()).reject = Some(listener.into_listener());
2236 self
2237 }
2238
2239 fn on_responder_start<M>(
2242 mut self,
2243 listener: impl IntoListener<super::ResponderEvent, M>,
2244 ) -> Self {
2245 super::responder::of(self.node()).start = Some(listener.into_listener());
2246 self
2247 }
2248
2249 fn on_responder_move<M>(
2251 mut self,
2252 listener: impl IntoListener<super::ResponderEvent, M>,
2253 ) -> Self {
2254 super::responder::of(self.node()).moved = Some(listener.into_listener());
2255 self
2256 }
2257
2258 fn on_responder_end<M>(
2260 mut self,
2261 listener: impl IntoListener<super::ResponderEvent, M>,
2262 ) -> Self {
2263 super::responder::of(self.node()).end = Some(listener.into_listener());
2264 self
2265 }
2266
2267 fn on_responder_release<M>(
2270 mut self,
2271 listener: impl IntoListener<super::ResponderEvent, M>,
2272 ) -> Self {
2273 super::responder::of(self.node()).release = Some(listener.into_listener());
2274 self
2275 }
2276
2277 fn on_responder_terminate<M>(
2280 mut self,
2281 listener: impl IntoListener<super::ResponderEvent, M>,
2282 ) -> Self {
2283 super::responder::of(self.node()).terminate = Some(listener.into_listener());
2284 self
2285 }
2286
2287 fn pan_values(
2292 mut self,
2293 x: Option<&super::AnimatedValue>,
2294 y: Option<&super::AnimatedValue>,
2295 ) -> Self {
2296 let x = x.and_then(|v| v.node().live());
2297 let y = y.and_then(|v| v.node().live());
2298 let prop = Prop::PanValues(x.as_ref().map(|n| n.id()), y.as_ref().map(|n| n.id()));
2299 super::host::set(self.node(), prop);
2300 if x.is_some() || y.is_some() {
2301 let bound = &mut self.node().attrs.rare_mut().bound;
2302 bound.extend(x);
2303 bound.extend(y);
2304 }
2305 self
2306 }
2307
2308 fn pan_enabled(mut self, enabled: impl IntoReactive<bool>) -> Self {
2311 super::host::bind_prop(self.node(), enabled, Prop::PanEnabled);
2312 self
2313 }
2314
2315 fn pan_scroll_handoff(mut self, enabled: impl IntoReactive<bool>) -> Self {
2320 super::host::bind_prop(self.node(), enabled, Prop::PanScrollHandoff);
2321 self
2322 }
2323
2324 fn pinch_value(mut self, scale: &super::AnimatedValue) -> Self {
2329 if let Some(node) = scale.node().live() {
2330 super::host::set(self.node(), Prop::PinchValue(Some(node.id())));
2331 self.node().attrs.rare_mut().bound.push(node);
2332 }
2333 self
2334 }
2335
2336 fn rotation_value(mut self, angle: &super::AnimatedValue) -> Self {
2340 if let Some(node) = angle.node().live() {
2341 super::host::set(self.node(), Prop::RotationValue(Some(node.id())));
2342 self.node().attrs.rare_mut().bound.push(node);
2343 }
2344 self
2345 }
2346
2347 fn on_pan_start<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2349 self.on(
2350 EventKind::PanStart,
2351 events::typed(listener.into_listener(), events::pan),
2352 )
2353 }
2354
2355 fn on_pan_end<M>(self, listener: impl IntoListener<PanEvent, M>) -> Self {
2357 self.on(
2358 EventKind::PanEnd,
2359 events::typed(listener.into_listener(), events::pan),
2360 )
2361 }
2362
2363 fn on_pinch_start<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2365 self.on(
2366 EventKind::PinchStart,
2367 events::typed(listener.into_listener(), events::pinch),
2368 )
2369 }
2370
2371 fn on_pinch_end<M>(self, listener: impl IntoListener<GestureEvent, M>) -> Self {
2373 self.on(
2374 EventKind::PinchEnd,
2375 events::typed(listener.into_listener(), events::pinch),
2376 )
2377 }
2378
2379 fn on_rotation_start<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2381 self.on(
2382 EventKind::RotationStart,
2383 events::typed(listener.into_listener(), events::rotation),
2384 )
2385 }
2386
2387 fn on_rotation_end<M>(self, listener: impl IntoListener<GestureEvent<Radians>, M>) -> Self {
2389 self.on(
2390 EventKind::RotationEnd,
2391 events::typed(listener.into_listener(), events::rotation),
2392 )
2393 }
2394
2395 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
2397 self.on(
2398 EventKind::AccessibilityAction,
2399 events::typed(listener.into_listener(), events::action),
2400 )
2401 }
2402
2403 fn on<M>(mut self, kind: EventKind, listener: impl IntoListener<EventPayload, M>) -> Self {
2406 self.node().handlers.push((kind, listener.into_listener()));
2407 self
2408 }
2409
2410 fn hit_slop(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
2412 super::host::bind_prop(self.node(), insets, Prop::HitSlop);
2413 self
2414 }
2415
2416 #[doc(hidden)]
2420 fn __link_href(mut self, href: impl IntoReactive<Option<SharedString>>) -> Self {
2421 super::host::bind_prop(self.node(), href, |href: Option<SharedString>| {
2422 Prop::Href(href.map(|href| href.to_arc()))
2423 });
2424 self
2425 }
2426
2427 fn long_press_delay(mut self, ms: f32) -> Self {
2429 super::host::set(self.node(), Prop::LongPressDelay(Some(ms)));
2430 self
2431 }
2432
2433 fn ripple(mut self, ripple: crate::props::Ripple) -> Self {
2435 super::host::set(self.node(), Prop::Ripple(Some(ripple)));
2436 self
2437 }
2438
2439 fn elevation(mut self, elevation: impl Into<Points>) -> Self {
2441 super::host::set(self.node(), Prop::Elevation(elevation.into()));
2442 self
2443 }
2444
2445 fn backdrop_material(mut self, material: crate::BackdropMaterial) -> Self {
2447 super::host::set(self.node(), Prop::BackdropMaterial(material));
2448 self
2449 }
2450
2451 fn scroll_edge_element(
2459 mut self,
2460 scroll_view: impl IntoReactive<Option<super::ElementRef>>,
2461 edge: crate::ScrollEdge,
2462 ) -> Self {
2463 let target =
2464 scroll_view
2465 .into_reactive()
2466 .map(move |scroll_view: Option<super::ElementRef>| {
2467 let scroll_view = scroll_view?.element_target()?;
2468 Some(super::ScrollEdgeTarget { scroll_view, edge })
2469 });
2470 super::host::bind_prop(self.node(), target, Prop::ScrollEdgeElement);
2471 self
2472 }
2473
2474 fn macos_backdrop(mut self, backdrop: impl IntoReactive<Option<crate::MacOsBackdrop>>) -> Self {
2477 super::host::bind_prop(self.node(), backdrop, Prop::MacOsBackdrop);
2478 self
2479 }
2480
2481 fn windows_backdrop(
2485 mut self,
2486 backdrop: impl IntoReactive<Option<crate::WindowsBackdrop>>,
2487 ) -> Self {
2488 super::host::bind_prop(self.node(), backdrop, Prop::WindowsBackdrop);
2489 self
2490 }
2491
2492 fn test_id(mut self, id: &str) -> Self {
2494 super::host::set(self.node(), Prop::TestId(Some(id.into())));
2495 self
2496 }
2497
2498 fn web_element(mut self, element: crate::WebElement) -> Self {
2504 super::host::set(self.node(), Prop::WebElement(Some(element)));
2505 self
2506 }
2507
2508 fn window_drag(mut self, enabled: impl IntoReactive<bool>) -> Self {
2516 super::host::bind_prop(self.node(), enabled, |enabled| {
2517 Prop::WindowDrag(Some(enabled))
2518 });
2519 self
2520 }
2521
2522 fn window_control(mut self, control: crate::desktop::WindowControl) -> Self {
2527 super::host::set(self.node(), Prop::WindowControl(Some(control)));
2528 self
2529 }
2530
2531 fn window_resize(mut self, edge: crate::desktop::ResizeEdge) -> Self {
2534 super::host::set(self.node(), Prop::WindowResize(Some(edge)));
2535 self
2536 }
2537
2538 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
2546 super::host::bind_prop(self.node(), focusable, |focusable| {
2547 Prop::Focusable(Some(focusable))
2548 });
2549 self
2550 }
2551
2552 fn native_id(mut self, id: &str) -> Self {
2555 super::host::set(self.node(), Prop::NativeId(Some(id.into())));
2556 self
2557 }
2558
2559 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2561 let s = f(StyleRefinement::default());
2562 self.style().extend_as(Variant::ACTIVE, s);
2563 self
2564 }
2565
2566 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2568 let s = f(StyleRefinement::default());
2569 self.style().extend_as(Variant::HOVER, s);
2570 self
2571 }
2572
2573 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2575 let s = f(StyleRefinement::default());
2576 self.style().extend_as(Variant::FOCUS, s);
2577 self
2578 }
2579
2580 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2585 let s = f(StyleRefinement::default());
2586 self.style().extend_as(Variant::FOCUS_VISIBLE, s);
2587 self
2588 }
2589
2590 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2595 let s = f(StyleRefinement::default());
2596 self.style().extend_as(Variant::FOCUS_WITHIN, s);
2597 self
2598 }
2599
2600 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
2602 let s = f(StyleRefinement::default());
2603 self.style().extend_as(Variant::DISABLED, s);
2604 self
2605 }
2606
2607 fn disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2609 self.node().bind_attr(disabled, |a, disabled| {
2610 a.disabled = disabled;
2611 a.state.disabled = disabled;
2612 });
2613 self
2614 }
2615
2616 fn selected_style(mut self, style: impl IntoReactive<Style>) -> Self {
2619 Style::apply(self.node(), style, Variant::SELECTED, |a, patch| {
2620 super::host::set_in(&mut a.props, Prop::SelectedStyle(patch))
2621 });
2622 self
2623 }
2624
2625 fn checked_style(mut self, style: impl IntoReactive<Style>) -> Self {
2629 Style::apply(self.node(), style, Variant::CHECKED, |a, patch| {
2630 super::host::set_in(&mut a.props, Prop::CheckedStyle(patch))
2631 });
2632 self
2633 }
2634
2635 fn indeterminate_style(mut self, style: impl IntoReactive<Style>) -> Self {
2639 Style::apply(self.node(), style, Variant::INDETERMINATE, |a, patch| {
2640 super::host::set_in(&mut a.props, Prop::IndeterminateStyle(patch))
2641 });
2642 self
2643 }
2644
2645 fn expanded_style(mut self, style: impl IntoReactive<Style>) -> Self {
2649 Style::apply(self.node(), style, Variant::EXPANDED, |a, patch| {
2650 super::host::set_in(&mut a.props, Prop::ExpandedStyle(patch))
2651 });
2652 self
2653 }
2654
2655 fn pressed_style(mut self, style: impl IntoReactive<Style>) -> Self {
2659 Style::apply(self.node(), style, Variant::ARIA_PRESSED, |a, patch| {
2660 super::host::set_in(&mut a.props, Prop::PressedStyle(patch))
2661 });
2662 self
2663 }
2664
2665 fn project_checked(mut self, checked: impl IntoReactive<bool>) -> Self {
2671 self.node().bind_attr(checked, |a, checked| {
2672 project(a, crate::tailwind::state::CHECKED, checked)
2673 });
2674 self
2675 }
2676
2677 fn project_indeterminate(mut self, indeterminate: impl IntoReactive<bool>) -> Self {
2683 self.node().bind_attr(indeterminate, |a, indeterminate| {
2684 project(a, crate::tailwind::state::INDETERMINATE, indeterminate)
2685 });
2686 self
2687 }
2688
2689 fn project_disabled(mut self, disabled: impl IntoReactive<bool>) -> Self {
2694 self.node().bind_attr(disabled, |a, disabled| {
2695 project(a, crate::tailwind::state::DISABLED, disabled)
2696 });
2697 self
2698 }
2699
2700 fn project_hovered(mut self, hovered: impl IntoReactive<bool>) -> Self {
2706 self.node().bind_attr(hovered, |a, hovered| {
2707 project(a, crate::tailwind::state::HOVERED, hovered)
2708 });
2709 self
2710 }
2711
2712 fn project_focused(mut self, focused: impl IntoReactive<bool>) -> Self {
2721 self.node().bind_attr(focused, |a, focused| {
2722 project(a, crate::tailwind::state::FOCUSED, focused)
2723 });
2724 self
2725 }
2726
2727 fn project_group_active(mut self, group: &'static str) -> Self {
2737 self.node().bind_attr(true, move |a, _: bool| {
2738 a.rare_mut().projected_active = Some(group)
2739 });
2740 self
2741 }
2742
2743 fn project_data(mut self, name: &'static str, on: impl IntoReactive<bool>) -> Self {
2752 self.node().bind_attr(on, move |a, on| {
2753 if !on && a.rare.is_none() {
2754 return;
2755 }
2756 let data = &mut a.rare_mut().projected_data;
2757 let at = data.binary_search(&name);
2758 match (at, on) {
2759 (Err(i), true) => data.insert(i, name),
2760 (Ok(i), false) => {
2761 data.remove(i);
2762 }
2763 _ => {}
2764 }
2765 });
2766 self
2767 }
2768}
2769
2770fn project(a: &mut Attrs, bit: u16, on: bool) {
2772 if on {
2773 a.rare_mut().projected_states |= bit;
2774 } else if let Some(r) = &mut a.rare {
2775 r.projected_states &= !bit;
2776 }
2777}
2778
2779macro_rules! element {
2780 ($(#[$doc:meta])* $name:ident) => {
2781 $(#[$doc])*
2782 #[derive(Clone)]
2783 pub struct $name(ElNode);
2784
2785 impl Element for $name {
2786 fn node(&mut self) -> &mut ElNode {
2787 &mut self.0
2788 }
2789 }
2790
2791 impl IntoElement for $name {
2792 fn into_element(self) -> AnyElement {
2793 AnyElement(self.0)
2794 }
2795 }
2796
2797 impl Accessible for $name {}
2798
2799 impl IntoTooltip for $name {
2800 fn apply_tooltip(self, node: &mut ElNode) {
2801 self.into_element().apply_tooltip(node);
2802 }
2803 }
2804 };
2805}
2806
2807element! {
2808 View
2810}
2811
2812element! {
2813 Text
2815}
2816
2817element! {
2818 Image
2820}
2821
2822element! {
2823 SlotElement
2826}
2827
2828element! {
2829 ListElement
2831}
2832
2833impl Interactive for View {}
2834impl ParentElement for View {}
2835
2836impl View {
2837 pub fn follow(mut self, target: impl IntoReactive<Option<super::ElementRef>>) -> Self {
2856 let target = (target.into_reactive()).map(|t: Option<super::ElementRef>| {
2857 t.and_then(|t| t.target()).map(super::FollowTarget)
2858 });
2859 super::host::bind_prop(&mut self.0, target, Prop::Follow);
2860 self
2861 }
2862
2863 pub fn follow_transition(
2869 mut self,
2870 transition: impl IntoReactive<Option<crate::LayoutTransition>>,
2871 ) -> Self {
2872 super::host::bind_prop(&mut self.0, transition, Prop::FollowTransition);
2873 self
2874 }
2875}
2876impl Interactive for SlotElement {}
2877impl Interactive for Text {}
2878impl Interactive for Image {}
2879
2880impl ParentElement for Text {
2885 fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
2886 let at = self.0.children.len();
2887 child.__push_into(&mut self.0.children);
2888 for el in &mut self.0.children[at..] {
2889 *el = span(std::mem::replace(el, ElNode::new(Tag::View)));
2890 }
2891 self
2892 }
2893
2894 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
2895 self.0
2896 .children
2897 .extend(children.into_iter().map(|c| span(c.into_element().0)));
2898 self
2899 }
2900}
2901
2902fn span(mut el: ElNode) -> ElNode {
2905 if el.tag == Tag::Text
2906 && matches!(el.kind, ElKind::Plain)
2907 && el.key.is_none()
2908 && el.children.is_empty()
2909 && el.handlers.is_empty()
2910 && el.style.is_empty()
2911 && el.attrs == Attrs::default()
2912 && !el.is_bound()
2913 {
2914 el.kind = ElKind::Raw;
2915 }
2916 el
2917}
2918
2919impl Text {
2920 pub fn on_text_layout(mut self, listener: impl Fn(&crate::TextGeometry) + 'static) -> Self {
2926 self.0.handlers.push((
2927 EventKind::TextLayout,
2928 super::Listener::from(move |payload: &EventPayload| {
2929 if let EventPayload::TextLayout(_) = payload
2930 && let Some(geometry) = crate::text::GeometryScope::current()
2931 {
2932 listener(&geometry);
2933 }
2934 }),
2935 ));
2936 self
2937 }
2938
2939 pub fn selection_color(mut self, color: impl IntoReactive<Hsla>) -> Self {
2941 super::host::bind_prop(&mut self.0, color, |c: Hsla| {
2942 Prop::SelectionColor(Some(Color::from(c)))
2943 });
2944 self
2945 }
2946
2947 pub fn shrink_to_fit(mut self, min_scale: impl IntoReactive<f32>) -> Self {
2949 super::host::set(&mut self.0, Prop::AdjustsFontSizeToFit(true));
2950 super::host::bind_prop(&mut self.0, min_scale, Prop::MinimumFontScale);
2951 self
2952 }
2953
2954 pub fn allow_font_scaling(mut self, allow: impl IntoReactive<bool>) -> Self {
2957 super::host::bind_prop(&mut self.0, allow, Prop::AllowFontScaling);
2958 self
2959 }
2960
2961 pub fn max_font_size_multiplier(mut self, multiplier: impl IntoReactive<f32>) -> Self {
2964 super::host::bind_prop(&mut self.0, multiplier, Prop::MaxFontSizeMultiplier);
2965 self
2966 }
2967}
2968
2969impl Image {
2970 pub fn placeholder(mut self, src: impl IntoReactive<super::ImageSrc>) -> Self {
2973 super::host::bind_prop(&mut self.0, src, |src: super::ImageSrc| {
2974 Prop::Image(crate::ImageProp::Placeholder(Some(ImageSource {
2975 uri: src.uri.to_arc(),
2976 size: src.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
2977 scales: src.scales,
2978 data: src.data,
2979 })))
2980 });
2981 self
2982 }
2983
2984 pub fn tint_color(self, color: impl IntoReactive<super::AdaptiveColor>) -> Self {
2986 Styled::tint_color(self, color)
2987 }
2988
2989 pub fn blur_radius(mut self, radius: impl Into<Points>) -> Self {
2991 super::host::set(
2992 &mut self.0,
2993 Prop::Image(crate::ImageProp::BlurRadius(radius.into())),
2994 );
2995 self
2996 }
2997
2998 pub fn fade_duration(mut self, ms: impl IntoReactive<f32>) -> Self {
3000 super::host::bind_prop(&mut self.0, ms, |ms| {
3001 Prop::Image(crate::ImageProp::FadeDuration(Some(ms)))
3002 });
3003 self
3004 }
3005
3006 pub fn on_load<M>(self, listener: impl IntoListener<Size<DevicePixels>, M>) -> Self {
3008 self.on(
3009 EventKind::Load,
3010 events::typed(listener.into_listener(), events::pixel_size),
3011 )
3012 }
3013
3014 pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
3016 self.on(
3017 EventKind::Error,
3018 events::typed(listener.into_listener(), events::message),
3019 )
3020 }
3021
3022 pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
3024 self.on(
3025 EventKind::LoadStart,
3026 events::typed(listener.into_listener(), events::unit),
3027 )
3028 }
3029
3030 pub fn on_load_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
3032 self.on(
3033 EventKind::LoadEnd,
3034 events::typed(listener.into_listener(), events::unit),
3035 )
3036 }
3037
3038 pub fn on_progress<M>(self, listener: impl IntoListener<events::ImageProgress, M>) -> Self {
3041 self.on(
3042 EventKind::Progress,
3043 events::typed(listener.into_listener(), events::image_progress),
3044 )
3045 }
3046}
3047
3048impl super::Scrollable for ListElement {}
3049
3050impl super::ListLayout for ListElement {
3051 fn config(&mut self) -> &mut ListConfig {
3052 match &mut self.0.kind {
3053 ElKind::List(list) => &mut list.config,
3054 _ => unreachable!("a ListElement is a list"),
3055 }
3056 }
3057
3058 fn bound_config(&mut self) -> &mut Vec<BoundListConfig> {
3059 &mut self.0.bound_list
3060 }
3061}
3062
3063#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3066pub struct Slot {
3067 name: &'static str,
3068}
3069
3070impl Slot {
3071 pub(crate) fn new(name: &'static str) -> Self {
3072 Self { name }
3073 }
3074
3075 pub fn name(&self) -> &'static str {
3077 self.name
3078 }
3079
3080 pub fn element(self) -> SlotElement {
3082 let mut node = ElNode::new(Tag::View);
3083 node.kind = ElKind::Slot(self.name);
3084 SlotElement(node)
3085 }
3086}
3087
3088#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3092pub struct Items {
3093 name: &'static str,
3094}
3095
3096impl Items {
3097 #[doc(hidden)]
3098 pub const fn __new(name: &'static str) -> Self {
3099 Self { name }
3100 }
3101}
3102
3103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3107pub struct Child(ChildRef);
3108
3109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3110enum ChildRef {
3111 Js(NodeId, bool),
3113 Row,
3114}
3115
3116impl Child {
3117 pub(crate) fn js(id: NodeId, text: bool) -> Self {
3118 Self(ChildRef::Js(id, text))
3119 }
3120
3121 pub(crate) fn row() -> Self {
3122 Self(ChildRef::Row)
3123 }
3124
3125 pub fn is_text(&self) -> bool {
3133 matches!(self.0, ChildRef::Js(_, true))
3134 }
3135}
3136
3137impl IntoElement for Child {
3138 fn into_element(self) -> AnyElement {
3139 let mut node = ElNode::new(Tag::View);
3140 node.kind = match self.0 {
3141 ChildRef::Js(id, _) => ElKind::JsChild(id),
3142 ChildRef::Row => ElKind::Children,
3143 };
3144 AnyElement(node)
3145 }
3146}
3147
3148pub fn view() -> View {
3150 View(ElNode::new(Tag::View))
3151}
3152
3153pub fn text(content: impl IntoReactive<SharedString>) -> Text {
3156 let mut node = ElNode::new(Tag::Text);
3157 match content.into_reactive() {
3158 Reactive::Static(content) => node.text = Some(content),
3159 Reactive::Bound(content) => {
3160 node.text = Some(SharedString::default());
3161 node.bound_text = Some(content);
3162 }
3163 }
3164 Text(node)
3165}
3166
3167pub fn image(src: impl IntoReactive<super::ImageSrc>) -> Image {
3171 let mut node = ElNode::new(Tag::Image);
3172 node.bind_attr(src, |a, src| a.rare_mut().src = Some(src));
3173 Image(node)
3174}
3175
3176#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3179pub struct Children {
3180 present: bool,
3181}
3182
3183impl Children {
3184 pub(crate) fn new(present: bool) -> Self {
3185 Self { present }
3186 }
3187
3188 pub fn is_empty(&self) -> bool {
3190 !self.present
3191 }
3192}
3193
3194impl IntoElement for Children {
3195 fn into_element(self) -> AnyElement {
3196 let mut node = ElNode::new(Tag::View);
3197 node.kind = ElKind::Children;
3198 AnyElement(node)
3199 }
3200}
3201
3202pub struct ComponentElement<C: Component> {
3226 node: ElNode,
3227 _component: PhantomData<fn() -> C>,
3228}
3229
3230impl<C: Component> ComponentElement<C> {
3231 #[doc(hidden)]
3234 pub fn __new(props: C::Props) -> Self {
3235 Self::new(props)
3236 }
3237
3238 #[doc(hidden)]
3240 pub fn __props_mut(&mut self) -> &mut C::Props {
3241 match &mut self.node.kind {
3242 ElKind::Component(c) => c
3243 .props
3244 .as_any_mut()
3245 .downcast_mut::<C::Props>()
3246 .expect("a component element holds its component's props"),
3247 _ => unreachable!("a component element is a component's"),
3248 }
3249 }
3250
3251 pub(crate) fn new(props: C::Props) -> Self {
3252 let mut node = ElNode::new(Tag::View);
3253 node.kind = ElKind::Component(ComponentEl {
3254 name: super::component::name_of::<C>(),
3255 make: super::component::make_instance::<C>,
3256 spec: ComponentSpec::of::<C>,
3257 props: Box::new(props),
3258 on_event: Vec::new(),
3259 by_name: None,
3260 });
3261 Self {
3262 node,
3263 _component: PhantomData,
3264 }
3265 }
3266
3267 pub fn by_name(props: C::Props) -> Self {
3276 if cfg!(not(target_arch = "wasm32")) {
3277 return Self::new(props);
3278 }
3279 Self::named(props)
3280 }
3281
3282 pub(crate) fn named(props: C::Props) -> Self {
3284 let mut node = ElNode::new(Tag::View);
3285 node.kind = ElKind::Component(ComponentEl {
3286 name: super::component::name_of::<C>(),
3287 make: super::component::missing_instance,
3288 spec: super::component::missing_spec,
3289 props: Box::new(props),
3290 on_event: Vec::new(),
3291 by_name: Some(std::any::TypeId::of::<C>()),
3292 });
3293 Self {
3294 node,
3295 _component: PhantomData,
3296 }
3297 }
3298
3299 pub fn fill(mut self, slot: &'static str, content: impl IntoElement) -> Self {
3304 self.node
3305 .children
3306 .retain(|c| !matches!(c.kind, ElKind::Fill(s) if s == slot));
3307 let mut fill = ElNode::new(Tag::View);
3308 fill.kind = ElKind::Fill(slot);
3309 fill.children.push(content.into_element().0);
3310 self.node.children.push(fill);
3311 self
3312 }
3313
3314 pub fn items(mut self, list: super::VirtualList) -> Self {
3322 match <C::Props as super::Props>::ITEMS {
3323 Some(name) => self.node.children.push(list.into_items(name)),
3324 None => {
3325 log::error!(target: "js", "{} has no `Items` prop to fill", super::component::name_of::<C>())
3326 }
3327 }
3328 self
3329 }
3330
3331 pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3336 let s = f(StyleRefinement::default());
3337 self.node.style.extend_as(Variant::ACTIVE, s);
3338 self
3339 }
3340
3341 pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3343 let s = f(StyleRefinement::default());
3344 self.node.style.extend_as(Variant::HOVER, s);
3345 self
3346 }
3347
3348 pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3350 let s = f(StyleRefinement::default());
3351 self.node.style.extend_as(Variant::FOCUS, s);
3352 self
3353 }
3354
3355 pub fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3358 let s = f(StyleRefinement::default());
3359 self.node.style.extend_as(Variant::FOCUS_VISIBLE, s);
3360 self
3361 }
3362
3363 pub fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3366 let s = f(StyleRefinement::default());
3367 self.node.style.extend_as(Variant::FOCUS_WITHIN, s);
3368 self
3369 }
3370
3371 pub fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3374 let s = f(StyleRefinement::default());
3375 self.node.style.extend_as(Variant::DISABLED, s);
3376 self
3377 }
3378
3379 pub fn test_id(mut self, id: &str) -> Self {
3382 super::host::set(&mut self.node, Prop::TestId(Some(id.into())));
3383 self
3384 }
3385
3386 pub fn component_ref(mut self, handle: &super::ComponentRef<C>) -> Self {
3388 self.node.attrs.set_element_ref(handle.element().target());
3389 self
3390 }
3391
3392 pub fn on_event<M>(mut self, listener: impl IntoListener<C::Event, M>) -> Self {
3398 let listener = listener.into_listener();
3399 if let ElKind::Component(c) = &mut self.node.kind {
3400 c.on_event.push(listener.wrap(|inner, event: &dyn Any| {
3401 if let Some(event) = event.downcast_ref::<C::Event>() {
3402 inner(event);
3403 }
3404 }));
3405 }
3406 self
3407 }
3408
3409 #[doc(hidden)]
3413 pub fn __on_variant<T: ?Sized + 'static, M>(
3414 self,
3415 pick: fn(&C::Event) -> Option<&T>,
3416 listener: impl IntoListener<T, M>,
3417 ) -> Self {
3418 let listener = listener.into_listener();
3419 self.on_event(listener.wrap(move |inner, event: &C::Event| {
3420 if let Some(data) = pick(event) {
3421 inner(data);
3422 }
3423 }))
3424 }
3425}
3426
3427pub trait ComponentBuilder: Element {
3499 type Component: Component;
3501
3502 #[doc(hidden)]
3504 fn __element(&mut self) -> &mut ComponentElement<Self::Component>;
3505
3506 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3511 let s = f(StyleRefinement::default());
3512 self.node().style.extend_as(Variant::ACTIVE, s);
3513 self
3514 }
3515
3516 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3518 let s = f(StyleRefinement::default());
3519 self.node().style.extend_as(Variant::HOVER, s);
3520 self
3521 }
3522
3523 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3525 let s = f(StyleRefinement::default());
3526 self.node().style.extend_as(Variant::FOCUS, s);
3527 self
3528 }
3529
3530 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3533 let s = f(StyleRefinement::default());
3534 self.node().style.extend_as(Variant::FOCUS_VISIBLE, s);
3535 self
3536 }
3537
3538 fn focus_within(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3541 let s = f(StyleRefinement::default());
3542 self.node().style.extend_as(Variant::FOCUS_WITHIN, s);
3543 self
3544 }
3545
3546 fn disabled_style(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3549 let s = f(StyleRefinement::default());
3550 self.node().style.extend_as(Variant::DISABLED, s);
3551 self
3552 }
3553
3554 #[doc(hidden)]
3557 fn __listen(mut self, kind: EventKind, listener: Listener<EventPayload>) -> Self {
3558 self.node().handlers.push((kind, listener));
3559 self
3560 }
3561
3562 fn test_id(mut self, id: &str) -> Self {
3565 super::host::set(self.node(), Prop::TestId(Some(id.into())));
3566 self
3567 }
3568
3569 fn tooltip(mut self, tooltip: impl IntoTooltip) -> Self {
3574 give_tooltip(self.node(), tooltip);
3575 self
3576 }
3577
3578 fn focusable(mut self, focusable: impl IntoReactive<bool>) -> Self {
3582 give_host(self.node(), |n| n.focusable(focusable));
3583 self
3584 }
3585
3586 fn accessibility_label(mut self, label: impl IntoReactive<SharedString>) -> Self {
3591 give_host(self.node(), |n| n.label(label));
3592 self
3593 }
3594
3595 fn accessibility_description(mut self, description: impl IntoReactive<SharedString>) -> Self {
3600 give_host(self.node(), |n| n.accessibility_description(description));
3601 self
3602 }
3603
3604 fn accessibility_value(mut self, value: impl IntoReactive<Option<AccessibilityValue>>) -> Self {
3608 give_host(self.node(), |n| n.accessibility_value(value));
3609 self
3610 }
3611
3612 fn accessibility_actions(
3617 mut self,
3618 actions: impl IntoReactive<Vec<crate::AccessibilityActionDef>>,
3619 ) -> Self {
3620 give_host(self.node(), |n| n.accessibility_actions(actions));
3621 self
3622 }
3623
3624 fn on_accessibility_action<M>(self, listener: impl IntoListener<str, M>) -> Self {
3628 let listener = events::typed(listener.into_listener(), events::action);
3629 self.__listen(EventKind::AccessibilityAction, listener)
3630 }
3631
3632 fn accessibility_active_descendant(
3637 mut self,
3638 target: impl IntoReactive<Option<super::ElementRef>>,
3639 ) -> Self {
3640 give_host(self.node(), |n| n.accessibility_active_descendant(target));
3641 self
3642 }
3643
3644 fn accessibility_controls(
3648 mut self,
3649 target: impl IntoReactive<Option<super::ElementRef>>,
3650 ) -> Self {
3651 give_host(self.node(), |n| n.accessibility_controls(target));
3652 self
3653 }
3654
3655 fn on_layout<M>(self, listener: impl IntoListener<Bounds<Points>, M>) -> Self {
3659 let listener = events::typed(listener.into_listener(), events::layout);
3660 self.__listen(EventKind::Layout, listener)
3661 }
3662
3663 fn on_mouse_enter<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3667 let listener = events::typed(listener.into_listener(), events::mouse);
3668 self.__listen(EventKind::MouseEnter, listener)
3669 }
3670
3671 fn on_mouse_leave<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3674 let listener = events::typed(listener.into_listener(), events::mouse);
3675 self.__listen(EventKind::MouseLeave, listener)
3676 }
3677
3678 fn on_mouse_move<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3682 let listener = events::typed(listener.into_listener(), events::mouse);
3683 self.__listen(EventKind::MouseMove, listener)
3684 }
3685
3686 fn on_mouse_up<M>(self, listener: impl IntoListener<MouseEvent, M>) -> Self {
3689 let listener = events::typed(listener.into_listener(), events::mouse);
3690 self.__listen(EventKind::MouseUp, listener)
3691 }
3692
3693 fn on_context_menu<M>(self, listener: impl IntoListener<ContextMenuEvent, M>) -> Self {
3698 let listener = events::typed(listener.into_listener(), events::context_menu);
3699 self.__listen(EventKind::ContextMenu, listener)
3700 }
3701
3702 fn on_file_drag_enter<M>(self, listener: impl IntoListener<events::FileDragEvent, M>) -> Self {
3705 let listener = events::typed(listener.into_listener(), events::file_drag);
3706 self.__listen(EventKind::FileDragEnter, listener)
3707 }
3708
3709 fn on_file_drag_leave<M>(self, listener: impl IntoListener<(), M>) -> Self {
3712 let listener = events::typed(listener.into_listener(), events::unit);
3713 self.__listen(EventKind::FileDragLeave, listener)
3714 }
3715
3716 fn on_file_drop<M>(self, listener: impl IntoListener<events::FileDropEvent, M>) -> Self {
3719 let listener = events::typed(listener.into_listener(), events::file_drop);
3720 self.__listen(EventKind::FileDrop, listener)
3721 }
3722
3723 fn component_ref(mut self, handle: &super::ComponentRef<Self::Component>) -> Self {
3725 self.__element()
3726 .node
3727 .attrs
3728 .set_element_ref(handle.element().target());
3729 self
3730 }
3731}
3732
3733impl<C: Component> Element for ComponentElement<C> {
3734 fn node(&mut self) -> &mut ElNode {
3735 &mut self.node
3736 }
3737}
3738
3739impl<C: Component> ParentElement for ComponentElement<C> {}
3743
3744impl<C: Component> ComponentBuilder for ComponentElement<C> {
3745 type Component = C;
3746
3747 fn __element(&mut self) -> &mut ComponentElement<C> {
3748 self
3749 }
3750}
3751
3752impl<C: Component> IntoElement for ComponentElement<C> {
3753 fn into_element(self) -> AnyElement {
3754 AnyElement(self.node)
3755 }
3756}
3757
3758#[cfg(test)]
3759mod file_listener_tests {
3760 use std::cell::Cell;
3761
3762 use super::*;
3763
3764 #[test]
3765 fn file_drag_enter_keeps_all_original_listener_forms() {
3766 let calls = Rc::new(Cell::new(0));
3767 let a = calls.clone();
3768 let b = calls.clone();
3769 let c = calls.clone();
3770 let d = calls.clone();
3771 let unit: Listener<()> = (move |_: &()| c.set(c.get() + 1)).into_listener();
3772 let nodes = [
3773 view().on_file_drag_enter(move || a.set(a.get() + 1)),
3774 view().on_file_drag_enter(move |_: &()| b.set(b.get() + 1)),
3775 view().on_file_drag_enter(unit),
3776 view().on_file_drag_enter(move |e: &events::FileDragEvent| {
3777 assert_eq!(e.uris, ["file:///tmp/a%20b.png"]);
3778 assert_eq!(e.mime_types, ["image/png"]);
3779 d.set(d.get() + 1);
3780 }),
3781 ];
3782 let payload = EventPayload::FileDrop(vec!["file:///tmp/a%20b.png".into()]);
3783 for mut node in nodes {
3784 let listener = node
3785 .node()
3786 .handlers
3787 .iter()
3788 .find(|(kind, _)| *kind == EventKind::FileDragEnter)
3789 .unwrap();
3790 listener.1.call(&payload);
3791 }
3792 assert_eq!(calls.get(), 4);
3793 }
3794}
3795
3796#[cfg(test)]
3797mod style_tests {
3798 use super::*;
3799 use crate::{PropertyValue, StyleKey, prelude::*};
3800
3801 fn red() -> PropertyValue {
3802 PropertyValue::Color(Some(rgb(0xff0000).into()))
3803 }
3804
3805 #[test]
3806 fn a_style_is_typed_only_with_typed_styles() {
3807 let declared = Style::default().with(StyleKey::Color, red());
3808 let typed = Style::from(StyleRefinement::default().text_color(rgb(0xff0000)));
3809 let bound = Style::from(StyleRefinement::default().text_color(move || rgb(0xff0000)));
3810 assert!(!Style::default().is_typed());
3811 assert!(!Style::from(StyleRefinement::default()).is_typed());
3812 assert!(!Style::from_decls([]).is_typed());
3813 assert!(!declared.is_typed());
3814 assert!(typed.is_typed());
3815 assert!(bound.is_typed());
3817 assert!(
3819 typed
3820 .clone()
3821 .with(StyleKey::Opacity, PropertyValue::Number(0.5.into()))
3822 .is_typed()
3823 );
3824 assert!(declared.then(&typed).is_typed());
3825 assert!(typed.then(&declared).is_typed());
3826 assert!(!declared.then(&declared).is_typed());
3827 }
3828}