Avatar
A round image that falls back to initials.
Web replica of the native GPUI output
ZDRSuse gpui::{div, prelude::*, px};
use crate::ui::avatar::Avatar;
pub fn avatar_demo() -> impl IntoElement {
div()
.flex()
.gap_3()
.child(Avatar::new("HK").src("https://github.com/hyuskui.png"))
.child(Avatar::new("ZD"))
.child(Avatar::new("RS").size(px(40.0)))
}Installation
Add the component
$ cargo hyuskui add avatarOr copy it by hand: paste the source below into
src/ui/avatar.rsand register it insrc/ui/mod.rs.Make sure the theme is installed
Every component reads colors from
crate::theme. If you have not runcargo hyuskui init, follow the installation guide first.
Usage
use crate::ui::avatar::*;Source
This file is yours after install. Change the styles, add variants, or delete what you do not need.
use gpui::{div, img, prelude::*, px, App, FontWeight, Pixels, SharedString, SharedUri, Window};
use crate::theme::ActiveTheme;
/// A round image with initials shown while it loads or when it is missing.
#[derive(IntoElement)]
pub struct Avatar {
src: Option<SharedUri>,
fallback: SharedString,
size: Pixels,
}
impl Avatar {
pub fn new(fallback: impl Into<SharedString>) -> Self {
Self {
src: None,
fallback: fallback.into(),
size: px(32.0),
}
}
pub fn src(mut self, src: impl Into<SharedUri>) -> Self {
self.src = Some(src.into());
self
}
pub fn size(mut self, size: Pixels) -> Self {
self.size = size;
self
}
}
impl RenderOnce for Avatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let (bg, fg) = (theme.muted, theme.muted_foreground);
let initials = self.fallback;
let fallback = move || {
// GPUI's overflow_hidden does not clip to rounded corners, so round the fill too.
div()
.size_full()
.rounded_full()
.flex()
.items_center()
.justify_center()
.bg(bg)
.text_color(fg)
.text_sm()
.font_weight(FontWeight::MEDIUM)
.child(initials.clone())
.into_any_element()
};
div()
.size(self.size)
.flex_none()
.rounded_full()
.overflow_hidden()
.map(|this| match self.src {
Some(src) => this.child(img(src).size_full().rounded_full().with_fallback(fallback)),
None => this.child(fallback()),
})
}
}