avatar.rs

 1use std::sync::Arc;
 2
 3use crate::prelude::*;
 4use gpui::{img, rems, Div, ImageData, ImageSource, IntoElement, Styled};
 5
 6#[derive(Debug, Default, PartialEq, Clone)]
 7pub enum Shape {
 8    #[default]
 9    Circle,
10    RoundedRectangle,
11}
12
13#[derive(IntoElement)]
14pub struct Avatar {
15    src: ImageSource,
16    is_available: Option<bool>,
17    shape: Shape,
18}
19
20impl RenderOnce for Avatar {
21    type Rendered = Div;
22
23    fn render(self, cx: &mut WindowContext) -> Self::Rendered {
24        let mut img = img(self.src);
25
26        if self.shape == Shape::Circle {
27            img = img.rounded_full();
28        } else {
29            img = img.rounded_md();
30        }
31
32        let size = rems(1.0);
33
34        div()
35            .size(size)
36            .child(
37                img.size(size)
38                    // todo!(Pull the avatar fallback background from the theme.)
39                    .bg(gpui::red()),
40            )
41            .children(self.is_available.map(|is_free| {
42                // HACK: non-integer sizes result in oval indicators.
43                let indicator_size = (size.0 * cx.rem_size() * 0.4).round();
44
45                div()
46                    .absolute()
47                    .z_index(1)
48                    .bg(if is_free { gpui::green() } else { gpui::red() })
49                    .size(indicator_size)
50                    .rounded(indicator_size)
51                    .bottom_0()
52                    .right_0()
53            }))
54    }
55}
56
57impl Avatar {
58    pub fn uri(src: impl Into<SharedString>) -> Self {
59        Self {
60            src: src.into().into(),
61            shape: Shape::Circle,
62            is_available: None,
63        }
64    }
65    pub fn data(src: Arc<ImageData>) -> Self {
66        Self {
67            src: src.into(),
68            shape: Shape::Circle,
69            is_available: None,
70        }
71    }
72
73    pub fn source(src: ImageSource) -> Self {
74        Self {
75            src,
76            shape: Shape::Circle,
77            is_available: None,
78        }
79    }
80    pub fn shape(mut self, shape: Shape) -> Self {
81        self.shape = shape;
82        self
83    }
84    pub fn availability_indicator(mut self, is_available: impl Into<Option<bool>>) -> Self {
85        self.is_available = is_available.into();
86        self
87    }
88}