Skip to main content

cosmic_applet_avestruz/views/components/
avatar.rs

1// SPDX-License-Identifier: MIT
2
3//! Someone's picture, round, or what stands in for it.
4
5use cosmic::Element;
6use cosmic::iced::{Alignment, Background, Border, Color, Length};
7use cosmic::widget::{container, text};
8use nostr_sdk::prelude::PublicKey;
9
10use crate::images::{ImageShape, ImageState, ImageStore};
11
12/// A colour of someone's own, from their public key: the same person is the
13/// same colour everywhere, before their picture loads and if they have none.
14/// Kept to the middle of the range so the white initial reads on it.
15fn key_color(public_key: &PublicKey) -> Color {
16    let bytes = public_key.to_bytes();
17    let channel = |index: usize| 0.25 + 0.45 * f32::from(bytes.get(index).copied().unwrap_or(0)) / 255.0;
18    Color::from_rgb(channel(0), channel(1), channel(2))
19}
20
21/// The picture at `picture`, round and `size` across. Until it has loaded,
22/// or if there is none, a disc in the person's own colour with the initial
23/// of `name`.
24pub fn avatar<'a, Message: 'a>(
25    images: &'a ImageStore,
26    picture: Option<&str>,
27    public_key: &PublicKey,
28    name: &str,
29    size: f32,
30) -> Element<'a, Message> {
31    // Asked for round: the picture comes as its middle square with the
32    // corners already transparent, so it only has to be drawn at `size`.
33    if let Some(ImageState::Ready(loaded)) = picture.map(|url| images.get(url, ImageShape::Circle)) {
34        return cosmic::widget::image(loaded.handle.clone()).width(Length::Fixed(size)).height(Length::Fixed(size)).into();
35    }
36
37    let initial: String = name.chars().find(|c| c.is_alphanumeric()).map(|c| c.to_uppercase().collect()).unwrap_or_default();
38    let fill = key_color(public_key);
39    container(text(initial).size(size * 0.45).font(cosmic::font::bold()))
40        .width(Length::Fixed(size))
41        .height(Length::Fixed(size))
42        .align_x(Alignment::Center)
43        .align_y(Alignment::Center)
44        .class(cosmic::theme::Container::custom(move |_theme| container::Style {
45            background: Some(Background::Color(fill)),
46            text_color: Some(Color::WHITE),
47            border: Border { radius: (size / 2.0).into(), ..Border::default() },
48            ..Default::default()
49        }))
50        .into()
51}
52
53#[cfg(test)]
54mod tests {
55    use super::key_color;
56    use nostr_sdk::prelude::Keys;
57
58    #[test]
59    fn a_key_always_gives_the_same_colour_and_one_white_reads_on() {
60        for _ in 0..50 {
61            let key = Keys::generate().public_key();
62            let color = key_color(&key);
63            assert_eq!(color, key_color(&key));
64            for channel in [color.r, color.g, color.b] {
65                assert!((0.25..=0.7).contains(&channel), "{channel}");
66            }
67        }
68    }
69}