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        Drag,
308        DragEventData;
309
310        /// Fires when a platform drag enters the element's area.
311        drag_enter => EventName::DragEnter;
312        /// Fires on entry and movement over the element and bubbles to ancestors.
313        drag_over => EventName::DragOver;
314        /// Fires when a platform drag leaves the element's area.
315        drag_leave => EventName::DragLeave;
316        /// Fires when accepted drag data is dropped onto the element.
317        drop => EventName::Drop;
318    }
319
320    event_handlers! {
321        ImePreedit,
322        ImePreeditEventData;
323
324        /// Fires while text is being composed through an input method editor (IME).
325        ime_preedit => EventName::ImePreedit;
326    }
327
328    /// Fires when the element's measured size or position changes.
329    fn on_sized(mut self, on_sized: impl Into<EventHandler<Event<SizedEventData>>>) -> Self
330    where
331        Self: LayoutExt,
332    {
333        self.event_handlers_mut()
334            .insert(EventName::Sized, EventHandlerType::Sized(on_sized.into()));
335        self.layout_mut().layout.has_layout_references = true;
336        self
337    }
338
339    /// Fires when the element becomes visible, even partially, inside the viewports of its clipping ancestors.
340    fn on_visible(mut self, on_visible: impl Into<EventHandler<Event<VisibleEventData>>>) -> Self {
341        self.event_handlers_mut().insert(
342            EventName::Visible,
343            EventHandlerType::Visible(on_visible.into()),
344        );
345        self
346    }
347
348    /// Fires when the element stops being visible inside the viewports of its clipping ancestors.
349    fn on_hidden(mut self, on_hidden: impl Into<EventHandler<Event<VisibleEventData>>>) -> Self {
350        self.event_handlers_mut().insert(
351            EventName::Hidden,
352            EventHandlerType::Visible(on_hidden.into()),
353        );
354        self
355    }
356
357    /// Fires when the element's inherited text style is resolved or changes.
358    fn on_styled(mut self, on_styled: impl Into<EventHandler<Event<StyledEventData>>>) -> Self {
359        self.event_handlers_mut().insert(
360            EventName::Styled,
361            EventHandlerType::Styled(on_styled.into()),
362        );
363        self
364    }
365
366    /// This is generally the best event in which to run "press" logic, this might be called `onClick`, `onActivate`, or `onConnect` in other platforms.
367    ///
368    /// Gets triggered when:
369    /// - **Click**: There is a `MouseUp` event (Left button) with the in the same element that there had been a `MouseDown` just before
370    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
371    /// - **Activated**: The element is focused and there is a keydown event pressing the OS activation key (e.g Space, Enter)
372    /// - **Accessibility**: Assistive technology requests the Click action
373    fn on_press(self, on_press: impl Into<EventHandler<Event<PressEventData>>>) -> Self
374    where
375        Self: AccessibilityExt,
376    {
377        let on_press = on_press.into();
378        self.a11y_builder(|builder| builder.add_action(AccessibilityAction::Click))
379            .on_accessibility_action({
380                let on_press = on_press.clone();
381                move |event: Event<AccessibilityActionEventData>| {
382                    if event.action == AccessibilityAction::Click {
383                        on_press.call(event.map(PressEventData::Accessibility));
384                    }
385                }
386            })
387            .on_pointer_press({
388                let on_press = on_press.clone();
389                move |e: Event<PointerEventData>| {
390                    let event = e.try_map(|d| match d {
391                        PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
392                            Some(PressEventData::Mouse(m))
393                        }
394                        PointerEventData::Touch(t) => Some(PressEventData::Touch(t)),
395                        _ => None,
396                    });
397                    if let Some(event) = event {
398                        on_press.call(event);
399                    }
400                }
401            })
402            .on_key_down(move |e: Event<KeyboardEventData>| {
403                if e.is_press_event() {
404                    on_press.call(e.map(PressEventData::Keyboard))
405                }
406            })
407    }
408
409    /// Also called the context menu click in other platforms.
410    /// Gets triggered when:
411    /// - **Click**: There is a `MouseDown` (Right button) event
412    fn on_secondary_down(
413        self,
414        on_secondary_down: impl Into<EventHandler<Event<PressEventData>>>,
415    ) -> Self {
416        let on_secondary_down = on_secondary_down.into();
417        self.on_pointer_down(move |e: Event<PointerEventData>| {
418            let event = e.try_map(|d| match d {
419                PointerEventData::Mouse(m) if m.button == Some(MouseButton::Right) => {
420                    Some(PressEventData::Mouse(m))
421                }
422                _ => None,
423            });
424            if let Some(event) = event {
425                on_secondary_down.call(event);
426            }
427        })
428    }
429
430    /// Gets triggered when:
431    /// - **Click**: There is a `MouseUp` event (Any button) with the in the same element that there had been a `MouseDown` just before
432    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
433    /// - **Activated**: The element is focused and there is a keydown event pressing the OS activation key (e.g Space, Enter)
434    /// - **Accessibility**: Assistive technology requests the Click action
435    fn on_all_press(self, on_press: impl Into<EventHandler<Event<PressEventData>>>) -> Self
436    where
437        Self: AccessibilityExt,
438    {
439        let on_press = on_press.into();
440        self.a11y_builder(|builder| builder.add_action(AccessibilityAction::Click))
441            .on_accessibility_action({
442                let on_press = on_press.clone();
443                move |event: Event<AccessibilityActionEventData>| {
444                    if event.action == AccessibilityAction::Click {
445                        on_press.call(event.map(PressEventData::Accessibility));
446                    }
447                }
448            })
449            .on_pointer_press({
450                let on_press = on_press.clone();
451                move |e: Event<PointerEventData>| {
452                    let event = e.map(|d| match d {
453                        PointerEventData::Mouse(m) => PressEventData::Mouse(m),
454                        PointerEventData::Touch(t) => PressEventData::Touch(t),
455                    });
456                    on_press.call(event);
457                }
458            })
459            .on_key_down(move |e: Event<KeyboardEventData>| {
460                if e.is_press_event() {
461                    on_press.call(e.map(PressEventData::Keyboard))
462                }
463            })
464    }
465    /// Gets triggered when:
466    /// - **Started clicking**: There is a `MouseDown` event (Left button)
467    /// - **Touched**: There is a `TouchEnd` event in the same element that there had been a `TouchStart` just before
468    ///
469    /// This event is intended to focus elements such as text inputs following each platform style.
470    fn on_focus_press(
471        self,
472        on_focus_press: impl Into<EventHandler<Event<FocusPressEventData>>>,
473    ) -> Self {
474        let on_focus_press = on_focus_press.into();
475        if cfg!(target_os = "android") {
476            self.on_pointer_press(move |e: Event<PointerEventData>| {
477                let event = e.try_map(|d| match d {
478                    PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
479                        Some(FocusPressEventData::Mouse(m))
480                    }
481                    PointerEventData::Touch(t) => Some(FocusPressEventData::Touch(t)),
482                    _ => None,
483                });
484                if let Some(event) = event {
485                    on_focus_press.call(event);
486                }
487            })
488        } else {
489            self.on_pointer_down(move |e: Event<PointerEventData>| {
490                let event = e.try_map(|d| match d {
491                    PointerEventData::Mouse(m) if m.button == Some(MouseButton::Left) => {
492                        Some(FocusPressEventData::Mouse(m))
493                    }
494                    PointerEventData::Touch(t) => Some(FocusPressEventData::Touch(t)),
495                    _ => None,
496                });
497                if let Some(event) = event {
498                    on_focus_press.call(event);
499                }
500            })
501        }
502    }
503}
504
505/// Data delivered to [`on_focus_press`](EventHandlersExt::on_focus_press), which can originate from a mouse or a touch.
506#[derive(Debug, Clone, PartialEq)]
507pub enum FocusPressEventData {
508    Mouse(MouseEventData),
509    Touch(TouchEventData),
510}
511
512impl FocusPressEventData {
513    pub fn global_location(&self) -> CursorPoint {
514        match self {
515            Self::Mouse(m) => m.global_location,
516            Self::Touch(t) => t.global_location,
517        }
518    }
519
520    pub fn element_location(&self) -> CursorPoint {
521        match self {
522            Self::Mouse(m) => m.element_location,
523            Self::Touch(t) => t.element_location,
524        }
525    }
526
527    pub fn button(&self) -> Option<MouseButton> {
528        match self {
529            Self::Mouse(m) => m.button,
530            Self::Touch(_) => None,
531        }
532    }
533}
534
535/// Data delivered to [`on_press`](EventHandlersExt::on_press) from a mouse, keyboard, touch or assistive technology.
536#[derive(Debug, Clone, PartialEq)]
537pub enum PressEventData {
538    Accessibility(AccessibilityActionEventData),
539    Mouse(MouseEventData),
540    Keyboard(KeyboardEventData),
541    Touch(TouchEventData),
542}
543
544/// Methods for setting the direction.
545pub trait DirectionExt: Sized {
546    /// Set the direction.
547    fn direction(self, direction: Direction) -> Self;
548
549    /// Set the direction to [`Direction::Vertical`].
550    fn vertical(self) -> Self {
551        self.direction(Direction::vertical())
552    }
553
554    /// Set the direction to [`Direction::Horizontal`].
555    fn horizontal(self) -> Self {
556        self.direction(Direction::horizontal())
557    }
558}
559
560impl<T: ContainerWithContentExt> DirectionExt for T {
561    fn direction(mut self, direction: Direction) -> Self {
562        self.layout_mut().layout.direction = direction;
563        self
564    }
565}
566
567/// Layout methods for containers that arrange children along a direction axis.
568pub trait ContainerWithContentExt
569where
570    Self: LayoutExt,
571{
572    /// Set how children are aligned along the direction axis. See [`Alignment`].
573    fn main_align(mut self, main_align: impl Into<Alignment>) -> Self {
574        self.layout_mut().layout.main_alignment = main_align.into();
575        self
576    }
577
578    /// Set how children are aligned across the direction axis. See [`Alignment`].
579    fn cross_align(mut self, cross_align: impl Into<Alignment>) -> Self {
580        self.layout_mut().layout.cross_alignment = cross_align.into();
581        self
582    }
583
584    /// Set the gap inserted between adjacent children, in pixels.
585    fn spacing(mut self, spacing: f32) -> Self {
586        self.layout_mut().layout.spacing = Length::new(spacing);
587        self
588    }
589
590    /// Set how children share the available space along the direction axis. See [`Content`].
591    fn content(mut self, content: Content) -> Self {
592        self.layout_mut().layout.content = content;
593        self
594    }
595    /// Center children on both axes. Shorthand for [`main_align`](Self::main_align) and [`cross_align`](Self::cross_align) set to [`Alignment::Center`].
596    fn center(mut self) -> Self {
597        self.layout_mut().layout.main_alignment = Alignment::Center;
598        self.layout_mut().layout.cross_alignment = Alignment::Center;
599
600        self
601    }
602
603    /// Shift the element's children horizontally by the given pixels.
604    fn offset_x(mut self, offset_x: f32) -> Self {
605        self.layout_mut().layout.offset_x = Length::new(offset_x);
606        self
607    }
608
609    /// Shift the element's children vertically by the given pixels.
610    fn offset_y(mut self, offset_y: f32) -> Self {
611        self.layout_mut().layout.offset_y = Length::new(offset_y);
612        self
613    }
614}
615
616/// Methods for setting an element's width and height.
617pub trait ContainerSizeExt
618where
619    Self: LayoutExt,
620{
621    /// Set the element's width. See [`Size`].
622    fn width(mut self, width: impl Into<Size>) -> Self {
623        self.layout_mut().layout.width = width.into();
624        self
625    }
626
627    /// Set the element's height. See [`Size`].
628    fn height(mut self, height: impl Into<Size>) -> Self {
629        self.layout_mut().layout.height = height.into();
630        self
631    }
632
633    /// Expand both `width` and `height` using [Size::fill()].
634    fn expanded(mut self) -> Self {
635        self.layout_mut().layout.width = Size::fill();
636        self.layout_mut().layout.height = Size::fill();
637        self
638    }
639}
640
641impl<T: ContainerExt> ContainerSizeExt for T {}
642
643/// Methods for setting how an element is placed relative to its parent or the window.
644pub trait ContainerPositionExt
645where
646    Self: LayoutExt,
647{
648    /// Set how the element is placed relative to its parent or the window. See [`Position`].
649    fn position(mut self, position: impl Into<Position>) -> Self {
650        self.layout_mut().layout.position = position.into();
651        self
652    }
653
654    /// Set the outer spacing between the element's edges and its surroundings. See [`Gaps`].
655    fn margin(mut self, margin: impl Into<Gaps>) -> Self {
656        self.layout_mut().layout.margin = margin.into();
657        self
658    }
659}
660
661impl<T: ContainerExt> ContainerPositionExt for T {}
662
663/// Method for setting an element's inner padding.
664pub trait ContainerExt
665where
666    Self: LayoutExt,
667{
668    /// Set the inner spacing between the element's edges and its content. See [`Gaps`].
669    fn padding(mut self, padding: impl Into<Gaps>) -> Self {
670        self.layout_mut().layout.padding = padding.into();
671        self
672    }
673}
674
675/// Methods for setting an element's size constraints.
676pub trait ContainerConstraintsExt
677where
678    Self: LayoutExt,
679{
680    /// Set the minimum width the element can shrink to. See [`Size`].
681    fn min_width(mut self, minimum_width: impl Into<Size>) -> Self {
682        self.layout_mut().layout.minimum_width = minimum_width.into();
683        self
684    }
685
686    /// Set the minimum height the element can shrink to. See [`Size`].
687    fn min_height(mut self, minimum_height: impl Into<Size>) -> Self {
688        self.layout_mut().layout.minimum_height = minimum_height.into();
689        self
690    }
691
692    /// Set the maximum width the element can grow to. See [`Size`].
693    fn max_width(mut self, maximum_width: impl Into<Size>) -> Self {
694        self.layout_mut().layout.maximum_width = maximum_width.into();
695        self
696    }
697
698    /// Set the maximum height the element can grow to. See [`Size`].
699    fn max_height(mut self, maximum_height: impl Into<Size>) -> Self {
700        self.layout_mut().layout.maximum_height = maximum_height.into();
701        self
702    }
703
704    /// Set how much of the measured width is actually used in layout. See [`VisibleSize`].
705    fn visible_width(mut self, visible_width: impl Into<VisibleSize>) -> Self {
706        self.layout_mut().layout.visible_width = visible_width.into();
707        self
708    }
709
710    /// Set how much of the measured height is actually used in layout. See [`VisibleSize`].
711    fn visible_height(mut self, visible_height: impl Into<VisibleSize>) -> Self {
712        self.layout_mut().layout.visible_height = visible_height.into();
713        self
714    }
715}
716
717impl<T: ContainerExt> ContainerConstraintsExt for T {}
718
719/// Low-level access to an element's [`LayoutData`].
720pub trait LayoutExt
721where
722    Self: Sized,
723{
724    /// Returns a mutable reference to the element's layout data.
725    fn layout_mut(&mut self) -> &mut LayoutData;
726
727    /// Replace all of the element's layout data at once. See [`LayoutData`].
728    fn layout(mut self, layout: LayoutData) -> Self {
729        *self.layout_mut() = layout;
730        self
731    }
732}
733
734/// Methods for configuring how an image is scaled and sampled.
735pub trait ImageExt
736where
737    Self: LayoutExt,
738{
739    /// Returns a mutable reference to the element's image data.
740    fn image_data_mut(&mut self) -> &mut ImageData;
741
742    /// Replace all of the element's image data at once. See [`ImageData`].
743    fn image_data(mut self, image_data: ImageData) -> Self {
744        *self.image_data_mut() = image_data;
745        self
746    }
747
748    /// Set the filtering used when the image is scaled. See [`SamplingMode`].
749    fn sampling_mode(mut self, sampling_mode: SamplingMode) -> Self {
750        self.image_data_mut().sampling_mode = sampling_mode;
751        self
752    }
753
754    /// Set how the image is scaled to fit its bounds. See [`AspectRatio`].
755    fn aspect_ratio(mut self, aspect_ratio: AspectRatio) -> Self {
756        self.image_data_mut().aspect_ratio = aspect_ratio;
757        self
758    }
759
760    /// Set how the image is positioned within its bounds. See [`ImageCover`].
761    fn image_cover(mut self, image_cover: ImageCover) -> Self {
762        self.image_data_mut().image_cover = image_cover;
763        self
764    }
765
766    /// Snap the image to the pixels grid. Defaults to `false`, but `SvgViewer` enables it.
767    fn snap_to_grid(mut self, snap_to_grid: bool) -> Self {
768        self.image_data_mut().snap_to_grid = snap_to_grid;
769        self
770    }
771
772    /// Apply a Gaussian blur of the given radius to the image.
773    fn blur(mut self, blur: f32) -> Self {
774        self.image_data_mut().blur = blur;
775        self
776    }
777}
778
779/// Methods for describing an element in the accessibility tree.
780pub trait AccessibilityExt: Sized {
781    /// Returns a mutable reference to the element's accessibility data.
782    fn accessibility_data_mut(&mut self) -> &mut AccessibilityData;
783
784    /// Replace all of the element's accessibility data at once. See [`AccessibilityData`].
785    fn accessibility(mut self, accessibility: AccessibilityData) -> Self {
786        *self.accessibility_data_mut() = accessibility;
787        self
788    }
789
790    /// Set an explicit accessibility id instead of an autogenerated one. See [`AccessibilityId`].
791    fn a11y_id(mut self, a11y_id: impl Into<Option<AccessibilityId>>) -> Self {
792        self.accessibility_data_mut().a11y_id = a11y_id.into();
793        self
794    }
795
796    /// Set whether the element is enabled for assistive technology.
797    fn a11y_enabled(mut self, enabled: impl Into<bool>) -> Self {
798        let builder = &mut self.accessibility_data_mut().builder;
799        if enabled.into() {
800            builder.clear_disabled();
801        } else {
802            builder.set_disabled();
803        }
804        self
805    }
806
807    /// Set whether the element can receive keyboard focus. See [`Focusable`].
808    fn a11y_focusable(mut self, a11y_focusable: impl Into<Focusable>) -> Self {
809        self.accessibility_data_mut().a11y_focusable = a11y_focusable.into();
810        self
811    }
812
813    /// Request that the element be focused automatically when it is mounted.
814    fn a11y_auto_focus(mut self, a11y_auto_focus: impl Into<bool>) -> Self {
815        self.accessibility_data_mut().a11y_auto_focus = a11y_auto_focus.into();
816        self
817    }
818
819    /// Mark the element as a member of the group identified by the given [`AccessibilityId`].
820    fn a11y_member_of(mut self, a11y_member_of: impl Into<AccessibilityId>) -> Self {
821        self.accessibility_data_mut()
822            .builder
823            .set_member_of(a11y_member_of.into());
824        self
825    }
826
827    /// Set the accessibility role exposed in the accessibility tree. See [`AccessibilityRole`].
828    fn a11y_role(mut self, a11y_role: impl Into<AccessibilityRole>) -> Self {
829        self.accessibility_data_mut()
830            .builder
831            .set_role(a11y_role.into());
832        self
833    }
834
835    /// Set the text label that describes the element in the accessibility tree.
836    fn a11y_alt(mut self, value: impl Into<String>) -> Self {
837        self.accessibility_data_mut().builder.set_label(value);
838        self
839    }
840
841    /// Edit the underlying `accesskit` node directly for advanced accessibility properties.
842    fn a11y_builder(mut self, with: impl FnOnce(&mut accesskit::Node)) -> Self {
843        with(&mut self.accessibility_data_mut().builder);
844        self
845    }
846}
847
848/// Methods for styling the text rendered by an element and inherited by its children.
849pub trait TextStyleExt
850where
851    Self: Sized,
852{
853    /// Returns a mutable reference to the element's text style data.
854    fn text_style_data_mut(&mut self) -> &mut TextStyleData;
855
856    /// Replace all of the element's text style data at once. See [`TextStyleData`].
857    fn text_style(mut self, data: TextStyleData) -> Self {
858        *self.text_style_data_mut() = data;
859        self
860    }
861
862    /// Paint the text with any [`Fill`]: a [`Color`], a gradient or a shader.
863    fn color(mut self, color: impl Into<Fill>) -> Self {
864        self.text_style_data_mut().color = Some(color.into());
865        self
866    }
867
868    /// Set the horizontal alignment of the text. See [`TextAlign`].
869    fn text_align(mut self, text_align: impl Into<TextAlign>) -> Self {
870        self.text_style_data_mut().text_align = Some(text_align.into());
871        self
872    }
873
874    /// Set the text size in pixels. See [`FontSize`].
875    fn font_size(mut self, font_size: impl Into<FontSize>) -> Self {
876        self.text_style_data_mut().font_size = Some(font_size.into());
877        self
878    }
879
880    /// Set the space between letters, in pixels. See [`LetterSpacing`].
881    fn letter_spacing(mut self, letter_spacing: impl Into<LetterSpacing>) -> Self {
882        self.text_style_data_mut().letter_spacing = Some(letter_spacing.into());
883        self
884    }
885
886    /// Add an OpenType font feature.
887    fn font_feature(mut self, font_feature: impl Into<FontFeature>) -> Self {
888        self.text_style_data_mut()
889            .font_features
890            .push(font_feature.into());
891        self
892    }
893
894    /// Every digit shares the same width, so changing numbers do not shift the layout.
895    fn font_tabular(self) -> Self {
896        self.font_feature(FontFeature::TABULAR_NUMBERS)
897    }
898
899    /// Lowercase letters render as small capitals.
900    fn font_small_caps(self) -> Self {
901        self.font_feature(FontFeature::SMALL_CAPS)
902    }
903
904    /// Zero renders with a slash or dot to tell it apart from the letter O.
905    fn font_slashed_zero(self) -> Self {
906        self.font_feature(FontFeature::SLASHED_ZERO)
907    }
908
909    /// Sequences like `1/2` render as fractions.
910    fn font_fractions(self) -> Self {
911        self.font_feature(FontFeature::FRACTIONS)
912    }
913
914    /// Disable standard ligatures like `fi` or the joined `=>` of coding fonts.
915    fn font_no_ligatures(self) -> Self {
916        self.font_feature(FontFeature::NO_LIGATURES)
917    }
918
919    /// Add a font family to try, in order of preference.
920    fn font_family(mut self, font_family: impl Into<Cow<'static, str>>) -> Self {
921        self.text_style_data_mut()
922            .font_families
923            .push(font_family.into());
924        self
925    }
926
927    /// Set the slant (style) of the font. See [`FontSlant`].
928    fn font_slant(mut self, font_slant: impl Into<FontSlant>) -> Self {
929        self.text_style_data_mut().font_slant = Some(font_slant.into());
930        self
931    }
932
933    /// Set the thickness of the font. See [`FontWeight`].
934    fn font_weight(mut self, font_weight: impl Into<FontWeight>) -> Self {
935        self.text_style_data_mut().font_weight = Some(font_weight.into());
936        self
937    }
938
939    /// Set the horizontal width of the font. See [`FontWidth`].
940    fn font_width(mut self, font_width: impl Into<FontWidth>) -> Self {
941        self.text_style_data_mut().font_width = Some(font_width.into());
942        self
943    }
944
945    /// Set how the leading of the first and last lines is handled. See [`TextHeightBehavior`].
946    fn text_height(mut self, text_height: impl Into<TextHeightBehavior>) -> Self {
947        self.text_style_data_mut().text_height = Some(text_height.into());
948        self
949    }
950
951    /// Add a shadow cast behind the text, replacing inherited shadows. See [`TextShadow`].
952    fn text_shadow(mut self, text_shadow: impl Into<TextShadow>) -> Self {
953        self.text_style_data_mut()
954            .text_shadows
955            .get_or_insert_default()
956            .push(text_shadow.into());
957        self
958    }
959
960    /// Replace the text shadows. An empty list clears inherited shadows.
961    fn text_shadows(mut self, text_shadows: impl IntoIterator<Item = TextShadow>) -> Self {
962        self.text_style_data_mut().text_shadows = Some(text_shadows.into_iter().collect());
963        self
964    }
965
966    /// Set a line drawn through, under or over the text. See [`TextDecoration`].
967    fn text_decoration(mut self, text_decoration: impl Into<TextDecoration>) -> Self {
968        self.text_style_data_mut().text_decoration = Some(text_decoration.into());
969        self
970    }
971}
972
973/// Methods for truncating text within an element's bounds.
974pub trait TextOverflowExt: TextStyleExt {
975    /// Set how text that does not fit its bounds is truncated. See [`TextOverflow`].
976    fn text_overflow(mut self, text_overflow: impl Into<TextOverflow>) -> Self {
977        self.text_style_data_mut().text_overflow = Some(text_overflow.into());
978        self
979    }
980}
981
982/// Methods for painting an element's background.
983pub trait BackgroundExt: StyleExt {
984    /// Paint the background with a color, gradient or shader. See [`Fill`].
985    fn background(mut self, background: impl Into<Fill>) -> Self {
986        self.style_mut().background = background.into();
987        self
988    }
989}
990
991/// Low-level access to an element's [`StyleState`].
992pub trait StyleExt
993where
994    Self: Sized,
995{
996    /// Returns a mutable reference to the element's style data.
997    fn style_mut(&mut self) -> &mut StyleState;
998
999    /// Replace all of the element's style data at once. See [`StyleState`].
1000    fn style(mut self, style: StyleState) -> Self {
1001        *self.style_mut() = style;
1002        self
1003    }
1004}
1005
1006/// Methods for decorating an element.
1007pub trait DecorationExt: StyleExt {
1008    /// Add an outline around the element. See [`Border`].
1009    fn border(mut self, border: impl Into<Option<Border>>) -> Self {
1010        if let Some(border) = border.into() {
1011            self.style_mut().borders.push(border);
1012        }
1013        self
1014    }
1015
1016    /// Add a shadow cast by the element. See [`Shadow`].
1017    fn shadow(mut self, shadow: impl Into<Shadow>) -> Self {
1018        self.style_mut().shadows.push(shadow.into());
1019        self
1020    }
1021
1022    /// Round the element's corners. See [`CornerRadius`].
1023    fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self {
1024        self.style_mut().corner_radius = corner_radius.into();
1025        self
1026    }
1027}
1028
1029impl<T: DecorationExt> CornerRadiusExt for T {
1030    fn with_corner_radius(mut self, corner_radius: f32) -> Self {
1031        self.style_mut().corner_radius = CornerRadius::new_all(corner_radius);
1032        self
1033    }
1034}
1035
1036/// Shorthand methods for setting an element's [`CornerRadius`] to common values.
1037pub trait CornerRadiusExt: Sized {
1038    /// Round all four corners to the given radius in pixels.
1039    fn with_corner_radius(self, corner_radius: f32) -> Self;
1040
1041    /// Shortcut for `corner_radius(0.)` - removes border radius.
1042    fn rounded_none(self) -> Self {
1043        self.with_corner_radius(0.)
1044    }
1045
1046    /// Shortcut for `corner_radius(6.)` - default border radius.
1047    fn rounded(self) -> Self {
1048        self.with_corner_radius(6.)
1049    }
1050
1051    /// Shortcut for `corner_radius(4.)` - small border radius.
1052    fn rounded_sm(self) -> Self {
1053        self.with_corner_radius(4.)
1054    }
1055
1056    /// Shortcut for `corner_radius(6.)` - medium border radius.
1057    fn rounded_md(self) -> Self {
1058        self.with_corner_radius(6.)
1059    }
1060
1061    /// Shortcut for `corner_radius(8.)` - large border radius.
1062    fn rounded_lg(self) -> Self {
1063        self.with_corner_radius(8.)
1064    }
1065
1066    /// Shortcut for `corner_radius(12.)` - extra large border radius.
1067    fn rounded_xl(self) -> Self {
1068        self.with_corner_radius(12.)
1069    }
1070
1071    /// Shortcut for `corner_radius(16.)` - extra large border radius.
1072    fn rounded_2xl(self) -> Self {
1073        self.with_corner_radius(16.)
1074    }
1075
1076    /// Shortcut for `corner_radius(24.)` - extra large border radius.
1077    fn rounded_3xl(self) -> Self {
1078        self.with_corner_radius(24.)
1079    }
1080
1081    /// Shortcut for `corner_radius(32.)` - extra large border radius.
1082    fn rounded_4xl(self) -> Self {
1083        self.with_corner_radius(32.)
1084    }
1085
1086    /// Shortcut for `corner_radius(99.)` - fully rounded (pill shape).
1087    fn rounded_full(self) -> Self {
1088        self.with_corner_radius(99.)
1089    }
1090}
1091
1092/// Methods for applying changes to an element conditionally.
1093pub trait MaybeExt
1094where
1095    Self: Sized,
1096{
1097    /// Apply `then` to the element only when the condition is `true`.
1098    fn maybe(self, bool: impl Into<bool>, then: impl FnOnce(Self) -> Self) -> Self {
1099        if bool.into() { then(self) } else { self }
1100    }
1101
1102    /// Apply `then` to the element only when the [`Option`] is [`Some`], passing the inner value.
1103    fn map<T>(self, data: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self {
1104        if let Some(data) = data {
1105            then(self, data)
1106        } else {
1107            self
1108        }
1109    }
1110}
1111
1112/// Method for controlling which painting layer an element belongs to.
1113pub trait LayerExt
1114where
1115    Self: Sized,
1116{
1117    /// Returns a mutable reference to the element's layer.
1118    fn layer_mut(&mut self) -> &mut Layer;
1119
1120    /// Sets the element's painting layer without changing its layout or position.
1121    ///
1122    /// Higher layers paint on top of lower layers. An integer is a [`Layer::Relative`]
1123    /// offset from the normal layer, which is one above the parent's layer.
1124    /// The default is `0`. Descendants use this element's resulting layer as their base.
1125    ///
1126    /// Use [`Layer::Overlay`] to raise content relative to its parent and escape
1127    /// ancestor clipping, or [`Layer::OverlayLevel`] for an absolute overlay level.
1128    /// Elements on the same layer have no guaranteed painting order.
1129    ///
1130    /// ```rust
1131    /// # use freya_core::prelude::*;
1132    /// rect()
1133    ///     .child(rect().layer(-1).child("Below default siblings"))
1134    ///     .child(rect().child("Default layer"))
1135    ///     .child(rect().layer(1).child("Above default siblings"))
1136    ///     .child(rect().layer(Layer::Overlay).child("Overlay"))
1137    /// # ;
1138    /// ```
1139    fn layer(mut self, layer: impl Into<Layer>) -> Self {
1140        *self.layer_mut() = layer.into();
1141        self
1142    }
1143}
1144
1145pub trait ScrollableExt
1146where
1147    Self: Sized,
1148{
1149    /// Returns a mutable reference to the element's effect data.
1150    fn effect_mut(&mut self) -> &mut EffectData;
1151
1152    /// Mark this element as scrollable.
1153    /// You are probably looking for the `ScrollView` component instead.
1154    fn scrollable(mut self, scrollable: impl Into<bool>) -> Self {
1155        self.effect_mut().scrollable = scrollable.into();
1156        self
1157    }
1158}
1159
1160/// Method for controlling whether an element responds to pointer events.
1161pub trait InteractiveExt
1162where
1163    Self: Sized,
1164{
1165    /// Returns a mutable reference to the element's effect data.
1166    fn effect_mut(&mut self) -> &mut EffectData;
1167
1168    /// Set whether the element receives pointer events. See [`Interactive`].
1169    fn interactive(mut self, interactive: impl Into<Interactive>) -> Self {
1170        self.effect_mut().interactive = interactive.into();
1171        self
1172    }
1173}
1174
1175/// Methods for visual effects applied to an element: clipping, backdrop blur, rotation, opacity and scale.
1176pub trait EffectExt: Sized {
1177    /// Returns a mutable reference to the element's effect data.
1178    fn effect_mut(&mut self) -> &mut EffectData;
1179
1180    /// Set the [`CursorIcon`] shown while the element is hovered.
1181    ///
1182    /// When multiple hovered elements define a cursor, the one painted on top wins.
1183    /// While a mouse button is pressed the cursor stays still.
1184    fn cursor(mut self, cursor: impl Into<Option<CursorIcon>>) -> Self {
1185        self.effect_mut().cursor = cursor.into();
1186        self
1187    }
1188
1189    /// Show or hide the mouse cursor while the element is hovered.
1190    ///
1191    /// The topmost hovered element with an explicit visibility wins, defaulting to visible.
1192    fn cursor_visible(mut self, visible: impl Into<Option<bool>>) -> Self {
1193        self.effect_mut().cursor_visible = visible.into();
1194        self
1195    }
1196
1197    /// Replace all of the element's effect data at once. See [`EffectData`].
1198    fn effect(mut self, effect: EffectData) -> Self {
1199        *self.effect_mut() = effect;
1200        self
1201    }
1202
1203    /// Set whether content overflowing the element's bounds is clipped. See [`Overflow`].
1204    fn overflow(mut self, overflow: impl Into<Overflow>) -> Self {
1205        self.effect_mut().overflow = overflow.into();
1206        self
1207    }
1208
1209    /// Apply a Gaussian blur of the given radius to the backdrop behind the element.
1210    fn backdrop_blur(mut self, blur: f32) -> Self {
1211        self.effect_mut().blur = Some(blur);
1212        self
1213    }
1214
1215    /// Rotate the element by the given angle in degrees.
1216    fn rotation(mut self, rotation: f32) -> Self {
1217        self.effect_mut().rotation = Some(rotation);
1218        self
1219    }
1220
1221    /// Mask this element and its children using the fill's opacity.
1222    fn mask(mut self, mask: impl Into<Fill>) -> Self {
1223        self.effect_mut().mask = Some(mask.into());
1224        self
1225    }
1226
1227    /// Set the element's opacity, from `0.0` (transparent) to `1.0` (opaque).
1228    fn opacity(mut self, opacity: f32) -> Self {
1229        self.effect_mut().opacity = Some(opacity);
1230        self
1231    }
1232
1233    /// Scale the element. See [`Scale`].
1234    fn scale(mut self, scale: impl Into<Scale>) -> Self {
1235        self.effect_mut().scale = Some(scale.into());
1236        self
1237    }
1238
1239    /// Set the point that the scale and rotation effects pivot around.
1240    ///
1241    /// Defaults to the element's center.
1242    fn transform_origin(mut self, transform_origin: impl Into<TransformOrigin>) -> Self {
1243        self.effect_mut().transform_origin = transform_origin.into();
1244        self
1245    }
1246}