freya_components/
loader.rs

1use freya_animation::prelude::*;
2use freya_core::prelude::*;
3use torin::size::Size;
4
5use crate::{
6    get_theme,
7    theming::component_themes::CircularLoaderThemePartial,
8};
9
10/// Circular loader component.
11///
12/// # Example
13///
14/// ```rust
15/// # use freya::prelude::*;
16/// fn app() -> impl IntoElement {
17///     CircularLoader::new()
18/// }
19///
20/// # use freya_testing::prelude::*;
21/// # launch_doc(|| {
22/// #   rect()
23///         .spacing(8.).center().expanded().child(app())
24/// # }, (250., 250.).into(), "./images/gallery_circular_loader.png");
25/// ```
26///
27/// # Preview
28/// ![Circular Loader Preview][circular_loader]
29#[cfg_attr(feature = "docs",
30    doc = embed_doc_image::embed_image!("circular_loader", "images/gallery_circular_loader.png")
31)]
32#[derive(PartialEq)]
33pub struct CircularLoader {
34    pub(crate) theme: Option<CircularLoaderThemePartial>,
35    size: f32,
36    key: DiffKey,
37}
38
39impl KeyExt for CircularLoader {
40    fn write_key(&mut self) -> &mut DiffKey {
41        &mut self.key
42    }
43}
44
45impl Default for CircularLoader {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl CircularLoader {
52    pub fn new() -> Self {
53        Self {
54            size: 32.,
55            theme: None,
56            key: DiffKey::None,
57        }
58    }
59
60    pub fn size(mut self, size: f32) -> Self {
61        self.size = size;
62        self
63    }
64}
65
66impl Render for CircularLoader {
67    fn render(&self) -> impl IntoElement {
68        let theme = get_theme!(&self.theme, circular_loader);
69
70        let animation = use_animation(|conf| {
71            conf.on_creation(OnCreation::Run);
72            conf.on_finish(OnFinish::Restart);
73            AnimNum::new(0.0, 360.0).time(650)
74        });
75
76        svg(Bytes::from_static(
77            r#"<svg viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg">
78                <circle class="spin" cx="300" cy="300" fill="none"
79                r="250" stroke-width="64" stroke="{color}"
80                stroke-dasharray="256 1400"
81                stroke-linecap="round" />
82            </svg>"#
83                .as_bytes(),
84        ))
85        .width(Size::px(self.size))
86        .height(Size::px(self.size))
87        .stroke(theme.primary_color)
88        .rotate(animation.get().value())
89    }
90
91    fn render_key(&self) -> DiffKey {
92        self.key.clone().or(self.default_key())
93    }
94}