ailloli_ui_widgets/controls/avatar.rs
1//! Circular avatars derived from names, explicit initials, or icons.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::Event;
5use ailloli_ui_core::geometry::{Constraints, Rect, Size};
6use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
7use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
8use ailloli_ui_runtime::component::{IntoView, View, Widget};
9use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
10use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
11use ailloli_ui_runtime::scene::PaintCtx;
12use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawText};
13use ailloli_ui_text::{TextLayoutParams, WrapMode};
14
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16/// Semantic color choices for an [`Avatar`].
17///
18/// # Examples
19///
20/// ```
21/// use ailloli_ui_widgets::controls::AvatarTone;
22/// assert_eq!(AvatarTone::default(), AvatarTone::Neutral);
23/// ```
24pub enum AvatarTone {
25 /// Elevated neutral surface with primary text.
26 #[default]
27 Neutral,
28 /// Accent-tinted background and foreground.
29 Accent,
30 /// Danger-tinted background and foreground.
31 Danger,
32 /// Success-tinted background and foreground.
33 Success,
34 /// Warning-tinted background and foreground.
35 Warning,
36 /// Informational-tinted background and foreground.
37 Info,
38 /// Standard surface with muted text.
39 Muted,
40}
41
42#[derive(Clone, Debug, PartialEq)]
43/// Resolved paint and logical-pixel sizing for an [`Avatar`].
44///
45/// # Examples
46///
47/// ```
48/// use ailloli_ui_core::Theme;
49/// use ailloli_ui_widgets::controls::{AvatarStyle, AvatarTone};
50/// let style = AvatarStyle::from_theme(Theme::dark(), AvatarTone::Accent);
51/// assert_eq!(style.size, 40.0);
52/// assert_eq!(style.text.px_size, 14);
53/// ```
54pub struct AvatarStyle {
55 /// Circular background fill.
56 pub background: Color,
57 /// Initials text style; its font size is rescaled during painting.
58 pub text: TextStyle,
59 /// Tint applied to icon content.
60 pub icon_tint: Color,
61 /// Border drawn around the avatar when visible.
62 pub ring: Border,
63 /// Preferred width and height in logical pixels.
64 pub size: f32,
65}
66
67impl Default for AvatarStyle {
68 fn default() -> Self {
69 Self::from_theme(Theme::default(), AvatarTone::Neutral)
70 }
71}
72
73impl AvatarStyle {
74 /// Resolves `tone` through `theme` with a `40` logical-pixel default size.
75 ///
76 /// Non-neutral semantic tones use a 20%-alpha tone background. Neutral and
77 /// muted tones instead use theme surface colors.
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// use ailloli_ui_core::Theme;
83 /// use ailloli_ui_widgets::controls::{AvatarStyle, AvatarTone};
84 /// let style = AvatarStyle::from_theme(Theme::dark(), AvatarTone::Muted);
85 /// assert_eq!(style.size, 40.0);
86 /// ```
87 pub fn from_theme(theme: Theme, tone: AvatarTone) -> Self {
88 let palette = theme.palette();
89 let tone_color = avatar_tone_color(theme, tone);
90 let (background, foreground) = match tone {
91 AvatarTone::Neutral => (palette.surface_elevated, palette.text),
92 AvatarTone::Muted => (palette.surface, palette.text_muted),
93 _ => (tone_color.with_alpha(0.20), tone_color),
94 };
95 Self {
96 background,
97 text: TextStyle::new(FontId::Ui, 14, foreground),
98 icon_tint: foreground,
99 ring: Border::new(1.0, palette.border),
100 size: 40.0,
101 }
102 }
103}
104
105#[derive(Clone, Debug, PartialEq)]
106/// Normalized text or icon payload painted inside an avatar.
107enum AvatarContent {
108 /// Up to three normalized uppercase characters.
109 Initials(String),
110 /// Theme-tinted icon identifier.
111 Icon(IconId),
112}
113
114/// A circular, non-interactive identity marker.
115///
116/// Name-derived avatars use at most the first character of each of the first
117/// two whitespace-separated words. Explicit initials accept at most three
118/// non-whitespace characters. Both forms uppercase Unicode and use `"?"` when
119/// no character remains.
120///
121/// # Examples
122///
123/// ```
124/// use ailloli_ui_widgets::controls::Avatar;
125/// let avatar = Avatar::new("Ada Lovelace");
126/// let _ = avatar;
127/// ```
128pub struct Avatar {
129 /// Layout configuration used to resolve the intrinsic square.
130 pub(crate) layout: LayoutStyle,
131 /// Flex-item behavior used by the parent layout.
132 pub(crate) flex_item: FlexItemStyle,
133 /// Semantic tone last selected through the public API.
134 tone: AvatarTone,
135 /// Resolved paint and size configuration.
136 style: AvatarStyle,
137 /// Normalized initials or icon payload.
138 content: AvatarContent,
139}
140
141crate::impl_layout_builders_unit!(Avatar);
142
143impl Avatar {
144 /// Creates an avatar whose initials are derived from `name`.
145 ///
146 /// Two or more words yield the first character of the first two words; one
147 /// word yields its first two characters. Blank input yields `"?"`.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use ailloli_ui_widgets::controls::Avatar;
153 /// let avatar = Avatar::new("Grace Hopper");
154 /// let _ = avatar;
155 /// ```
156 pub fn new(name: impl Into<String>) -> Self {
157 Self::initials(derive_initials(&name.into()))
158 }
159
160 /// Creates an avatar from explicit initials.
161 ///
162 /// Whitespace is removed, at most three input characters are retained, and
163 /// Unicode uppercase expansion may produce more than three output code
164 /// points. Blank input becomes `"?"`.
165 ///
166 /// # Examples
167 ///
168 /// ```
169 /// use ailloli_ui_widgets::controls::Avatar;
170 /// let avatar = Avatar::initials("gh");
171 /// let _ = avatar;
172 /// ```
173 pub fn initials(initials: impl Into<String>) -> Self {
174 let tone = AvatarTone::Neutral;
175 Self {
176 layout: LayoutStyle::default(),
177 flex_item: FlexItemStyle::default(),
178 tone,
179 style: AvatarStyle::from_theme(Theme::default(), tone),
180 content: AvatarContent::Initials(normalize_initials(&initials.into())),
181 }
182 }
183
184 /// Creates an avatar whose content is `icon`.
185 ///
186 /// The icon is centered at 48% of the avatar's shortest side and tinted
187 /// with [`AvatarStyle::icon_tint`].
188 ///
189 /// # Examples
190 ///
191 /// ```
192 /// use ailloli_ui_core::IconId;
193 /// use ailloli_ui_widgets::controls::Avatar;
194 /// let avatar = Avatar::icon(IconId::History);
195 /// let _ = avatar;
196 /// ```
197 pub fn icon(icon: IconId) -> Self {
198 let tone = AvatarTone::Neutral;
199 Self {
200 layout: LayoutStyle::default(),
201 flex_item: FlexItemStyle::default(),
202 tone,
203 style: AvatarStyle::from_theme(Theme::default(), tone),
204 content: AvatarContent::Icon(icon),
205 }
206 }
207
208 /// Re-resolves the complete style for `tone` using the default theme.
209 ///
210 /// This resets any custom style and size previously supplied.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use ailloli_ui_widgets::controls::{Avatar, AvatarTone};
216 /// let avatar = Avatar::new("Ailloli").tone(AvatarTone::Accent);
217 /// let _ = avatar;
218 /// ```
219 pub fn tone(mut self, tone: AvatarTone) -> Self {
220 self.tone = tone;
221 self.style = AvatarStyle::from_theme(Theme::default(), tone);
222 self
223 }
224
225 /// Replaces all resolved style values without changing the stored tone.
226 ///
227 /// A later [`Self::tone`] call replaces this custom style.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// use ailloli_ui_core::Theme;
233 /// use ailloli_ui_widgets::controls::{Avatar, AvatarStyle, AvatarTone};
234 /// let style = AvatarStyle::from_theme(Theme::dark(), AvatarTone::Info);
235 /// let avatar = Avatar::new("Ailloli").avatar_style(style);
236 /// let _ = avatar;
237 /// ```
238 pub fn avatar_style(mut self, style: AvatarStyle) -> Self {
239 self.style = style;
240 self
241 }
242
243 /// Sets the preferred square size in logical pixels, clamped to `0.0`.
244 ///
245 /// `NaN` is treated as zero. Explicit layout width/height builders may
246 /// override this intrinsic size.
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use ailloli_ui_widgets::controls::Avatar;
252 /// let avatar = Avatar::new("Ailloli").size(32.0);
253 /// let _ = avatar;
254 /// ```
255 pub fn size(mut self, value: f32) -> Self {
256 self.style.size = value.max(0.0);
257 self
258 }
259}
260
261/// Retained leaf widget holding the normalized content and resolved style.
262struct AvatarWidget {
263 /// Layout copied from the builder.
264 layout: LayoutStyle,
265 /// Style copied from the builder.
266 style: AvatarStyle,
267 /// Content copied from the builder.
268 content: AvatarContent,
269}
270
271impl<A: 'static> Widget<A> for AvatarWidget {
272 fn debug_name(&self) -> &'static str {
273 "Avatar"
274 }
275
276 fn layout(
277 &self,
278 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
279 _ctx: &mut LayoutCtx<'_>,
280 _children: &mut [LayoutChild],
281 constraints: Constraints,
282 ) -> LayoutResult {
283 let intrinsic = Size::new(self.style.size, self.style.size);
284 let size = apply_layout_size(intrinsic, self.layout, constraints);
285 LayoutResult {
286 size,
287 children: Vec::new(),
288 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
289 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
290 overlay_hit_bounds: Vec::new(),
291 clip: None,
292 is_window_root_clip: false,
293 artifact: None,
294 }
295 }
296
297 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
298 let radius = bounds.w.min(bounds.h) * 0.5;
299 ctx.push(DrawCmd::RRect(DrawRRect {
300 rect: bounds,
301 radius,
302 color: self.style.background,
303 }));
304
305 match &self.content {
306 AvatarContent::Initials(initials) => paint_initials(ctx, bounds, initials, &self.style),
307 AvatarContent::Icon(icon) => {
308 let icon_size = bounds.w.min(bounds.h) * 0.48;
309 ctx.push(DrawCmd::Image(DrawImage {
310 rect: Rect::new(
311 bounds.x + (bounds.w - icon_size) * 0.5,
312 bounds.y + (bounds.h - icon_size) * 0.5,
313 icon_size,
314 icon_size,
315 ),
316 icon: icon.clone(),
317 tint: self.style.icon_tint,
318 rotation_rad: 0.0,
319 }));
320 }
321 }
322
323 if self.style.ring.is_visible() {
324 ctx.push(DrawCmd::Border(DrawBorder {
325 rect: bounds,
326 radius: Radius::uniform(radius),
327 border: self.style.ring,
328 }));
329 }
330 }
331
332 fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
333 }
334
335 fn focus_policy(&self) -> FocusPolicy {
336 FocusPolicy::NotFocusable
337 }
338}
339
340impl<A: 'static> IntoView<A> for Avatar {
341 fn into_view(self) -> View<A> {
342 finish_view_sized(
343 View::leaf(AvatarWidget {
344 layout: self.layout,
345 style: self.style,
346 content: self.content,
347 }),
348 self.flex_item,
349 LayoutSizeHint::from_layout(self.layout),
350 )
351 }
352}
353
354/// Centers initials using a font size equal to 36% of the shortest side.
355///
356/// Painting is skipped when the paint context has no text system. The computed
357/// font size has a 10-pixel floor and saturates through Rust's float-to-integer
358/// cast if it exceeds `u16`.
359fn paint_initials(ctx: &mut PaintCtx<'_>, bounds: Rect, initials: &str, style: &AvatarStyle) {
360 let Some(text_system) = ctx.text_system.as_deref_mut() else {
361 return;
362 };
363 let mut text_style = style.text;
364 text_style.px_size = (bounds.w.min(bounds.h) * 0.36).round().max(10.0) as u16;
365 let layout = text_system.layout_cached(TextLayoutParams {
366 text: initials,
367 style: text_style,
368 max_width: Some(bounds.w),
369 wrap_mode: WrapMode::NoWrap,
370 });
371 let baseline = layout
372 .lines
373 .first()
374 .map(|line| line.baseline_y)
375 .unwrap_or(0.0);
376 let x = bounds.x + (bounds.w - layout.metrics.width) * 0.5;
377 let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
378 ctx.push(DrawCmd::Text(DrawText {
379 pos: [x, y],
380 color: text_style.color,
381 decoration: ailloli_ui_core::TextDecoration::None,
382 layout: layout.clone(),
383 }));
384}
385
386/// Maps an avatar tone to the corresponding theme palette color.
387fn avatar_tone_color(theme: Theme, tone: AvatarTone) -> Color {
388 let palette = theme.palette();
389 match tone {
390 AvatarTone::Neutral => palette.text,
391 AvatarTone::Accent => palette.accent,
392 AvatarTone::Danger => palette.danger,
393 AvatarTone::Success => palette.success,
394 AvatarTone::Warning => palette.warning,
395 AvatarTone::Info => palette.info,
396 AvatarTone::Muted => palette.text_muted,
397 }
398}
399
400/// Derives one or two initials from the first two non-empty words in `name`.
401fn derive_initials(name: &str) -> String {
402 let mut words = name.split_whitespace().filter(|word| !word.is_empty());
403 let first = words.next();
404 let second = words.next();
405 let raw = match (first, second) {
406 (Some(a), Some(b)) => format!(
407 "{}{}",
408 a.chars().next().unwrap_or_default(),
409 b.chars().next().unwrap_or_default()
410 ),
411 (Some(a), None) => a.chars().take(2).collect(),
412 _ => "?".to_string(),
413 };
414 normalize_initials(&raw)
415}
416
417/// Removes whitespace, keeps three input characters, uppercases, and defaults to `?`.
418fn normalize_initials(value: &str) -> String {
419 let mut out = String::new();
420 for ch in value
421 .trim()
422 .chars()
423 .filter(|ch| !ch.is_whitespace())
424 .take(3)
425 {
426 for upper in ch.to_uppercase() {
427 out.push(upper);
428 }
429 }
430 if out.is_empty() {
431 "?".to_string()
432 } else {
433 out
434 }
435}