Skip to main content

freya_core/
element.rs

1use std::{
2    any::{
3        Any,
4        TypeId,
5    },
6    borrow::Cow,
7    fmt::Debug,
8    rc::Rc,
9};
10
11use freya_engine::prelude::{
12    Canvas,
13    FontCollection,
14    FontMgr,
15    SkRRect,
16    SkRect,
17};
18use rustc_hash::FxHashMap;
19use torin::{
20    prelude::{
21        Area,
22        LayoutNode,
23        PostMeasure,
24        Size2D,
25    },
26    scaled::Scaled,
27    torin::Torin,
28};
29
30use crate::{
31    data::{
32        AccessibilityData,
33        EffectData,
34        LayoutData,
35        StyleState,
36        TextStyleData,
37        TextStyleState,
38    },
39    diff_key::DiffKey,
40    event_handler::EventHandler,
41    events::{
42        data::{
43            AccessibilityActionEventData,
44            Event,
45            KeyboardEventData,
46            MouseEventData,
47            PointerEventData,
48            SizedEventData,
49            StyledEventData,
50            TouchEventData,
51            VisibleEventData,
52            WheelEventData,
53        },
54        name::EventName,
55    },
56    layers::Layer,
57    node_id::NodeId,
58    prelude::{
59        Color,
60        DragEventData,
61        ImePreeditEventData,
62        MaybeExt,
63    },
64    style::fill::Fill,
65    text_cache::TextCache,
66    tree::DiffModifies,
67};
68
69/// Tells Freya how to lay out, handle events for, describe accessibility and draw an element.
70///
71/// To make your own element, implement this trait and override what you need. For example,
72/// [`render`](Self::render) draws it, [`layout`](Self::layout) supplies its layout,
73/// [`measure`](Self::measure) gives it a custom size, and [`is_point_inside`](Self::is_point_inside)
74/// changes how pointer hits are detected. Everything has a default, so you can start with just
75/// the methods your element needs. Override [`changed`](Self::changed) and [`diff`](Self::diff)
76/// when changes to its data need to update the UI.
77///
78/// To put it in the UI tree, implement `From<YourElement> for Element` (or otherwise make it
79/// convertible into [`Element`]). You can also implement builder traits like `LayoutExt` to let
80/// callers set its properties. Freya stores elements as `Rc<dyn ElementExt>`, so they must be
81/// `'static` through the [`Any`].
82///
83/// See [`feature_element.rs`](https://github.com/marc2332/freya/blob/main/examples/feature_element.rs)
84/// for a full example.
85pub trait ElementExt: Any {
86    /// Converts this value into an [`Element`] if it implements `Into<Element>`.
87    fn into_element(self) -> Element
88    where
89        Self: Sized + Into<Element>,
90    {
91        self.into()
92    }
93
94    /// Returns whether this element has changed compared to another one.
95    fn changed(&self, _other: &Rc<dyn ElementExt>) -> bool {
96        false
97    }
98
99    /// Tells Freya what needs updating when this element changes.
100    fn diff(&self, _other: &Rc<dyn ElementExt>) -> DiffModifies {
101        DiffModifies::empty()
102    }
103
104    /// Returns layout properties used to position and size this element.
105    fn layout(&'_ self) -> Cow<'_, LayoutData> {
106        Cow::Owned(Default::default())
107    }
108
109    /// Returns accessibility properties for this element.
110    fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
111        Cow::Owned(Default::default())
112    }
113
114    /// Returns optional effect properties for this element.
115    fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
116        None
117    }
118
119    /// Returns visual style properties for this element.
120    fn style(&'_ self) -> Cow<'_, StyleState> {
121        Cow::Owned(Default::default())
122    }
123
124    /// Whether the element paints nothing, letting events fall through to
125    /// non-ancestor elements behind it.
126    fn is_transparent(&self) -> bool {
127        self.style().background == Fill::Color(Color::TRANSPARENT)
128    }
129
130    /// Returns text styling inherited by text content in this element.
131    fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
132        Cow::Owned(Default::default())
133    }
134
135    /// Returns the drawing layer assigned to this element.
136    fn layer(&self) -> Layer {
137        Layer::default()
138    }
139
140    /// Returns event handlers registered on this element.
141    fn events_handlers(&'_ self) -> Option<Cow<'_, EventHandlers>> {
142        None
143    }
144
145    /// Measures the element and optionally returns measurement data for later layout stages.
146    fn measure(&self, _context: LayoutContext) -> Option<(Size2D, Rc<dyn Any>)> {
147        None
148    }
149
150    /// Returns whether this element hooks into layout measurement.
151    fn should_hook_measurement(&self) -> bool {
152        false
153    }
154
155    /// Returns whether to measure this element's children.
156    fn should_measure_inner_children(&self) -> bool {
157        true
158    }
159
160    /// Whether this element needs a [ElementExt::post_measure] step after the layout pass.
161    fn needs_post_measure(&self) -> bool {
162        false
163    }
164
165    /// Runs after this element and its children are measured.
166    fn post_measure(&self, _context: PostMeasureContext) -> PostMeasure<NodeId> {
167        PostMeasure::default()
168    }
169
170    /// Tests whether the pointer position is inside this element's hit area.
171    fn is_point_inside(&self, context: EventMeasurementContext) -> bool {
172        context
173            .layout_node
174            .visible_area()
175            .contains(context.cursor.to_f32())
176    }
177
178    /// Applies clipping for this element before it and its children are rendered.
179    fn clip(&self, _context: ClipContext) {}
180
181    /// Whether this element paints content, excluding backdrop effects and descendants.
182    fn paints_content(&self) -> bool {
183        true
184    }
185
186    /// Renders this element using the supplied canvas and layout context.
187    fn render(&self, _context: RenderContext) {}
188
189    /// Creates a rounded rectangle from an area using this element's corner radius.
190    fn render_rect(&self, area: &Area, scale_factor: f32) -> SkRRect {
191        let style = self.style();
192        let corner_radius = style.corner_radius.with_scale(scale_factor);
193        SkRRect::new_rect_radii(
194            SkRect::new(area.min_x(), area.min_y(), area.max_x(), area.max_y()),
195            &[
196                (corner_radius.top_left(), corner_radius.top_left()).into(),
197                (corner_radius.top_right(), corner_radius.top_right()).into(),
198                (corner_radius.bottom_right(), corner_radius.bottom_right()).into(),
199                (corner_radius.bottom_left(), corner_radius.bottom_left()).into(),
200            ],
201        )
202    }
203
204    /// Mutates the accessibility node immediately before it enters the accessibility tree.
205    fn finish_accessibility(&self, _builder: &mut accesskit::Node) {}
206}
207
208#[allow(dead_code)]
209pub struct LayoutContext<'a> {
210    pub node_id: NodeId,
211    pub torin_node: &'a torin::node::Node,
212    pub area_size: &'a Size2D,
213    pub font_collection: &'a mut FontCollection,
214    pub font_manager: &'a FontMgr,
215    pub text_style_state: &'a TextStyleState,
216    pub fallback_fonts: &'a [Cow<'static, str>],
217    pub scale_factor: f64,
218    pub text_cache: &'a mut TextCache,
219}
220
221#[allow(dead_code)]
222pub struct RenderContext<'a> {
223    pub font_collection: &'a mut FontCollection,
224    pub canvas: &'a Canvas,
225    pub layout_node: &'a LayoutNode,
226    pub text_style_state: &'a TextStyleState,
227    pub scale_factor: f64,
228}
229
230pub struct EventMeasurementContext<'a> {
231    pub cursor: ragnarok::CursorPoint,
232    pub layout_node: &'a LayoutNode,
233    pub scale_factor: f64,
234}
235
236pub struct PostMeasureContext<'a> {
237    pub node_layout: &'a LayoutNode,
238    pub children: &'a [NodeId],
239    pub layout: &'a Torin<NodeId>,
240    pub font_collection: &'a mut FontCollection,
241    pub text_style_state: &'a TextStyleState,
242    pub fallback_fonts: &'a [Cow<'static, str>],
243    pub scale_factor: f64,
244}
245
246pub struct ClipContext<'a> {
247    pub canvas: &'a Canvas,
248    pub visible_area: &'a Area,
249    pub scale_factor: f64,
250}
251
252impl<T: Any + PartialEq> ComponentProps for T {
253    fn changed(&self, other: &dyn ComponentProps) -> bool {
254        (other as &dyn Any)
255            .downcast_ref::<T>()
256            .is_none_or(|other| self != other)
257    }
258}
259
260pub trait ComponentProps: Any {
261    fn changed(&self, other: &dyn ComponentProps) -> bool;
262}
263
264#[derive(Clone, Debug)]
265pub enum ElementChildren {
266    Owned(Vec<Element>),
267    Retained(Rc<Vec<Element>>),
268}
269
270impl Default for ElementChildren {
271    fn default() -> Self {
272        Self::Owned(Vec::new())
273    }
274}
275
276impl From<Vec<Element>> for ElementChildren {
277    fn from(children: Vec<Element>) -> Self {
278        Self::Owned(children)
279    }
280}
281
282impl PartialEq for ElementChildren {
283    fn eq(&self, other: &Self) -> bool {
284        match (self, other) {
285            (Self::Owned(children), Self::Owned(previous)) => children == previous,
286            (Self::Retained(children), Self::Retained(previous)) => {
287                Rc::ptr_eq(children, previous) || children == previous
288            }
289            (Self::Owned(owned), Self::Retained(retained))
290            | (Self::Retained(retained), Self::Owned(owned)) => owned == retained.as_ref(),
291        }
292    }
293}
294
295#[derive(Clone)]
296pub enum Element {
297    Component {
298        key: DiffKey,
299        comp: Rc<dyn Fn(Rc<dyn ComponentProps>) -> Element>,
300        props: Rc<dyn ComponentProps>,
301    },
302    Element {
303        key: DiffKey,
304        element: Rc<dyn ElementExt>,
305        elements: ElementChildren,
306    },
307}
308
309impl Debug for Element {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        match self {
312            Self::Element { key, elements, .. } => {
313                f.write_str(&format!("Element {{ key: {:?} }}", key))?;
314                elements.fmt(f)
315            }
316            Self::Component { key, .. } => f.write_str(&format!("Component {{ key: {:?} }}", key)),
317        }
318    }
319}
320
321pub trait IntoElement {
322    fn into_element(self) -> Element;
323}
324
325impl<T: Into<Element>> IntoElement for T {
326    fn into_element(self) -> Element {
327        self.into()
328    }
329}
330
331/// [App] is a trait for root-level application components.
332/// Types implementing [App] automatically implement [Component] and have a
333/// blanket [PartialEq] implementation that always returns true.
334pub trait App: 'static {
335    fn render(&self) -> impl IntoElement;
336}
337
338/// [AppComponent] is a wrapper for [App] components that returns true in equality checks.
339#[derive(Clone)]
340pub struct AppComponent {
341    render: Rc<dyn Fn() -> Element + 'static>,
342}
343
344impl AppComponent {
345    pub fn new(render: impl App + 'static) -> Self {
346        Self {
347            render: Rc::new(move || render.render().into_element()),
348        }
349    }
350}
351
352impl PartialEq for AppComponent {
353    fn eq(&self, _other: &Self) -> bool {
354        true
355    }
356}
357
358#[cfg(feature = "hotreload")]
359impl<F, E> From<F> for AppComponent
360where
361    F: Fn() -> E + Clone + 'static,
362    E: IntoElement,
363{
364    fn from(render: F) -> Self {
365        AppComponent {
366            render: Rc::new(move || {
367                crate::hotreload::subsecond::HotFn::current(render.clone())
368                    .call(())
369                    .into_element()
370            }),
371        }
372    }
373}
374
375#[cfg(not(feature = "hotreload"))]
376impl<F, E> From<F> for AppComponent
377where
378    F: Fn() -> E + 'static,
379    E: IntoElement,
380{
381    fn from(render: F) -> Self {
382        AppComponent {
383            render: Rc::new(move || render().into_element()),
384        }
385    }
386}
387
388impl Component for AppComponent {
389    fn render(&self) -> impl IntoElement {
390        (self.render)()
391    }
392}
393
394/// Encapsulate reusable pieces of UI by using the [Component] trait.
395/// Every [Component] creates a new layer of state in the app,
396/// meaning that implementors of [Component] can make use of hooks in their [Component::render] method.
397/// ```rust, no_run
398/// # use freya::prelude::*;
399/// #[derive(PartialEq)]
400/// struct ReusableCounter {
401///     pub init_number: u8,
402/// }
403///
404/// impl Component for ReusableCounter {
405///     fn render(&self) -> impl IntoElement {
406///         let mut number = use_state(|| self.init_number);
407///         label()
408///             .on_press(move |_| {
409///                 *number.write() += 1;
410///             })
411///             .text(number.read().to_string())
412///     }
413/// }
414/// ```
415pub trait Component: ComponentKey + PartialEq + 'static {
416    fn render(&self) -> impl IntoElement;
417
418    fn render_key(&self) -> DiffKey {
419        self.default_key()
420    }
421}
422
423pub trait ComponentOwned: ComponentKey + PartialEq + 'static {
424    fn render(self) -> impl IntoElement;
425
426    fn render_key(&self) -> DiffKey {
427        self.default_key()
428    }
429}
430
431pub trait ComponentKey {
432    fn default_key(&self) -> DiffKey;
433}
434
435impl<T> Component for T
436where
437    T: ComponentOwned + Clone + PartialEq,
438{
439    fn render(&self) -> impl IntoElement {
440        <Self as ComponentOwned>::render(self.clone())
441    }
442    fn render_key(&self) -> DiffKey {
443        <Self as ComponentOwned>::render_key(self)
444    }
445}
446
447impl<T> ComponentKey for T
448where
449    T: Component,
450{
451    fn default_key(&self) -> DiffKey {
452        use std::hash::{
453            Hash,
454            Hasher,
455        };
456        let mut hasher = rustc_hash::FxHasher::default();
457        TypeId::of::<T>().hash(&mut hasher);
458        DiffKey::DefaultU64(hasher.finish())
459    }
460}
461
462impl<T> MaybeExt for T where T: Component {}
463
464impl<T: Component> From<T> for Element {
465    fn from(value: T) -> Self {
466        let key = value.render_key();
467        Element::Component {
468            key,
469            #[cfg(feature = "hotreload")]
470            comp: Rc::new(move |props| {
471                let props = (&*props as &dyn Any).downcast_ref::<T>().unwrap();
472                crate::hotreload::subsecond::HotFn::current(|v: &T| v.render().into_element())
473                    .call((props,))
474            }),
475            #[cfg(not(feature = "hotreload"))]
476            comp: Rc::new(move |props| {
477                let props = (&*props as &dyn Any).downcast_ref::<T>().unwrap();
478                props.render().into_element()
479            }),
480            props: Rc::new(value),
481        }
482    }
483}
484
485impl PartialEq for Element {
486    fn eq(&self, other: &Self) -> bool {
487        match (self, other) {
488            (
489                Self::Component {
490                    key: key1,
491                    props: props1,
492                    ..
493                },
494                Self::Component {
495                    key: key2,
496                    props: props2,
497                    ..
498                },
499            ) => key1 == key2 && !props1.changed(props2.as_ref()),
500            (
501                Self::Element {
502                    key: key1,
503                    element: element1,
504                    elements: elements1,
505                },
506                Self::Element {
507                    key: key2,
508                    element: element2,
509                    elements: elements2,
510                },
511            ) => key1 == key2 && !element1.changed(element2) && elements1 == elements2,
512            _ => false,
513        }
514    }
515}
516
517pub type EventHandlers = FxHashMap<EventName, EventHandlerType>;
518
519#[derive(Clone, PartialEq)]
520pub enum EventHandlerType {
521    AccessibilityAction(EventHandler<Event<AccessibilityActionEventData>>),
522    Mouse(EventHandler<Event<MouseEventData>>),
523    Keyboard(EventHandler<Event<KeyboardEventData>>),
524    Sized(EventHandler<Event<SizedEventData>>),
525    Visible(EventHandler<Event<VisibleEventData>>),
526    Styled(EventHandler<Event<StyledEventData>>),
527    Wheel(EventHandler<Event<WheelEventData>>),
528    Touch(EventHandler<Event<TouchEventData>>),
529    Pointer(EventHandler<Event<PointerEventData>>),
530    ImePreedit(EventHandler<Event<ImePreeditEventData>>),
531    Drag(EventHandler<Event<DragEventData>>),
532}