herogpui-components 0.10.2

HeroUI-style component library for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Avatar — port of `@heroui/avatar` (v3.2.4, Radix Avatar 1.1.11 semantics).

use std::sync::Arc;
use std::time::Duration;

use gpui::{
    px, App, ElementId, ImageCacheError, ImageSource, ImgResourceLoader, IntoElement,
    ParentElement, Pixels, RenderImage, RenderOnce, Resource, SharedString, Styled, Window,
};
use herogpui_core::{element_id, Color};
use herogpui_theme::ActiveTheme;

/// `Avatar.Image.onError` — v3's `(event) => void`, with no event payload to
/// hand over, exactly the shape `Table.onLoadMore` and `Input.onClear` use.
type OnImageError = Arc<dyn Fn(&mut Window, &mut App) + 'static>;

/// `Avatar.Image.onLoad` — same ported shape as [`OnImageError`].
type OnImageLoad = Arc<dyn Fn(&mut Window, &mut App) + 'static>;

/// Per-instance image state, keyed in the window under the avatar's instance
/// id alone. Radix Avatar tracks pending/loaded/errored per component
/// instance: two avatars pointing at the same source fire their own
/// callbacks and run their own `delay_ms` windows, even though gpui
/// deduplicates the underlying asset load per source. The image latches reset
/// on a source change; the fallback timer does not, because `Avatar.Fallback`
/// remains mounted while `Avatar.Image` changes.
#[derive(Clone, Default)]
struct AvatarImageState {
    /// The source identity whose image latches this slot tracks. A different
    /// identity resets those latches and bumps [`AvatarImageState::generation`].
    source: Option<SourceIdentity>,
    /// Bumped on every source change. Tasks spawned for one image identity
    /// must not fire a load latch after the identity changed under them.
    generation: u32,
    /// The mounted fallback's `delay_ms` task is armed (running or done).
    armed: bool,
    /// The fallback's `delay_ms` window (if any) has elapsed since mount.
    delay_elapsed: bool,
    /// The load has failed; `on_error` has been fired exactly once.
    errored: bool,
    /// The load has succeeded; `on_load` has been fired exactly once.
    loaded: bool,
}

/// Fill of an avatar fallback (`variant`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AvatarVariant {
    /// The pinned base fill (`bg-default`); the color recolours the initials.
    #[default]
    Default,
    /// The color's soft wash with `text-{role}-soft-foreground` initials.
    Soft,
}

impl AvatarVariant {
    pub const ALL: [AvatarVariant; 2] = [AvatarVariant::Default, AvatarVariant::Soft];

    pub fn label(self) -> &'static str {
        match self {
            AvatarVariant::Default => "Default",
            AvatarVariant::Soft => "Soft",
        }
    }
}

/// HeroUI Avatar: image or name-initials fallback.
#[derive(IntoElement)]
pub struct Avatar {
    /// The instance's element id, required at construction. The image
    /// lifecycle state (`delay_ms` window, `on_error`/`on_load` latches) is
    /// keyed under it, so two avatars rendered on one page must carry
    /// distinct ids here or they share one state slot.
    id: ElementId,
    name: SharedString,
    source: Option<ImageSource>,
    custom_source_key: Option<SharedString>,
    on_error: Option<OnImageError>,
    on_load: Option<OnImageLoad>,
    /// `Avatar.Fallback.delayMs`, in milliseconds.
    fallback_delay_ms: Option<u64>,
    /// `Avatar.Fallback` children — an icon, a `+N` counter, any element.
    fallback: Option<gpui::AnyElement>,
    /// `Avatar.Fallback.color` — overrides the parent color for everything
    /// the fallback paints.
    fallback_color: Option<Color>,
    /// Edge length, set by [`Avatar::size`]. v3 has no custom-pixel prop.
    size_px: Pixels,
    /// Whether [`Avatar::size`] was `Sm`, which rounds one step tighter.
    small: bool,
    /// Whether [`Avatar::size`] was `Lg`, whose fallback text steps up.
    large: bool,
    color: Color,
    variant: AvatarVariant,
    /// The corner radius, in place of the size's `rounded-3xl`
    /// (`rounded-2xl` on `Sm`).
    radius: Option<Pixels>,
    /// The `sx` slot, refined over the root style at the end of render.
    sx: Option<Box<gpui::StyleRefinement>>,
}

impl Avatar {
    /// The instance's element id is a constructor argument, not an optional
    /// builder: image lifecycle state is keyed under it, and a defaulted
    /// literal would silently merge same-source siblings into one instance.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            name: "".into(),
            source: None,
            custom_source_key: None,
            on_error: None,
            on_load: None,
            fallback_delay_ms: None,
            fallback: None,
            fallback_color: None,
            size_px: px(40.),
            small: false,
            large: false,
            color: Color::Default,
            variant: AvatarVariant::Default,
            radius: None,
            sx: None,
        }
    }

    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
        self.name = name.into();
        self
    }

    pub fn variant(mut self, variant: AvatarVariant) -> Self {
        self.variant = variant;
        self
    }

    /// `Avatar.Image.src` — a plain string or path loads through gpui's asset
    /// system (a parseable URI is fetched, anything else is an embedded
    /// resource); a [`gpui::ImageSource::Image`], `Render` or `Custom` is the
    /// explicit gpui part for images the app already holds or loads itself.
    pub fn src(mut self, src: impl Into<ImageSource>) -> Self {
        self.source = Some(src.into());
        self
    }

    /// Sets the stable logical identity for a custom [`ImageSource`] loader.
    /// Rebuilding an equivalent loader per frame keeps the same lifecycle when
    /// this is omitted; change the key when the loader starts serving a new
    /// logical image so its load and error latches reset.
    pub fn custom_source_key(mut self, key: impl Into<SharedString>) -> Self {
        self.custom_source_key = Some(key.into());
        self
    }

    /// `Avatar.Image.onError` — callback when the image fails to load. The
    /// fallback initials replace the image on that same failure.
    pub fn on_error(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_error = Some(Arc::new(f));
        self
    }

    /// `Avatar.Image.onLoad` — callback when the image has loaded and
    /// replaces the fallback.
    pub fn on_load(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_load = Some(Arc::new(f));
        self
    }

    /// `Avatar.Fallback.delayMs` — hold the fallback back this many
    /// milliseconds **from fallback mount**, so a slow load does not flash the
    /// initials behind it (v3: "Delay before showing fallback (prevents
    /// flash)"). A success renders before the window ends; a failure or source
    /// change inside it waits for the same window — it does not restart it.
    pub fn delay_ms(mut self, ms: u64) -> Self {
        self.fallback_delay_ms = Some(ms);
        self
    }

    /// `Avatar.Fallback` children — replaces the name initials with any
    /// element (an icon, a `+N` counter, custom text).
    pub fn fallback(mut self, content: impl IntoElement) -> Self {
        self.fallback = Some(content.into_any_element());
        self
    }

    /// `Avatar.Fallback.color` — overrides the parent [`Avatar::color`] for
    /// the fallback's soft-foreground text and soft fill. It is its own
    /// documented prop, not an alias of the parent's color.
    pub fn fallback_color(mut self, c: Color) -> Self {
        self.fallback_color = Some(c);
        self
    }

    pub fn size(mut self, size: herogpui_core::Size) -> Self {
        self.size_px = match size {
            herogpui_core::Size::Sm => px(32.),
            herogpui_core::Size::Md => px(40.),
            herogpui_core::Size::Lg => px(48.),
        };
        // `.avatar--sm` is `rounded-2xl` where the other two are `rounded-3xl`:
        // at 32px a 24px radius would be all but a circle, so v3 steps it down.
        self.small = size == herogpui_core::Size::Sm;
        self.large = size == herogpui_core::Size::Lg;
        self
    }

    pub fn color(mut self, c: Color) -> Self {
        self.color = c;
        self
    }

    /// The corner radius, in place of the size's `rounded-3xl`
    /// (`rounded-2xl` on `Sm`). Not a v3 prop; the removed v2 `radius` prop is
    /// prohibited and this is a per-component repository extension.
    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    /// The one slot for caller-owned low-level styling: GPUI's styling methods
    /// (`bg`, `text_color`, `w`, `h`, `p`, `rounded`, `border_color`, …)
    /// applied to the avatar's root element after every value the variant, the
    /// color and the active theme chose, so they win.
    pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
        self.sx = Some(crate::util::capture_sx(style));
        self
    }

    /// The initials `name` renders when no [`Avatar::fallback`] children are
    /// set: the uppercase first characters of the first two words, or `?`
    /// when there is nothing to take a character from.
    pub fn initials(name: &str) -> String {
        let words: Vec<&str> = name.split_whitespace().collect();
        let mut out = String::new();
        for w in words.iter().take(2) {
            if let Some(c) = w.chars().next() {
                out.extend(c.to_uppercase());
            }
        }
        if out.is_empty() {
            "?".to_owned()
        } else {
            out
        }
    }
}

/// The stable identity of one avatar's image source. Every resource and
/// image variant compares by value: the location, the image content id, or
/// the render image's allocation id. A `Custom` loader has no stable value
/// identity — a closure rebuilt inline each frame gets a fresh allocation
/// every time — so it shares the instance's single lifecycle slot unless the
/// caller supplies an explicit logical source key.
#[derive(Clone, PartialEq)]
enum SourceIdentity {
    Resource(Resource),
    Image(u64),
    Render(usize),
    Custom(Option<SharedString>),
}

/// What the avatar keys its lifecycle state against this frame.
fn source_identity(
    source: &ImageSource,
    custom_source_key: Option<&SharedString>,
) -> SourceIdentity {
    match source {
        ImageSource::Resource(resource) => SourceIdentity::Resource(resource.clone()),
        ImageSource::Image(image) => SourceIdentity::Image(image.id()),
        ImageSource::Render(image) => SourceIdentity::Render(image.id.0),
        ImageSource::Custom(_) => SourceIdentity::Custom(custom_source_key.cloned()),
    }
}

/// What the source reports this frame: `Some(Ok)` loaded, `Some(Err)` failed,
/// `None` still pending. `use_asset` (not `get_asset`) is the call that also
/// arranges a redraw once a resource load settles.
/// Whether an observed load/error completion may report.
///
/// A completion observed while its source is mounted must still lose when the
/// source changed before the reporting task runs: switching sources bumps
/// [`AvatarImageState::generation`], so a task carrying the older generation
/// is stale. The `already` half keeps `on_load`/`on_error` firing exactly
/// once. Pure so the stale-callback contract has deterministic unit coverage
/// independent of executor timing (a synchronously-decoding source reports
/// while still mounted; a pending one must not report after unmount).
fn first_completion(already: bool, state_generation: u32, observed_generation: u32) -> bool {
    !already && state_generation == observed_generation
}

fn observe_load(
    source: &ImageSource,
    window: &mut Window,
    cx: &mut App,
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
    match source {
        ImageSource::Resource(resource) => window.use_asset::<ImgResourceLoader>(resource, cx),
        ImageSource::Image(image) => image.clone().use_render_image(window, cx).map(Ok),
        ImageSource::Render(image) => Some(Ok(image.clone())),
        ImageSource::Custom(loader) => loader(window, cx),
    }
}

impl RenderOnce for Avatar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = cx.colors();
        // `Avatar.Fallback.color` overrides the parent color for everything
        // the fallback paints; the wiring is explicit so the parent's
        // same-named `color` never silently stands in for it.
        let fb_role = cx.role(self.fallback_color.unwrap_or(self.color));
        // Both variants paint the fallback text `text-{role}-soft-foreground`;
        // for `--default` that resolves to `--default-foreground`.
        let soft_fg = fb_role.soft_foreground(colors.foreground);
        let (bg, fallback_bg) = match self.variant {
            // `.avatar` fills `bg-default` for every color: the color recolours
            // the initials, never the fill.
            AvatarVariant::Default => (colors.default.color, colors.default.color),
            // `.avatar--soft` clears the base fill and the fallback paints
            // `bg-{role}-soft` with the same soft foreground.
            AvatarVariant::Soft => (gpui::transparent_black(), fb_role.soft()),
        };
        // `.avatar__fallback` is `text-sm`; `.avatar--lg .avatar__fallback`
        // steps the fallback text up to `text-base`.
        let font = if self.large { px(16.) } else { px(14.) };
        let leading = if self.large { px(24.) } else { px(20.) };
        let radius = self.radius.unwrap_or_else(|| {
            if self.small {
                crate::util::soft_radius(cx)
            } else {
                crate::util::control_radius(cx)
            }
        });
        let sx_corners = crate::util::sx_radius(&self.sx);

        let el = gpui::div()
            .relative()
            .flex()
            .items_center()
            .justify_center()
            .size(self.size_px)
            .rounded(radius)
            .bg(bg)
            .text_color(soft_fg)
            .text_size(font)
            .line_height(leading)
            .font_weight(gpui::FontWeight::MEDIUM)
            .overflow_hidden()
            .flex_shrink_0();

        let fallback_content: gpui::AnyElement = match self.fallback {
            Some(content) => content,
            None => Avatar::initials(&self.name).into_any_element(),
        };
        // `.avatar__fallback` is `size-full bg-default` and relies on the
        // avatar's `overflow-hidden` to clip its fill to the rounded corner.
        // gpui clips a child to the parent's *rect*, not to its radius, so a
        // square fill here squared off every avatar — the same reason the
        // loaded image below carries the radius.
        let fallback = gpui::div()
            .flex()
            .items_center()
            .justify_center()
            .size_full()
            .rounded(radius)
            .bg(fallback_bg)
            .text_color(soft_fg)
            .text_size(font)
            .line_height(leading)
            .font_weight(gpui::FontWeight::MEDIUM)
            .child(fallback_content);
        let fallback = crate::util::round_sx_corners(fallback, &sx_corners);

        // Keep the image lifecycle slot alive even when the source is absent:
        // image latches must reset when an image is removed and later re-added
        // with the same source, while the mounted fallback timer survives.
        let key = element_id::scoped(&self.id, "image");
        let state = window.use_keyed_state(key, cx, |_, _| AvatarImageState::default());
        let source = self.source;
        let identity = source
            .as_ref()
            .map(|source| source_identity(source, self.custom_source_key.as_ref()));
        state.update(cx, |state, _| {
            if state.source.as_ref() != identity.as_ref() {
                let armed = state.armed;
                let delay_elapsed = state.delay_elapsed;
                *state = AvatarImageState {
                    source: identity,
                    generation: state.generation + 1,
                    armed,
                    delay_elapsed,
                    ..AvatarImageState::default()
                };
            }
        });
        let snapshot = state.read(cx).clone();

        // `Avatar.Fallback` stays mounted for the life of this Avatar, so its
        // delay starts once per instance, including when the image is added
        // after the first render.
        if self.fallback_delay_ms.is_some() && !snapshot.armed {
            let weak = state.downgrade();
            let delay_ms = self.fallback_delay_ms.unwrap_or_default();
            window
                .spawn(cx, async move |cx| {
                    // The latch makes a double spawn (two frames before the
                    // task first runs) wait-free.
                    let start = weak
                        .update(cx, |s, _| {
                            if s.armed {
                                None
                            } else {
                                s.armed = true;
                                Some(())
                            }
                        })
                        .unwrap_or(None);
                    if start.is_some() {
                        cx.background_executor()
                            .timer(Duration::from_millis(delay_ms))
                            .await;
                        weak.update(cx, |s, cx| {
                            s.delay_elapsed = true;
                            cx.notify();
                        })
                        .ok();
                    }
                })
                .detach();
        }
        let fallback_visible = self.fallback_delay_ms.is_none() || snapshot.delay_elapsed;

        let el = match source {
            None => {
                if fallback_visible {
                    el.child(fallback)
                } else {
                    el
                }
            }
            Some(source) => {
                let got = observe_load(&source, window, cx);
                match &got {
                    // `Avatar.Image.onLoad` fires once, on the first observed
                    // success, outside the layout phase.
                    Some(Ok(_)) if !snapshot.loaded => {
                        let weak = state.downgrade();
                        let on_load = self.on_load.clone();
                        let generation = snapshot.generation;
                        window
                            .spawn(cx, async move |cx| {
                                let first = weak
                                    .update(cx, |s, _| {
                                        if first_completion(s.loaded, s.generation, generation) {
                                            s.loaded = true;
                                            true
                                        } else {
                                            false
                                        }
                                    })
                                    .unwrap_or(false);
                                if first {
                                    let _ = cx.update(|window, cx| {
                                        if let Some(on_load) = &on_load {
                                            on_load(window, cx);
                                        }
                                    });
                                }
                            })
                            .detach();
                    }
                    // `Avatar.Image.onError` fires once, on the first observed
                    // failure, outside the layout phase.
                    Some(Err(_)) if !snapshot.errored => {
                        let weak = state.downgrade();
                        let on_error = self.on_error.clone();
                        let generation = snapshot.generation;
                        window
                            .spawn(cx, async move |cx| {
                                let first = weak
                                    .update(cx, |s, _| {
                                        if first_completion(s.errored, s.generation, generation) {
                                            s.errored = true;
                                            true
                                        } else {
                                            false
                                        }
                                    })
                                    .unwrap_or(false);
                                if first {
                                    let _ = cx.update(|window, cx| {
                                        if let Some(on_error) = &on_error {
                                            on_error(window, cx);
                                        }
                                    });
                                }
                            })
                            .detach();
                    }
                    _ => {}
                }

                match got {
                    // Success: the image replaces the fallback inside the
                    // `.avatar__image` box.
                    Some(Ok(data)) => el.child(crate::util::round_sx_corners(
                        gpui::img(data)
                            .absolute()
                            .inset_0()
                            .size_full()
                            .rounded(radius),
                        &sx_corners,
                    )),
                    // Pending and error both keep the fallback box; with a
                    // `delay_ms` window still running the box stays empty.
                    Some(Err(_)) | None => {
                        if fallback_visible {
                            el.child(fallback)
                        } else {
                            el
                        }
                    }
                }
            }
        };
        crate::util::apply_sx(el, &self.sx)
    }
}

// The pinned `.avatar` fills `bg-default` for every color and paints the
// initials `text-{role}-soft-foreground`; a solid role fill or a muted
// fallback looks plausible on screen, so the check is mechanical.
#[cfg(test)]
mod fill_tokens {
    #[test]
    fn fallback_and_image_keep_the_roots_explicit_corners() {
        use gpui::{px, AbsoluteLength, Styled};

        let sx = Some(crate::util::capture_sx(|el| {
            el.rounded_tl(px(0.)).rounded_br(px(3.))
        }));
        let corners = crate::util::sx_radius(&sx);
        let mut image =
            crate::util::round_sx_corners(gpui::img("avatar.png").rounded(px(8.)), &corners);
        let radii = image.style().corner_radii.clone();
        for (actual, expected) in [
            (radii.top_left, 0.),
            (radii.top_right, 8.),
            (radii.bottom_left, 8.),
            (radii.bottom_right, 3.),
        ] {
            assert_eq!(actual, Some(AbsoluteLength::Pixels(px(expected))));
        }

        let source = include_str!("avatar.rs")
            .split("#[cfg(test)]")
            .next()
            .unwrap();
        let compact: String = source.split_whitespace().collect();
        for consumer in [
            "letsx_corners=crate::util::sx_radius(&self.sx);",
            "letfallback=crate::util::round_sx_corners(fallback,&sx_corners);",
            "crate::util::round_sx_corners(gpui::img(data).absolute().inset_0().size_full().rounded(radius),&sx_corners,)",
            "crate::util::apply_sx(el,&self.sx)",
        ] {
            assert!(compact.contains(consumer), "missing corner consumer: {consumer}");
        }
    }

    #[test]
    fn the_fills_and_foregrounds_follow_the_pinned_css() {
        // Scan the implementation only; this test's own text names the
        // forbidden accessors.
        let source = include_str!("avatar.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source
                .contains("AvatarVariant::Default => (colors.default.color, colors.default.color)"),
            "the base avatar and its fallback slot must fill `bg-default` \
             (pinned `.avatar` + `.avatar__fallback`)"
        );
        assert!(
            source.contains("AvatarVariant::Soft => (gpui::transparent_black(), fb_role.soft())"),
            "the soft avatar root must be transparent and its fallback slot \
             must fill `bg-{{role}}-soft` (pinned `.avatar--soft`)"
        );
        assert!(
            source.contains("cx.role(self.fallback_color.unwrap_or(self.color))"),
            "`Avatar.Fallback.color` must override the parent color for the \
             fallback painting, not alias it"
        );
        assert!(
            source.contains("let font = if self.large { px(16.) } else { px(14.) }"),
            "`.avatar__fallback` is `text-sm` and `.avatar--lg \
             .avatar__fallback` steps it up to `text-base` (16px)"
        );
        assert!(
            source.contains(".size_full()") && source.contains(".bg(fallback_bg)"),
            "the fallback must be the pinned full-size fallback slot, not a \
             raw child of the root"
        );
        let compact: String = source.split_whitespace().collect();
        assert!(
            compact.contains("gpui::img(data).absolute().inset_0().size_full().rounded(radius)"),
            "the loaded image must carry the avatar radius because not every \
             renderer clips image content at a rounded parent"
        );
        assert!(
            !source.contains("colors().muted"),
            "the soft default initials are `text-default-soft-foreground`, \
             not the muted tone"
        );
        assert!(
            !source.contains("surface_tertiary"),
            "the base avatar fills `bg-default`, not a surface level"
        );
        assert!(
            !source.contains("(fb_role.color, fb_role.foreground)"),
            "the base avatar never paints a solid role fill"
        );
    }
}

// The stale-callback guard, pinned without executor timing: a completion
// observed while its source is mounted reports exactly once, and a source
// switch before the reporting task runs suppresses it.
#[cfg(test)]
mod outcome_guard {
    use super::first_completion;

    #[test]
    fn fresh_completion_reports() {
        assert!(first_completion(false, 0, 0));
    }

    #[test]
    fn source_switch_before_report_suppresses() {
        assert!(!first_completion(false, 1, 0));
    }

    #[test]
    fn second_completion_never_reports() {
        assert!(!first_completion(true, 1, 1));
    }
}