freya_core/states/
canvas.rs

1use freya_native_core::{
2    attributes::AttributeName,
3    exports::shipyard::Component,
4    node::{
5        NodeType,
6        OwnedAttributeValue,
7    },
8    node_ref::NodeView,
9    prelude::{
10        AttributeMaskBuilder,
11        Dependancy,
12        NodeMaskBuilder,
13        State,
14    },
15    tags::TagName,
16    SendAnyMap,
17};
18use freya_native_core_macro::partial_derive_state;
19
20use crate::custom_attributes::{
21    CanvasReference,
22    CustomAttributeValues,
23};
24
25#[derive(Default, PartialEq, Clone, Debug, Component)]
26pub struct CanvasState {
27    pub canvas_ref: Option<CanvasReference>,
28}
29
30#[partial_derive_state]
31impl State<CustomAttributeValues> for CanvasState {
32    type ParentDependencies = ();
33
34    type ChildDependencies = ();
35
36    type NodeDependencies = ();
37
38    const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
39        .with_attrs(AttributeMaskBuilder::Some(&[
40            AttributeName::CanvasReference,
41        ]))
42        .with_tag();
43
44    fn allow_node(node_type: &NodeType<CustomAttributeValues>) -> bool {
45        node_type.tag() == Some(&TagName::Rect)
46    }
47
48    fn update<'a>(
49        &mut self,
50        node_view: NodeView<CustomAttributeValues>,
51        _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
52        _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
53        _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
54        _context: &SendAnyMap,
55    ) -> bool {
56        let mut canvas = CanvasState::default();
57
58        if let Some(attributes) = node_view.attributes() {
59            for attr in attributes {
60                #[allow(clippy::single_match)]
61                match attr.attribute {
62                    AttributeName::CanvasReference => {
63                        if let OwnedAttributeValue::Custom(CustomAttributeValues::Canvas(
64                            new_canvas,
65                        )) = attr.value
66                        {
67                            canvas.canvas_ref = Some(new_canvas.clone());
68                        }
69                    }
70                    _ => {}
71                }
72            }
73        }
74
75        let changed = &canvas != self;
76
77        *self = canvas;
78        changed
79    }
80}