Skip to main content

freya_core/elements/
extensions.rs

1use std::{
2    borrow::Cow,
3    hash::{
4        Hash,
5        Hasher,
6    },
7    rc::Rc,
8};
9
10use paste::paste;
11use ragnarok::CursorPoint;
12use rustc_hash::FxHasher;
13use torin::{
14    content::Content,
15    gaps::Gaps,
16    prelude::{
17        Alignment,
18        Direction,
19        Length,
20        Position,
21        VisibleSize,
22    },
23    size::Size,
24};
25
26use crate::{
27    data::{
28        AccessibilityData,
29        EffectData,
30        LayoutData,
31        Overflow,
32        TextStyleData,
33    },
34    diff_key::DiffKey,
35    element::{
36        Element,
37        EventHandlerType,
38        EventHandlers,
39    },
40    elements::{
41        image::{
42            AspectRatio,
43            Image,
44            ImageCover,
45            ImageData,
46            SamplingMode,
47        },
48        label::Label,
49        paragraph::Paragraph,
50        rect::Rect,
51    },
52    event_handler::EventHandler,
53    events::{
54        data::{
55            Event,
56            KeyboardEventData,
57            MouseEventData,
58            SizedEventData,
59            StyledEventData,
60            VisibleEventData,
61            WheelEventData,
62        },
63        name::EventName,
64    },
65    layers::Layer,
66    prelude::*,
67    style::{
68        font_feature::FontFeature,
69        font_size::FontSize,
70        font_slant::FontSlant,
71        font_weight::FontWeight,
72        font_width::FontWidth,
73        letter_spacing::LetterSpacing,
74        scale::Scale,
75        text_height::TextHeightBehavior,
76        text_overflow::TextOverflow,
77        text_shadow::TextShadow,
78        transform_origin::TransformOrigin,
79    },
80};
81
82/// Trait for composing child elements.
83pub trait ChildrenExt: Sized {
84    /// Returns a mutable reference to the internal children vector.
85    ///
86    /// # Example
87    /// ```ignore
88    /// impl ChildrenExt for MyElement {
89    ///     fn children_mut(&mut self) -> &mut Vec<Element> {
90    ///         &mut self.elements
91    ///     }
92    /// }
93    /// ```
94    fn children_mut(&mut self) -> &mut Vec<Element>;
95
96    /// Extends the children with an iterable of anything that implements [`IntoElement`].
97    ///
98    /// # Example
99    /// ```ignore
100    /// rect().children(["Hello", "World"].map(|t| label().text(t)))
101    /// ```
102    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
103        self.children_mut()
104            .extend(children.into_iter().map(IntoElement::into_element));
105        self
106    }
107
108    /// Appends a child only when the [`Option`] is [`Some`].
109    ///
110    /// # Example
111    /// ```ignore
112    /// rect().maybe_child(show_badge.then(|| label().text("New")))
113    /// ```
114    fn maybe_child<C: IntoElement>(mut self, child: Option<C>) -> Self {
115        if let Some(child) = child {
116            self.children_mut().push(child.into_element());
117        }
118        self
119    }
120
121    /// Appends a single child element.
122    ///
123    /// # Example
124    /// ```ignore
125    /// rect().child(label().text("Hello"))
126    /// ```
127    fn child<C: IntoElement>(mut self, child: C) -> Self {
128        self.children_mut().push(child.into_element());
129        self
130    }
131}
132
133/// Reuses unchanged children by Rc identity.
134/// It is an alternative to [ChildrenExt].
135pub trait RetainedChildrenExt: ChildrenExt {
136    /// Replaces existing children with retained children.
137    fn retained_children(self, children: Rc<Vec<Element>>) -> Self;
138}
139
140/// Trait for giving an element a stable identity across renders.
141pub trait KeyExt: Sized {
142    /// Returns a mutable reference to the element's diff key.
143    fn key_mut(&mut self) -> &mut DiffKey;
144
145    /// Assign a key derived from any hashable value, used to reconcile elements in dynamic lists.
146    /// The key is scoped to the element's type, so the same value used
147    /// on different element or component types never collides.
148    fn key(mut self, key: impl Hash) -> Self
149    where
150        Self: 'static,
151    {
152        let mut hasher = FxHasher::default();
153        std::any::TypeId::of::<Self>().hash(&mut hasher);
154        key.hash(&mut hasher);
155        *self.key_mut() = DiffKey::U64(hasher.finish());
156        self
157    }
158}
159
160/// Methods for unconditionally modifying an element.
161pub trait WithExt: Sized {
162    /// Applies `with` immediately.
163    fn with(self, with: impl FnOnce(Self) -> Self) -> Self {
164        with(self)
165    }
166}
167
168impl WithExt for Rect {}
169impl WithExt for Label {}
170impl WithExt for Paragraph {}
171impl WithExt for Image {}
172
173macro_rules! event_handlers {
174    (
175        $handler_variant:ident, $event_data:ty;
176        $(
177            $(#[$attr:meta])*
178            $name:ident => $event_variant:expr ;
179        )*
180    ) => {
181        paste! {
182            $(
183                $(#[$attr])*
184                fn [<on_$name>](mut self, [<on_$name>]: impl Into<EventHandler<Event<$event_data>>>) -> Self {
185                    self.event_handlers_mut()
186                        .insert($event_variant, EventHandlerType::$handler_variant([<on_$name>].into()));
187                    self
188                }
189            )*
190        }
191    };
192}
193
194/// Methods for attaching event handlers to an element.
195///
196/// Many events come in three flavors: the plain one fires only while the pointer is over the
197/// element, the `global_` variants fire no matter where the event happens, and the `capture_`
198/// variants fire during the top-down capture phase, before the event reaches the inner element.
199///
200/// For high-level press handling, prefer [`on_press`](EventHandlersExt::on_press) over the raw mouse/pointer events.
201pub trait EventHandlersExt: Sized {
202    /// Returns a mutable reference to the element's event handler map.
203    fn event_handlers_mut(&mut self) -> &mut EventHandlers;
204
205    /// Replace all of this element's event handlers with the given map.
206    fn event_handlers(mut self, event_handlers: EventHandlers) -> Self {
207        *self.event_handlers_mut() = event_handlers;
208        self
209    }
210
211    event_handlers! {
212        AccessibilityAction,
213        AccessibilityActionEventData;
214
215        /// Fires when assistive technology requests an action advertised through [`a11y_builder`](AccessibilityExt::a11y_builder).
216        accessibility_action => EventName::AccessibilityAction;
217    }
218
219    event_handlers! {
220        Mouse,
221        MouseEventData;
222
223        /// Fires when a mouse button is pressed down over the element.
224        mouse_down => EventName::MouseDown;
225        /// Fires when a mouse button is released over the element.
226        mouse_up => EventName::MouseUp;
227        /// Fires when the cursor moves over the element.
228        mouse_move => EventName::MouseMove;
229
230    }
231
232    event_handlers! {
233        Pointer,
234        PointerEventData;
235
236        /// Fires when a pointer (mouse or touch) is released anywhere, even outside the element.
237        global_pointer_up => EventName::GlobalPointerUp;
238        /// Fires when a pointer (mouse or touch) goes down anywhere, even outside the element.
239        global_pointer_down => EventName::GlobalPointerDown;
240        /// Fires when a pointer (mouse or touch) moves anywhere, even outside the element.
241        global_pointer_move => EventName::GlobalPointerMove;
242
243        /// Like [`on_global_pointer_move`](Self::on_global_pointer_move), but fires during the top-down capture phase.
244        capture_global_pointer_move => EventName::CaptureGlobalPointerMove;
245        /// Like [`on_global_pointer_up`](Self::on_global_pointer_up), but fires during the top-down capture phase.
246        capture_global_pointer_up => EventName::CaptureGlobalPointerUp;
247    }
248
249    event_handlers! {
250        Keyboard,
251        KeyboardEventData;
252
253        /// Fires when a key is pressed down while the element is focused.
254        key_down => EventName::KeyDown;
255        /// Fires when a key is released while the element is focused.
256        key_up => EventName::KeyUp;
257
258        /// Fires when a key is pressed down, regardless of which element is focused.
259        global_key_down => EventName::GlobalKeyDown;
260        /// Fires when a key is released, regardless of which element is focused.
261        global_key_up => EventName::GlobalKeyUp;
262    }
263
264    event_handlers! {
265        Wheel,
266        WheelEventData;
267
268        /// Fires when the scroll wheel is used over the element.
269        wheel => EventName::Wheel;
270    }
271
272    event_handlers! {
273        Touch,
274        TouchEventData;
275
276        /// Fires when an ongoing touch is cancelled by the system.
277        touch_cancel => EventName::TouchCancel;
278        /// Fires when a touch point is placed on the element.
279        touch_start => EventName::TouchStart;
280        /// Fires when a touch point moves across the element.
281        touch_move => EventName::TouchMove;
282        /// Fires when a touch point is lifted from the element.
283        touch_end => EventName::TouchEnd;
284    }
285
286    event_handlers! {
287        Pointer,
288        PointerEventData;
289
290        /// Fires when the element is pressed and released by a pointer (mouse or touch).
291        pointer_press => EventName::PointerPress;
292        /// Fires when a pointer (mouse or touch) goes down over the element.
293        pointer_down => EventName::PointerDown;
294        /// Fires when a pointer (mouse or touch) moves over the element.
295        pointer_move => EventName::PointerMove;
296        /// Fires when a pointer enters the element.
297        pointer_enter => EventName::PointerEnter;
298        /// Fires when a pointer leaves the element.
299        pointer_leave => EventName::PointerLeave;
300        /// Fires when a pointer is over the element, including over its children.
301        pointer_over => EventName::PointerOver;
302        /// Fires when a pointer leaves the element or one of its children.
303        pointer_out => EventName::PointerOut;
304    }
305
306    event_handlers! {
307        File,
308        FileEventData;
309
310        /// Fires when a file is dropped onto the element.
311        file_drop => EventName::FileDrop;
312        /// Fires when a dragged file hovers anywhere over the window.
313        global_file_hover => EventName::GlobalFileHover;
314        /// Fires when a dragged file stops hovering over the window.
315        global_file_hover_cancelled => EventName::GlobalFileHoverCancelled;
316    }
317
318    event_handlers! {
319        ImePreedit,
320        ImePreeditEventData;
321
322        /// Fires while text is being composed through an input method editor (IME).
323        ime_preedit => EventName::ImePreedit;
324    }
325
326    /// Fires when the element's measured size or position changes.
327    fn on_sized(mut self, on_sized: impl Into<EventHandler<Event<SizedEventData>>>) -> Self
328    where
329        Self: LayoutExt,
330    {
331        self.event_handlers_mut()
332            .insert(EventName::Sized, EventHandlerType::Sized(on_sized.into()));
333        self.layout_mut().layout.has_layout_references = true;
334        self
335    }
336
337    /// Fires when the element becomes visible, even partially, inside the viewports of its clipping ancestors.
338    fn on_visible(mut self, on_visible: impl Into<EventHandler<Event<VisibleEventData>>>) -> Self {
339        self.event_handlers_mut().insert(
340            EventName::Visible,
341            EventHandlerType::Visible(on_visible.into()),
342        );
343        self
344    }
345
346    /// Fires when the element stops being visible inside the viewports of its clipping ancestors.
347    fn on_hidden(mut self, on_hidden: impl Into<EventHandler<Event<VisibleEventData>>>) -> Self {
348        self.event_handlers_mut().insert(
349            EventName::Hidden,
350            EventHandlerType::Visible(on_hidden.into()),
351        );
352        self
353    }
354
355    /// Fires when the element's inherited text style is resolved or changes.
356    fn on_styled(mut self, on_styled: impl Into<EventHandler<Event<StyledEventData>>>) -> Self {
357        self.event_handlers_mut().insert(
358            EventName::Styled,
359            EventHandlerType::Styled(on_styled.into()),
360        );
361        self
362    }
363
364    /// This is generally the best event in which to run "press" logic, this might be called `onClick`, `onActivate`, or `onConnect` in other platforms.
365    ///
366    /// Gets triggered when:
367    /// - **Click**: There is a `MouseUp` event (Left button) with the in the same element that there had been a `MouseDown` just before
368    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
369    /// - **Activated**: The element is focused and there is a keydown event pressing the OS activation key (e.g Space, Enter)
370    /// - **Accessibility**: Assistive technology requests the Click action
371    fn on_press(self, on_press: impl Into<EventHandler<Event<PressEventData>>>) -> Self
372    where
373        Self: AccessibilityExt,
374    {
375        let on_press = on_press.into();
376        self.a11y_builder(|builder| builder.add_action(AccessibilityAction::Click))
377            .on_accessibility_action({
378                let on_press = on_press.clone();
379                move |event: Event<AccessibilityActionEventData>| {
380                    if event.action == AccessibilityAction::Click {
381                        on_press.call(event.map(PressEventData::Accessibility));
382                    }
383                }
384            })
385            .on_pointer_press({
386                let on_press = on_press.clone();
387                move |e: Event<PointerEventData>| {
388                    let event = e.try_map(|d| match d {
389                        PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
390                            Some(PressEventData::Mouse(m))
391                        }
392                        PointerEventData::Touch(t) => Some(PressEventData::Touch(t)),
393                        _ => None,
394                    });
395                    if let Some(event) = event {
396                        on_press.call(event);
397                    }
398                }
399            })
400            .on_key_down(move |e: Event<KeyboardEventData>| {
401                if e.is_press_event() {
402                    on_press.call(e.map(PressEventData::Keyboard))
403                }
404            })
405    }
406
407    /// Also called the context menu click in other platforms.
408    /// Gets triggered when:
409    /// - **Click**: There is a `MouseDown` (Right button) event
410    fn on_secondary_down(
411        self,
412        on_secondary_down: impl Into<EventHandler<Event<PressEventData>>>,
413    ) -> Self {
414        let on_secondary_down = on_secondary_down.into();
415        self.on_pointer_down(move |e: Event<PointerEventData>| {
416            let event = e.try_map(|d| match d {
417                PointerEventData::Mouse(m) if m.button == Some(MouseButton::Right) => {
418                    Some(PressEventData::Mouse(m))
419                }
420                _ => None,
421            });
422            if let Some(event) = event {
423                on_secondary_down.call(event);
424            }
425        })
426    }
427
428    /// Gets triggered when:
429    /// - **Click**: There is a `MouseUp` event (Any button) with the in the same element that there had been a `MouseDown` just before
430    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
431    /// - **Activated**: The element is focused and there is a keydown event pressing the OS activation key (e.g Space, Enter)
432    /// - **Accessibility**: Assistive technology requests the Click action
433    fn on_all_press(self, on_press: impl Into<EventHandler<Event<PressEventData>>>) -> Self
434    where
435        Self: AccessibilityExt,
436    {
437        let on_press = on_press.into();
438        self.a11y_builder(|builder| builder.add_action(AccessibilityAction::Click))
439            .on_accessibility_action({
440                let on_press = on_press.clone();
441                move |event: Event<AccessibilityActionEventData>| {
442                    if event.action == AccessibilityAction::Click {
443                        on_press.call(event.map(PressEventData::Accessibility));
444                    }
445                }
446            })
447            .on_pointer_press({
448                let on_press = on_press.clone();
449                move |e: Event<PointerEventData>| {
450                    let event = e.map(|d| match d {
451                        PointerEventData::Mouse(m) => PressEventData::Mouse(m),
452                        PointerEventData::Touch(t) => PressEventData::Touch(t),
453                    });
454                    on_press.call(event);
455                }
456            })
457            .on_key_down(move |e: Event<KeyboardEventData>| {
458                if e.is_press_event() {
459                    on_press.call(e.map(PressEventData::Keyboard))
460                }
461            })
462    }
463    /// Gets triggered when:
464    /// - **Started clicking**: There is a `MouseDown` event (Left button)
465    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
466    ///
467    /// This event is intended to focus elements such as text inputs following each platform style.
468    fn on_focus_press(
469        self,
470        on_focus_press: impl Into<EventHandler<Event<FocusPressEventData>>>,
471    ) -> Self {
472        let on_focus_press = on_focus_press.into();
473        if cfg!(target_os = "android") {
474            self.on_pointer_press(move |e: Event<PointerEventData>| {
475                let event = e.try_map(|d| match d {
476                    PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
477                        Some(FocusPressEventData::Mouse(m))
478                    }
479                    PointerEventData::Touch(t) => Some(FocusPressEventData::Touch(t)),
480                    _ => None,
481                });
482                if let Some(event) = event {
483                    on_focus_press.call(event);
484                }
485            })
486        } else {
487            self.on_pointer_down(move |e: Event<PointerEventData>| {
488                let event = e.try_map(|d| match d {
489                    PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
490                        Some(FocusPressEventData::Mouse(m))
491                    }
492                    PointerEventData::Touch(t) => Some(FocusPressEventData::Touch(t)),
493                    _ => None,
494                });
495                if let Some(event) = event {
496                    on_focus_press.call(event);
497                }
498            })
499        }
500    }
501}
502
503/// Data delivered to [`on_focus_press`](EventHandlersExt::on_focus_press), which can originate from a mouse or a touch.
504#[derive(Debug, Clone, PartialEq)]
505pub enum FocusPressEventData {
506    Mouse(MouseEventData),
507    Touch(TouchEventData),
508}
509
510impl FocusPressEventData {
511    pub fn global_location(&self) -> CursorPoint {
512        match self {
513            Self::Mouse(m) => m.global_location,
514            Self::Touch(t) => t.global_location,
515        }
516    }
517
518    pub fn element_location(&self) -> CursorPoint {
519        match self {
520            Self::Mouse(m) => m.element_location,
521            Self::Touch(t) => t.element_location,
522        }
523    }
524
525    pub fn button(&self) -> Option<MouseButton> {
526        match self {
527            Self::Mouse(m) => m.button,
528            Self::Touch(_) => None,
529        }
530    }
531}
532
533/// Data delivered to [`on_press`](EventHandlersExt::on_press) from a mouse, keyboard, touch or assistive technology.
534#[derive(Debug, Clone, PartialEq)]
535pub enum PressEventData {
536    Accessibility(AccessibilityActionEventData),
537    Mouse(MouseEventData),
538    Keyboard(KeyboardEventData),
539    Touch(TouchEventData),
540}
541
542/// Layout methods for containers that arrange children along a direction axis.
543pub trait ContainerWithContentExt
544where
545    Self: LayoutExt,
546{
547    /// Set the axis children are stacked along. See [`Direction`].
548    fn direction(mut self, direction: Direction) -> Self {
549        self.layout_mut().layout.direction = direction;
550        self
551    }
552    /// Set how children are aligned along the direction axis. See [`Alignment`].
553    fn main_align(mut self, main_align: impl Into<Alignment>) -> Self {
554        self.layout_mut().layout.main_alignment = main_align.into();
555        self
556    }
557
558    /// Set how children are aligned across the direction axis. See [`Alignment`].
559    fn cross_align(mut self, cross_align: impl Into<Alignment>) -> Self {
560        self.layout_mut().layout.cross_alignment = cross_align.into();
561        self
562    }
563
564    /// Set the gap inserted between adjacent children, in pixels.
565    fn spacing(mut self, spacing: f32) -> Self {
566        self.layout_mut().layout.spacing = Length::new(spacing);
567        self
568    }
569
570    /// Set how children share the available space along the direction axis. See [`Content`].
571    fn content(mut self, content: Content) -> Self {
572        self.layout_mut().layout.content = content;
573        self
574    }
575    /// Center children on both axes. Shorthand for [`main_align`](Self::main_align) and [`cross_align`](Self::cross_align) set to [`Alignment::Center`].
576    fn center(mut self) -> Self {
577        self.layout_mut().layout.main_alignment = Alignment::Center;
578        self.layout_mut().layout.cross_alignment = Alignment::Center;
579
580        self
581    }
582
583    /// Shift the element's children horizontally by the given pixels.
584    fn offset_x(mut self, offset_x: f32) -> Self {
585        self.layout_mut().layout.offset_x = Length::new(offset_x);
586        self
587    }
588
589    /// Shift the element's children vertically by the given pixels.
590    fn offset_y(mut self, offset_y: f32) -> Self {
591        self.layout_mut().layout.offset_y = Length::new(offset_y);
592        self
593    }
594
595    /// Stack children vertically. Shorthand for [`direction`](Self::direction) set to [`Direction::Vertical`].
596    fn vertical(mut self) -> Self {
597        self.layout_mut().layout.direction = Direction::vertical();
598        self
599    }
600
601    /// Stack children horizontally. Shorthand for [`direction`](Self::direction) set to [`Direction::Horizontal`].
602    fn horizontal(mut self) -> Self {
603        self.layout_mut().layout.direction = Direction::horizontal();
604        self
605    }
606}
607
608/// Methods for setting an element's width and height.
609pub trait ContainerSizeExt
610where
611    Self: LayoutExt,
612{
613    /// Set the element's width. See [`Size`].
614    fn width(mut self, width: impl Into<Size>) -> Self {
615        self.layout_mut().layout.width = width.into();
616        self
617    }
618
619    /// Set the element's height. See [`Size`].
620    fn height(mut self, height: impl Into<Size>) -> Self {
621        self.layout_mut().layout.height = height.into();
622        self
623    }
624
625    /// Expand both `width` and `height` using [Size::fill()].
626    fn expanded(mut self) -> Self {
627        self.layout_mut().layout.width = Size::fill();
628        self.layout_mut().layout.height = Size::fill();
629        self
630    }
631}
632
633impl<T: ContainerExt> ContainerSizeExt for T {}
634
635/// Methods for setting how an element is placed relative to its parent or the window.
636pub trait ContainerPositionExt
637where
638    Self: LayoutExt,
639{
640    /// Set how the element is placed relative to its parent or the window. See [`Position`].
641    fn position(mut self, position: impl Into<Position>) -> Self {
642        self.layout_mut().layout.position = position.into();
643        self
644    }
645
646    /// Set the outer spacing between the element's edges and its surroundings. See [`Gaps`].
647    fn margin(mut self, margin: impl Into<Gaps>) -> Self {
648        self.layout_mut().layout.margin = margin.into();
649        self
650    }
651}
652
653impl<T: ContainerExt> ContainerPositionExt for T {}
654
655/// Method for setting an element's inner padding.
656pub trait ContainerExt
657where
658    Self: LayoutExt,
659{
660    /// Set the inner spacing between the element's edges and its content. See [`Gaps`].
661    fn padding(mut self, padding: impl Into<Gaps>) -> Self {
662        self.layout_mut().layout.padding = padding.into();
663        self
664    }
665}
666
667/// Methods for setting an element's size constraints.
668pub trait ContainerConstraintsExt
669where
670    Self: LayoutExt,
671{
672    /// Set the minimum width the element can shrink to. See [`Size`].
673    fn min_width(mut self, minimum_width: impl Into<Size>) -> Self {
674        self.layout_mut().layout.minimum_width = minimum_width.into();
675        self
676    }
677
678    /// Set the minimum height the element can shrink to. See [`Size`].
679    fn min_height(mut self, minimum_height: impl Into<Size>) -> Self {
680        self.layout_mut().layout.minimum_height = minimum_height.into();
681        self
682    }
683
684    /// Set the maximum width the element can grow to. See [`Size`].
685    fn max_width(mut self, maximum_width: impl Into<Size>) -> Self {
686        self.layout_mut().layout.maximum_width = maximum_width.into();
687        self
688    }
689
690    /// Set the maximum height the element can grow to. See [`Size`].
691    fn max_height(mut self, maximum_height: impl Into<Size>) -> Self {
692        self.layout_mut().layout.maximum_height = maximum_height.into();
693        self
694    }
695
696    /// Set how much of the measured width is actually used in layout. See [`VisibleSize`].
697    fn visible_width(mut self, visible_width: impl Into<VisibleSize>) -> Self {
698        self.layout_mut().layout.visible_width = visible_width.into();
699        self
700    }
701
702    /// Set how much of the measured height is actually used in layout. See [`VisibleSize`].
703    fn visible_height(mut self, visible_height: impl Into<VisibleSize>) -> Self {
704        self.layout_mut().layout.visible_height = visible_height.into();
705        self
706    }
707}
708
709impl<T: ContainerExt> ContainerConstraintsExt for T {}
710
711/// Low-level access to an element's [`LayoutData`].
712pub trait LayoutExt
713where
714    Self: Sized,
715{
716    /// Returns a mutable reference to the element's layout data.
717    fn layout_mut(&mut self) -> &mut LayoutData;
718
719    /// Replace all of the element's layout data at once. See [`LayoutData`].
720    fn layout(mut self, layout: LayoutData) -> Self {
721        *self.layout_mut() = layout;
722        self
723    }
724}
725
726/// Methods for configuring how an image is scaled and sampled.
727pub trait ImageExt
728where
729    Self: LayoutExt,
730{
731    /// Returns a mutable reference to the element's image data.
732    fn image_data_mut(&mut self) -> &mut ImageData;
733
734    /// Replace all of the element's image data at once. See [`ImageData`].
735    fn image_data(mut self, image_data: ImageData) -> Self {
736        *self.image_data_mut() = image_data;
737        self
738    }
739
740    /// Set the filtering used when the image is scaled. See [`SamplingMode`].
741    fn sampling_mode(mut self, sampling_mode: SamplingMode) -> Self {
742        self.image_data_mut().sampling_mode = sampling_mode;
743        self
744    }
745
746    /// Set how the image is scaled to fit its bounds. See [`AspectRatio`].
747    fn aspect_ratio(mut self, aspect_ratio: AspectRatio) -> Self {
748        self.image_data_mut().aspect_ratio = aspect_ratio;
749        self
750    }
751
752    /// Set how the image is positioned within its bounds. See [`ImageCover`].
753    fn image_cover(mut self, image_cover: ImageCover) -> Self {
754        self.image_data_mut().image_cover = image_cover;
755        self
756    }
757
758    /// Snap the image to the pixels grid. Defaults to `false`, but `SvgViewer` enables it.
759    fn snap_to_grid(mut self, snap_to_grid: bool) -> Self {
760        self.image_data_mut().snap_to_grid = snap_to_grid;
761        self
762    }
763
764    /// Apply a Gaussian blur of the given radius to the image.
765    fn blur(mut self, blur: f32) -> Self {
766        self.image_data_mut().blur = blur;
767        self
768    }
769}
770
771/// Methods for describing an element in the accessibility tree.
772pub trait AccessibilityExt: Sized {
773    /// Returns a mutable reference to the element's accessibility data.
774    fn accessibility_data_mut(&mut self) -> &mut AccessibilityData;
775
776    /// Replace all of the element's accessibility data at once. See [`AccessibilityData`].
777    fn accessibility(mut self, accessibility: AccessibilityData) -> Self {
778        *self.accessibility_data_mut() = accessibility;
779        self
780    }
781
782    /// Set an explicit accessibility id instead of an autogenerated one. See [`AccessibilityId`].
783    fn a11y_id(mut self, a11y_id: impl Into<Option<AccessibilityId>>) -> Self {
784        self.accessibility_data_mut().a11y_id = a11y_id.into();
785        self
786    }
787
788    /// Set whether the element is enabled for assistive technology.
789    fn a11y_enabled(mut self, enabled: impl Into<bool>) -> Self {
790        let builder = &mut self.accessibility_data_mut().builder;
791        if enabled.into() {
792            builder.clear_disabled();
793        } else {
794            builder.set_disabled();
795        }
796        self
797    }
798
799    /// Set whether the element can receive keyboard focus. See [`Focusable`].
800    fn a11y_focusable(mut self, a11y_focusable: impl Into<Focusable>) -> Self {
801        self.accessibility_data_mut().a11y_focusable = a11y_focusable.into();
802        self
803    }
804
805    /// Request that the element be focused automatically when it is mounted.
806    fn a11y_auto_focus(mut self, a11y_auto_focus: impl Into<bool>) -> Self {
807        self.accessibility_data_mut().a11y_auto_focus = a11y_auto_focus.into();
808        self
809    }
810
811    /// Mark the element as a member of the group identified by the given [`AccessibilityId`].
812    fn a11y_member_of(mut self, a11y_member_of: impl Into<AccessibilityId>) -> Self {
813        self.accessibility_data_mut()
814            .builder
815            .set_member_of(a11y_member_of.into());
816        self
817    }
818
819    /// Set the accessibility role exposed in the accessibility tree. See [`AccessibilityRole`].
820    fn a11y_role(mut self, a11y_role: impl Into<AccessibilityRole>) -> Self {
821        self.accessibility_data_mut()
822            .builder
823            .set_role(a11y_role.into());
824        self
825    }
826
827    /// Set the text label that describes the element in the accessibility tree.
828    fn a11y_alt(mut self, value: impl Into<String>) -> Self {
829        self.accessibility_data_mut().builder.set_label(value);
830        self
831    }
832
833    /// Edit the underlying `accesskit` node directly for advanced accessibility properties.
834    fn a11y_builder(mut self, with: impl FnOnce(&mut accesskit::Node)) -> Self {
835        with(&mut self.accessibility_data_mut().builder);
836        self
837    }
838}
839
840/// Methods for styling the text rendered by an element and inherited by its children.
841pub trait TextStyleExt
842where
843    Self: Sized,
844{
845    /// Returns a mutable reference to the element's text style data.
846    fn text_style_data_mut(&mut self) -> &mut TextStyleData;
847
848    /// Replace all of the element's text style data at once. See [`TextStyleData`].
849    fn text_style(mut self, data: TextStyleData) -> Self {
850        *self.text_style_data_mut() = data;
851        self
852    }
853
854    /// Paint the text with any [`Fill`]: a [`Color`], a gradient or a shader.
855    fn color(mut self, color: impl Into<Fill>) -> Self {
856        self.text_style_data_mut().color = Some(color.into());
857        self
858    }
859
860    /// Set the horizontal alignment of the text. See [`TextAlign`].
861    fn text_align(mut self, text_align: impl Into<TextAlign>) -> Self {
862        self.text_style_data_mut().text_align = Some(text_align.into());
863        self
864    }
865
866    /// Set the text size in pixels. See [`FontSize`].
867    fn font_size(mut self, font_size: impl Into<FontSize>) -> Self {
868        self.text_style_data_mut().font_size = Some(font_size.into());
869        self
870    }
871
872    /// Set the space between letters, in pixels. See [`LetterSpacing`].
873    fn letter_spacing(mut self, letter_spacing: impl Into<LetterSpacing>) -> Self {
874        self.text_style_data_mut().letter_spacing = Some(letter_spacing.into());
875        self
876    }
877
878    /// Add an OpenType font feature.
879    fn font_feature(mut self, font_feature: impl Into<FontFeature>) -> Self {
880        self.text_style_data_mut()
881            .font_features
882            .push(font_feature.into());
883        self
884    }
885
886    /// Every digit shares the same width, so changing numbers do not shift the layout.
887    fn font_tabular(self) -> Self {
888        self.font_feature(FontFeature::TABULAR_NUMBERS)
889    }
890
891    /// Lowercase letters render as small capitals.
892    fn font_small_caps(self) -> Self {
893        self.font_feature(FontFeature::SMALL_CAPS)
894    }
895
896    /// Zero renders with a slash or dot to tell it apart from the letter O.
897    fn font_slashed_zero(self) -> Self {
898        self.font_feature(FontFeature::SLASHED_ZERO)
899    }
900
901    /// Sequences like `1/2` render as fractions.
902    fn font_fractions(self) -> Self {
903        self.font_feature(FontFeature::FRACTIONS)
904    }
905
906    /// Disable standard ligatures like `fi` or the joined `=>` of coding fonts.
907    fn font_no_ligatures(self) -> Self {
908        self.font_feature(FontFeature::NO_LIGATURES)
909    }
910
911    /// Add a font family to try, in order of preference.
912    fn font_family(mut self, font_family: impl Into<Cow<'static, str>>) -> Self {
913        self.text_style_data_mut()
914            .font_families
915            .push(font_family.into());
916        self
917    }
918
919    /// Set the slant (style) of the font. See [`FontSlant`].
920    fn font_slant(mut self, font_slant: impl Into<FontSlant>) -> Self {
921        self.text_style_data_mut().font_slant = Some(font_slant.into());
922        self
923    }
924
925    /// Set the thickness of the font. See [`FontWeight`].
926    fn font_weight(mut self, font_weight: impl Into<FontWeight>) -> Self {
927        self.text_style_data_mut().font_weight = Some(font_weight.into());
928        self
929    }
930
931    /// Set the horizontal width of the font. See [`FontWidth`].
932    fn font_width(mut self, font_width: impl Into<FontWidth>) -> Self {
933        self.text_style_data_mut().font_width = Some(font_width.into());
934        self
935    }
936
937    /// Set how the leading of the first and last lines is handled. See [`TextHeightBehavior`].
938    fn text_height(mut self, text_height: impl Into<TextHeightBehavior>) -> Self {
939        self.text_style_data_mut().text_height = Some(text_height.into());
940        self
941    }
942
943    /// Add a shadow cast behind the text, replacing inherited shadows. See [`TextShadow`].
944    fn text_shadow(mut self, text_shadow: impl Into<TextShadow>) -> Self {
945        self.text_style_data_mut()
946            .text_shadows
947            .get_or_insert_default()
948            .push(text_shadow.into());
949        self
950    }
951
952    /// Replace the text shadows. An empty list clears inherited shadows.
953    fn text_shadows(mut self, text_shadows: impl IntoIterator<Item = TextShadow>) -> Self {
954        self.text_style_data_mut().text_shadows = Some(text_shadows.into_iter().collect());
955        self
956    }
957
958    /// Set a line drawn through, under or over the text. See [`TextDecoration`].
959    fn text_decoration(mut self, text_decoration: impl Into<TextDecoration>) -> Self {
960        self.text_style_data_mut().text_decoration = Some(text_decoration.into());
961        self
962    }
963}
964
965/// Methods for truncating text within an element's bounds.
966pub trait TextOverflowExt: TextStyleExt {
967    /// Set how text that does not fit its bounds is truncated. See [`TextOverflow`].
968    fn text_overflow(mut self, text_overflow: impl Into<TextOverflow>) -> Self {
969        self.text_style_data_mut().text_overflow = Some(text_overflow.into());
970        self
971    }
972}
973
974/// Methods for painting an element's background.
975pub trait BackgroundExt: StyleExt {
976    /// Paint the background with a color, gradient or shader. See [`Fill`].
977    fn background(mut self, background: impl Into<Fill>) -> Self {
978        self.style_mut().background = background.into();
979        self
980    }
981}
982
983/// Low-level access to an element's [`StyleState`].
984pub trait StyleExt
985where
986    Self: Sized,
987{
988    /// Returns a mutable reference to the element's style data.
989    fn style_mut(&mut self) -> &mut StyleState;
990
991    /// Replace all of the element's style data at once. See [`StyleState`].
992    fn style(mut self, style: StyleState) -> Self {
993        *self.style_mut() = style;
994        self
995    }
996}
997
998/// Methods for decorating an element.
999pub trait DecorationExt: StyleExt {
1000    /// Add an outline around the element. See [`Border`].
1001    fn border(mut self, border: impl Into<Option<Border>>) -> Self {
1002        if let Some(border) = border.into() {
1003            self.style_mut().borders.push(border);
1004        }
1005        self
1006    }
1007
1008    /// Add a shadow cast by the element. See [`Shadow`].
1009    fn shadow(mut self, shadow: impl Into<Shadow>) -> Self {
1010        self.style_mut().shadows.push(shadow.into());
1011        self
1012    }
1013
1014    /// Round the element's corners. See [`CornerRadius`].
1015    fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self {
1016        self.style_mut().corner_radius = corner_radius.into();
1017        self
1018    }
1019}
1020
1021impl<T: DecorationExt> CornerRadiusExt for T {
1022    fn with_corner_radius(mut self, corner_radius: f32) -> Self {
1023        self.style_mut().corner_radius = CornerRadius::new_all(corner_radius);
1024        self
1025    }
1026}
1027
1028/// Shorthand methods for setting an element's [`CornerRadius`] to common values.
1029pub trait CornerRadiusExt: Sized {
1030    /// Round all four corners to the given radius in pixels.
1031    fn with_corner_radius(self, corner_radius: f32) -> Self;
1032
1033    /// Shortcut for `corner_radius(0.)` - removes border radius.
1034    fn rounded_none(self) -> Self {
1035        self.with_corner_radius(0.)
1036    }
1037
1038    /// Shortcut for `corner_radius(6.)` - default border radius.
1039    fn rounded(self) -> Self {
1040        self.with_corner_radius(6.)
1041    }
1042
1043    /// Shortcut for `corner_radius(4.)` - small border radius.
1044    fn rounded_sm(self) -> Self {
1045        self.with_corner_radius(4.)
1046    }
1047
1048    /// Shortcut for `corner_radius(6.)` - medium border radius.
1049    fn rounded_md(self) -> Self {
1050        self.with_corner_radius(6.)
1051    }
1052
1053    /// Shortcut for `corner_radius(8.)` - large border radius.
1054    fn rounded_lg(self) -> Self {
1055        self.with_corner_radius(8.)
1056    }
1057
1058    /// Shortcut for `corner_radius(12.)` - extra large border radius.
1059    fn rounded_xl(self) -> Self {
1060        self.with_corner_radius(12.)
1061    }
1062
1063    /// Shortcut for `corner_radius(16.)` - extra large border radius.
1064    fn rounded_2xl(self) -> Self {
1065        self.with_corner_radius(16.)
1066    }
1067
1068    /// Shortcut for `corner_radius(24.)` - extra large border radius.
1069    fn rounded_3xl(self) -> Self {
1070        self.with_corner_radius(24.)
1071    }
1072
1073    /// Shortcut for `corner_radius(32.)` - extra large border radius.
1074    fn rounded_4xl(self) -> Self {
1075        self.with_corner_radius(32.)
1076    }
1077
1078    /// Shortcut for `corner_radius(99.)` - fully rounded (pill shape).
1079    fn rounded_full(self) -> Self {
1080        self.with_corner_radius(99.)
1081    }
1082}
1083
1084/// Methods for applying changes to an element conditionally.
1085pub trait MaybeExt
1086where
1087    Self: Sized,
1088{
1089    /// Apply `then` to the element only when the condition is `true`.
1090    fn maybe(self, bool: impl Into<bool>, then: impl FnOnce(Self) -> Self) -> Self {
1091        if bool.into() { then(self) } else { self }
1092    }
1093
1094    /// Apply `then` to the element only when the [`Option`] is [`Some`], passing the inner value.
1095    fn map<T>(self, data: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
1096        if let Some(data) = data {
1097            then(self, data)
1098        } else {
1099            self
1100        }
1101    }
1102}
1103
1104/// Method for controlling which painting layer an element belongs to.
1105pub trait LayerExt
1106where
1107    Self: Sized,
1108{
1109    /// Returns a mutable reference to the element's layer.
1110    fn layer_mut(&mut self) -> &mut Layer;
1111
1112    /// Sets the element's painting layer without changing its layout or position.
1113    ///
1114    /// Higher layers paint on top of lower layers. An integer is a [`Layer::Relative`]
1115    /// offset from the normal layer, which is one above the parent's layer.
1116    /// The default is `0`. Descendants use this element's resulting layer as their base.
1117    ///
1118    /// Use [`Layer::Overlay`] to raise content relative to its parent and escape
1119    /// ancestor clipping, or [`Layer::OverlayLevel`] for an absolute overlay level.
1120    /// Elements on the same layer have no guaranteed painting order.
1121    ///
1122    /// ```rust
1123    /// # use freya_core::prelude::*;
1124    /// rect()
1125    ///     .child(rect().layer(-1).child("Below default siblings"))
1126    ///     .child(rect().child("Default layer"))
1127    ///     .child(rect().layer(1).child("Above default siblings"))
1128    ///     .child(rect().layer(Layer::Overlay).child("Overlay"))
1129    /// # ;
1130    /// ```
1131    fn layer(mut self, layer: impl Into<Layer>) -> Self {
1132        *self.layer_mut() = layer.into();
1133        self
1134    }
1135}
1136
1137pub trait ScrollableExt
1138where
1139    Self: Sized,
1140{
1141    /// Returns a mutable reference to the element's effect data.
1142    fn effect_mut(&mut self) -> &mut EffectData;
1143
1144    /// Mark this element as scrollable.
1145    /// You are probably looking for the `ScrollView` component instead.
1146    fn scrollable(mut self, scrollable: impl Into<bool>) -> Self {
1147        self.effect_mut().scrollable = scrollable.into();
1148        self
1149    }
1150}
1151
1152/// Method for controlling whether an element responds to pointer events.
1153pub trait InteractiveExt
1154where
1155    Self: Sized,
1156{
1157    /// Returns a mutable reference to the element's effect data.
1158    fn effect_mut(&mut self) -> &mut EffectData;
1159
1160    /// Set whether the element receives pointer events. See [`Interactive`].
1161    fn interactive(mut self, interactive: impl Into<Interactive>) -> Self {
1162        self.effect_mut().interactive = interactive.into();
1163        self
1164    }
1165}
1166
1167/// Methods for visual effects applied to an element: clipping, backdrop blur, rotation, opacity and scale.
1168pub trait EffectExt: Sized {
1169    /// Returns a mutable reference to the element's effect data.
1170    fn effect_mut(&mut self) -> &mut EffectData;
1171
1172    /// Set the [`CursorIcon`] shown while the element is hovered.
1173    ///
1174    /// When multiple hovered elements define a cursor, the one painted on top wins.
1175    /// While a mouse button is pressed the cursor stays still.
1176    fn cursor(mut self, cursor: impl Into<Option<CursorIcon>>) -> Self {
1177        self.effect_mut().cursor = cursor.into();
1178        self
1179    }
1180
1181    /// Show or hide the mouse cursor while the element is hovered.
1182    ///
1183    /// The topmost hovered element with an explicit visibility wins, defaulting to visible.
1184    fn cursor_visible(mut self, visible: impl Into<Option<bool>>) -> Self {
1185        self.effect_mut().cursor_visible = visible.into();
1186        self
1187    }
1188
1189    /// Replace all of the element's effect data at once. See [`EffectData`].
1190    fn effect(mut self, effect: EffectData) -> Self {
1191        *self.effect_mut() = effect;
1192        self
1193    }
1194
1195    /// Set whether content overflowing the element's bounds is clipped. See [`Overflow`].
1196    fn overflow(mut self, overflow: impl Into<Overflow>) -> Self {
1197        self.effect_mut().overflow = overflow.into();
1198        self
1199    }
1200
1201    /// Apply a Gaussian blur of the given radius to the backdrop behind the element.
1202    fn backdrop_blur(mut self, blur: f32) -> Self {
1203        self.effect_mut().blur = Some(blur);
1204        self
1205    }
1206
1207    /// Rotate the element by the given angle in degrees.
1208    fn rotation(mut self, rotation: f32) -> Self {
1209        self.effect_mut().rotation = Some(rotation);
1210        self
1211    }
1212
1213    /// Set the element's opacity, from `0.0` (transparent) to `1.0` (opaque).
1214    fn opacity(mut self, opacity: f32) -> Self {
1215        self.effect_mut().opacity = Some(opacity);
1216        self
1217    }
1218
1219    /// Scale the element. See [`Scale`].
1220    fn scale(mut self, scale: impl Into<Scale>) -> Self {
1221        self.effect_mut().scale = Some(scale.into());
1222        self
1223    }
1224
1225    /// Set the point that the scale and rotation effects pivot around.
1226    ///
1227    /// Defaults to the element's center.
1228    fn transform_origin(mut self, transform_origin: impl Into<TransformOrigin>) -> Self {
1229        self.effect_mut().transform_origin = transform_origin.into();
1230        self
1231    }
1232}