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
145
use crate::Loader;
use dioxus::prelude::*;
use freya_elements::elements as dioxus_elements;

use freya_hooks::{use_applied_theme, use_focus, NetworkImageTheme, NetworkImageThemeWith};
use freya_node_state::bytes_to_data;
use reqwest::Url;

/// [`NetworkImage`] component properties.
#[derive(Props)]
pub struct NetworkImageProps<'a> {
    /// Theme override.
    #[props(optional)]
    pub theme: Option<NetworkImageThemeWith>,

    /// URL of the image
    pub url: Url,

    /// Fallback element
    #[props(optional)]
    pub fallback: Option<Element<'a>>,

    /// Loading element
    #[props(optional)]
    pub loading: Option<Element<'a>>,

    /// Information about the image.
    #[props(optional, into)]
    pub alt: Option<String>,
}

/// Image status.
#[derive(PartialEq)]
pub enum ImageStatus {
    /// Image is being fetched.
    Loading,

    /// Image fetching threw an error.
    Errored,

    /// Image has been fetched.
    Loaded,
}

/// `NetworkImage` component.
///
/// # Props
/// See [`NetworkImageProps`].
///
/// # Example
///  
/// ```rust
/// # use freya::prelude::*;
/// fn app(cx: Scope) -> Element {
///     render!(
///         NetworkImage {
///             url: "https://raw.githubusercontent.com/jigsawpieces/dog-api-images/main/greyhound/Cordelia.jpg".parse().unwrap()
///         }
///     )
/// }
///
#[allow(non_snake_case)]
pub fn NetworkImage<'a>(cx: Scope<'a, NetworkImageProps<'a>>) -> Element<'a> {
    let focus = use_focus(cx);
    let status = use_state(cx, || ImageStatus::Loading);
    let image_bytes = use_state::<Option<Vec<u8>>>(cx, || None);

    let focus_id = focus.attribute(cx);
    let NetworkImageTheme { width, height } =
        use_applied_theme!(cx, &cx.props.theme, network_image);
    let alt = cx.props.alt.as_deref();

    use_effect(cx, &cx.props.url, move |url| {
        to_owned![image_bytes, status];
        async move {
            // Loading image
            status.set(ImageStatus::Loading);
            let img = fetch_image(url).await;
            if let Ok(img) = img {
                // Image loaded
                image_bytes.set(Some(img));
                status.set(ImageStatus::Loaded)
            } else if let Err(_err) = img {
                // Image errored
                image_bytes.set(None);
                status.set(ImageStatus::Errored)
            }
        }
    });

    if *status.get() == ImageStatus::Loading {
        if let Some(loading_element) = &cx.props.loading {
            render!(loading_element)
        } else {
            render!(
                rect {
                    height: "{height}",
                    width: "{width}",
                    main_align: "center",
                    cross_align: "center",
                    Loader {}
                }
            )
        }
    } else if *status.get() == ImageStatus::Errored {
        if let Some(fallback_element) = &cx.props.fallback {
            render!(fallback_element)
        } else {
            render!(
                rect {
                    height: "{height}",
                    width: "{width}",
                    main_align: "center",
                    cross_align: "center",
                    label {
                        text_align: "center",
                        "Error"
                    }
                }
            )
        }
    } else {
        render! {
            image_bytes.as_ref().map(|bytes| {
                let image_data = bytes_to_data(cx, bytes);
                rsx!(
                    image {
                        height: "{height}",
                        width: "{width}",
                        focus_id: focus_id,
                        image_data: image_data,
                        role: "image",
                        alt: alt
                    }
                )
            })
        }
    }
}

async fn fetch_image(url: Url) -> Result<Vec<u8>, reqwest::Error> {
    let res = reqwest::get(url).await?;
    let data = res.bytes().await?;
    Ok(data.to_vec())
}