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
69pub trait ElementExt: Any {
86 fn into_element(self) -> Element
88 where
89 Self: Sized + Into<Element>,
90 {
91 self.into()
92 }
93
94 fn changed(&self, _other: &Rc<dyn ElementExt>) -> bool {
96 false
97 }
98
99 fn diff(&self, _other: &Rc<dyn ElementExt>) -> DiffModifies {
101 DiffModifies::empty()
102 }
103
104 fn layout(&'_ self) -> Cow<'_, LayoutData> {
106 Cow::Owned(Default::default())
107 }
108
109 fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
111 Cow::Owned(Default::default())
112 }
113
114 fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
116 None
117 }
118
119 fn style(&'_ self) -> Cow<'_, StyleState> {
121 Cow::Owned(Default::default())
122 }
123
124 fn is_transparent(&self) -> bool {
127 self.style().background == Fill::Color(Color::TRANSPARENT)
128 }
129
130 fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
132 Cow::Owned(Default::default())
133 }
134
135 fn layer(&self) -> Layer {
137 Layer::default()
138 }
139
140 fn events_handlers(&'_ self) -> Option<Cow<'_, EventHandlers>> {
142 None
143 }
144
145 fn measure(&self, _context: LayoutContext) -> Option<(Size2D, Rc<dyn Any>)> {
147 None
148 }
149
150 fn should_hook_measurement(&self) -> bool {
152 false
153 }
154
155 fn should_measure_inner_children(&self) -> bool {
157 true
158 }
159
160 fn needs_post_measure(&self) -> bool {
162 false
163 }
164
165 fn post_measure(&self, _context: PostMeasureContext) -> PostMeasure<NodeId> {
167 PostMeasure::default()
168 }
169
170 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 fn clip(&self, _context: ClipContext) {}
180
181 fn paints_content(&self) -> bool {
183 true
184 }
185
186 fn render(&self, _context: RenderContext) {}
188
189 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 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
331pub trait App: 'static {
335 fn render(&self) -> impl IntoElement;
336}
337
338#[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
394pub 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}