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 FileEventData,
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 render(&self, _context: RenderContext) {}
183
184 fn render_rect(&self, area: &Area, scale_factor: f32) -> SkRRect {
186 let style = self.style();
187 let corner_radius = style.corner_radius.with_scale(scale_factor);
188 SkRRect::new_rect_radii(
189 SkRect::new(area.min_x(), area.min_y(), area.max_x(), area.max_y()),
190 &[
191 (corner_radius.top_left(), corner_radius.top_left()).into(),
192 (corner_radius.top_right(), corner_radius.top_right()).into(),
193 (corner_radius.bottom_right(), corner_radius.bottom_right()).into(),
194 (corner_radius.bottom_left(), corner_radius.bottom_left()).into(),
195 ],
196 )
197 }
198
199 fn finish_accessibility(&self, _builder: &mut accesskit::Node) {}
201}
202
203#[allow(dead_code)]
204pub struct LayoutContext<'a> {
205 pub node_id: NodeId,
206 pub torin_node: &'a torin::node::Node,
207 pub area_size: &'a Size2D,
208 pub font_collection: &'a mut FontCollection,
209 pub font_manager: &'a FontMgr,
210 pub text_style_state: &'a TextStyleState,
211 pub fallback_fonts: &'a [Cow<'static, str>],
212 pub scale_factor: f64,
213 pub text_cache: &'a mut TextCache,
214}
215
216#[allow(dead_code)]
217pub struct RenderContext<'a> {
218 pub font_collection: &'a mut FontCollection,
219 pub canvas: &'a Canvas,
220 pub layout_node: &'a LayoutNode,
221 pub text_style_state: &'a TextStyleState,
222 pub scale_factor: f64,
223}
224
225pub struct EventMeasurementContext<'a> {
226 pub cursor: ragnarok::CursorPoint,
227 pub layout_node: &'a LayoutNode,
228 pub scale_factor: f64,
229}
230
231pub struct PostMeasureContext<'a> {
232 pub node_layout: &'a LayoutNode,
233 pub children: &'a [NodeId],
234 pub layout: &'a Torin<NodeId>,
235 pub font_collection: &'a mut FontCollection,
236 pub text_style_state: &'a TextStyleState,
237 pub fallback_fonts: &'a [Cow<'static, str>],
238 pub scale_factor: f64,
239}
240
241pub struct ClipContext<'a> {
242 pub canvas: &'a Canvas,
243 pub visible_area: &'a Area,
244 pub scale_factor: f64,
245}
246
247impl<T: Any + PartialEq> ComponentProps for T {
248 fn changed(&self, other: &dyn ComponentProps) -> bool {
249 (other as &dyn Any)
250 .downcast_ref::<T>()
251 .is_none_or(|other| self != other)
252 }
253}
254
255pub trait ComponentProps: Any {
256 fn changed(&self, other: &dyn ComponentProps) -> bool;
257}
258
259#[derive(Clone, Debug)]
260pub enum ElementChildren {
261 Owned(Vec<Element>),
262 Retained(Rc<Vec<Element>>),
263}
264
265impl Default for ElementChildren {
266 fn default() -> Self {
267 Self::Owned(Vec::new())
268 }
269}
270
271impl From<Vec<Element>> for ElementChildren {
272 fn from(children: Vec<Element>) -> Self {
273 Self::Owned(children)
274 }
275}
276
277impl PartialEq for ElementChildren {
278 fn eq(&self, other: &Self) -> bool {
279 match (self, other) {
280 (Self::Owned(children), Self::Owned(previous)) => children == previous,
281 (Self::Retained(children), Self::Retained(previous)) => {
282 Rc::ptr_eq(children, previous) || children == previous
283 }
284 (Self::Owned(owned), Self::Retained(retained))
285 | (Self::Retained(retained), Self::Owned(owned)) => owned == retained.as_ref(),
286 }
287 }
288}
289
290#[derive(Clone)]
291pub enum Element {
292 Component {
293 key: DiffKey,
294 comp: Rc<dyn Fn(Rc<dyn ComponentProps>) -> Element>,
295 props: Rc<dyn ComponentProps>,
296 },
297 Element {
298 key: DiffKey,
299 element: Rc<dyn ElementExt>,
300 elements: ElementChildren,
301 },
302}
303
304impl Debug for Element {
305 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306 match self {
307 Self::Element { key, elements, .. } => {
308 f.write_str(&format!("Element {{ key: {:?} }}", key))?;
309 elements.fmt(f)
310 }
311 Self::Component { key, .. } => f.write_str(&format!("Component {{ key: {:?} }}", key)),
312 }
313 }
314}
315
316pub trait IntoElement {
317 fn into_element(self) -> Element;
318}
319
320impl<T: Into<Element>> IntoElement for T {
321 fn into_element(self) -> Element {
322 self.into()
323 }
324}
325
326pub trait App: 'static {
330 fn render(&self) -> impl IntoElement;
331}
332
333#[derive(Clone)]
335pub struct AppComponent {
336 render: Rc<dyn Fn() -> Element + 'static>,
337}
338
339impl AppComponent {
340 pub fn new(render: impl App + 'static) -> Self {
341 Self {
342 render: Rc::new(move || render.render().into_element()),
343 }
344 }
345}
346
347impl PartialEq for AppComponent {
348 fn eq(&self, _other: &Self) -> bool {
349 true
350 }
351}
352
353#[cfg(feature = "hotreload")]
354impl<F, E> From<F> for AppComponent
355where
356 F: Fn() -> E + Clone + 'static,
357 E: IntoElement,
358{
359 fn from(render: F) -> Self {
360 AppComponent {
361 render: Rc::new(move || {
362 crate::hotreload::subsecond::HotFn::current(render.clone())
363 .call(())
364 .into_element()
365 }),
366 }
367 }
368}
369
370#[cfg(not(feature = "hotreload"))]
371impl<F, E> From<F> for AppComponent
372where
373 F: Fn() -> E + 'static,
374 E: IntoElement,
375{
376 fn from(render: F) -> Self {
377 AppComponent {
378 render: Rc::new(move || render().into_element()),
379 }
380 }
381}
382
383impl Component for AppComponent {
384 fn render(&self) -> impl IntoElement {
385 (self.render)()
386 }
387}
388
389pub trait Component: ComponentKey + PartialEq + 'static {
411 fn render(&self) -> impl IntoElement;
412
413 fn render_key(&self) -> DiffKey {
414 self.default_key()
415 }
416}
417
418pub trait ComponentOwned: ComponentKey + PartialEq + 'static {
419 fn render(self) -> impl IntoElement;
420
421 fn render_key(&self) -> DiffKey {
422 self.default_key()
423 }
424}
425
426pub trait ComponentKey {
427 fn default_key(&self) -> DiffKey;
428}
429
430impl<T> Component for T
431where
432 T: ComponentOwned + Clone + PartialEq,
433{
434 fn render(&self) -> impl IntoElement {
435 <Self as ComponentOwned>::render(self.clone())
436 }
437 fn render_key(&self) -> DiffKey {
438 <Self as ComponentOwned>::render_key(self)
439 }
440}
441
442impl<T> ComponentKey for T
443where
444 T: Component,
445{
446 fn default_key(&self) -> DiffKey {
447 use std::hash::{
448 Hash,
449 Hasher,
450 };
451 let mut hasher = rustc_hash::FxHasher::default();
452 TypeId::of::<T>().hash(&mut hasher);
453 DiffKey::DefaultU64(hasher.finish())
454 }
455}
456
457impl<T> MaybeExt for T where T: Component {}
458
459impl<T: Component> From<T> for Element {
460 fn from(value: T) -> Self {
461 let key = value.render_key();
462 Element::Component {
463 key,
464 #[cfg(feature = "hotreload")]
465 comp: Rc::new(move |props| {
466 let props = (&*props as &dyn Any).downcast_ref::<T>().unwrap();
467 crate::hotreload::subsecond::HotFn::current(|v: &T| v.render().into_element())
468 .call((props,))
469 }),
470 #[cfg(not(feature = "hotreload"))]
471 comp: Rc::new(move |props| {
472 let props = (&*props as &dyn Any).downcast_ref::<T>().unwrap();
473 props.render().into_element()
474 }),
475 props: Rc::new(value),
476 }
477 }
478}
479
480impl PartialEq for Element {
481 fn eq(&self, other: &Self) -> bool {
482 match (self, other) {
483 (
484 Self::Component {
485 key: key1,
486 props: props1,
487 ..
488 },
489 Self::Component {
490 key: key2,
491 props: props2,
492 ..
493 },
494 ) => key1 == key2 && !props1.changed(props2.as_ref()),
495 (
496 Self::Element {
497 key: key1,
498 element: element1,
499 elements: elements1,
500 },
501 Self::Element {
502 key: key2,
503 element: element2,
504 elements: elements2,
505 },
506 ) => key1 == key2 && !element1.changed(element2) && elements1 == elements2,
507 _ => false,
508 }
509 }
510}
511
512pub type EventHandlers = FxHashMap<EventName, EventHandlerType>;
513
514#[derive(Clone, PartialEq)]
515pub enum EventHandlerType {
516 AccessibilityAction(EventHandler<Event<AccessibilityActionEventData>>),
517 Mouse(EventHandler<Event<MouseEventData>>),
518 Keyboard(EventHandler<Event<KeyboardEventData>>),
519 Sized(EventHandler<Event<SizedEventData>>),
520 Visible(EventHandler<Event<VisibleEventData>>),
521 Styled(EventHandler<Event<StyledEventData>>),
522 Wheel(EventHandler<Event<WheelEventData>>),
523 Touch(EventHandler<Event<TouchEventData>>),
524 Pointer(EventHandler<Event<PointerEventData>>),
525 ImePreedit(EventHandler<Event<ImePreeditEventData>>),
526 File(EventHandler<Event<FileEventData>>),
527}