1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::sync::Arc;

use dioxus_core::{
    prelude::spawn,
    use_hook,
    AttributeValue,
};
use dioxus_signals::{
    ReadOnlySignal,
    Readable,
    Signal,
    Writable,
};
use freya_common::NodeReferenceLayout;
use freya_node_state::{
    CustomAttributeValues,
    NodeReference,
};
use tokio::sync::watch::channel;

/// Subscribe to a Node layout changes.
pub fn use_node() -> (AttributeValue, NodeReferenceLayout) {
    let (tx, signal) = use_hook(|| {
        let (tx, mut rx) = channel::<NodeReferenceLayout>(NodeReferenceLayout::default());
        let mut signal = Signal::new(NodeReferenceLayout::default());

        spawn(async move {
            while rx.changed().await.is_ok() {
                if *signal.peek() != *rx.borrow() {
                    signal.set(rx.borrow().clone());
                }
            }
        });

        (Arc::new(tx), signal)
    });

    (
        AttributeValue::any_value(CustomAttributeValues::Reference(NodeReference(tx))),
        signal.read_unchecked().clone(),
    )
}

/// Get a signal to read the latest layout from a Node.
pub fn use_node_signal() -> (AttributeValue, ReadOnlySignal<NodeReferenceLayout>) {
    let (tx, signal) = use_hook(|| {
        let (tx, mut rx) = channel::<NodeReferenceLayout>(NodeReferenceLayout::default());
        let mut signal = Signal::new(NodeReferenceLayout::default());

        spawn(async move {
            while rx.changed().await.is_ok() {
                if *signal.peek() != *rx.borrow() {
                    signal.set(rx.borrow().clone());
                }
            }
        });

        (Arc::new(tx), signal)
    });

    (
        AttributeValue::any_value(CustomAttributeValues::Reference(NodeReference(tx))),
        signal.into(),
    )
}

pub fn use_node_signal_with_prev() -> (
    AttributeValue,
    ReadOnlySignal<Option<NodeReferenceLayout>>,
    ReadOnlySignal<Option<NodeReferenceLayout>>,
) {
    let (tx, curr_signal, prev_signal) = use_hook(|| {
        let (tx, mut rx) = channel::<NodeReferenceLayout>(NodeReferenceLayout::default());
        let mut curr_signal = Signal::new(None);
        let mut prev_signal = Signal::new(None);

        spawn(async move {
            while rx.changed().await.is_ok() {
                if *curr_signal.peek() != Some(rx.borrow().clone()) {
                    prev_signal.set(curr_signal());
                    curr_signal.set(Some(rx.borrow().clone()));
                }
            }
        });

        (Arc::new(tx), curr_signal, prev_signal)
    });

    (
        AttributeValue::any_value(CustomAttributeValues::Reference(NodeReference(tx))),
        curr_signal.into(),
        prev_signal.into(),
    )
}

#[cfg(test)]
mod test {
    use freya::prelude::*;
    use freya_testing::prelude::*;

    use crate::use_node;

    #[tokio::test]
    pub async fn track_size() {
        fn use_node_app() -> Element {
            let (reference, size) = use_node();

            rsx!(
                rect {
                    reference: reference,
                    width: "50%",
                    height: "25%",
                    label {
                        "{size.area.width()}"
                    }
                }
            )
        }

        let mut utils = launch_test_with_config(
            use_node_app,
            TestingConfig::<()> {
                size: (500.0, 800.0).into(),
                ..TestingConfig::default()
            },
        );

        utils.wait_for_update().await;
        let root = utils.root().get(0);
        assert_eq!(
            root.get(0).get(0).text().unwrap().parse::<f32>(),
            Ok(500.0 * 0.5)
        );

        utils.resize((300.0, 800.0).into());
        utils.wait_for_update().await;

        let root = utils.root().get(0);
        assert_eq!(
            root.get(0).get(0).text().unwrap().parse::<f32>(),
            Ok(300.0 * 0.5)
        );
    }
}