u0ui 0.3.0

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
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
//! Avatar: a round user picture or initials (`.cu-avatar*` in `custom.css`;
//! Carbon's UI shell user avatar style, no core component).
//!
//! - **Appearance**: `.cu-avatar { width: 2rem; height: 2rem; border-radius:
//!   var(--border-radius-max); overflow: hidden }`; sm 1.5rem, lg 3rem, xl
//!   4rem. The fallback fills it with initials (`.cu-avatar-fallback {
//!   font-size: 0.75rem; font-weight: 600 }`) in a `tag-background-*` /
//!   `tag-color-*` pair. The fallback's own `font-size: 0.75rem` wins over the
//!   avatar's size font (`.cu-avatar--lg { font-size: 1rem }`), so initials are
//!   12px at every size, as in the reference.
//! - **Image**: `AvatarImage` covers the circle (`object-fit: cover`); while it
//!   loads or when it fails, the fallback shows (`onError → setOk(false)`).
//! - **Group**: `.cu-avatar-group > .cu-avatar { box-shadow: 0 0 0 2px
//!   var(--background) }` and `+ .cu-avatar { margin-left: -0.5rem }`.
//! - **Marks**: `MarkGroup` overlaps marks that are not people (an
//!   agent's logo, a brand glyph) as `AvatarGroup` overlaps avatars: the
//!   same ring and the same overlap for its size (a quarter of it, as
//!   `-0.5rem` of the 2rem avatar), each mark on a square of the ring's
//!   colour, square as Carbon's shapes are, so what it overlaps does not
//!   show through it.
//! - **Behavior**: none. Kit's `Avatar` derives colors from the name and draws
//!   its own sizes; Carbon's palette is the tag pairs, so this is drawn here.
use crate::{
    icons::{CarbonIcon, Icon},
    theme::color,
    tokens::{ColorRole, FontFamilyKey},
    typography::font,
};
use gpui_kit::{
    AnyElement, App, BoxShadow, Hsla, ImageSource, IntoElement, ObjectFit, ParentElement, Pixels,
    RenderOnce, SharedString, Styled, StyledImage as _, Window, div, img,
    prelude::FluentBuilder as _, px, rems,
};

/// `index.d.ts` `AvatarProps.size`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AvatarSize {
    /// 1.5rem.
    Sm,
    /// 2rem, the default.
    #[default]
    Md,
    /// 3rem.
    Lg,
    /// 4rem.
    Xl,
}

impl AvatarSize {
    /// Every size.
    pub const ALL: [AvatarSize; 4] = [Self::Sm, Self::Md, Self::Lg, Self::Xl];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Sm => "sm",
            Self::Md => "md",
            Self::Lg => "lg",
            Self::Xl => "xl",
        }
    }

    /// Diameter in px (`.cu-avatar` 2rem; `--sm` 1.5rem, `--lg` 3rem, `--xl` 4rem).
    pub const fn diameter(self) -> f32 {
        match self {
            Self::Sm => 24.,
            Self::Md => 32.,
            Self::Lg => 48.,
            Self::Xl => 64.,
        }
    }
}

/// `index.d.ts` `AvatarFallback.color`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AvatarColor {
    /// `blue`, the default.
    #[default]
    Blue,
    /// `teal`.
    Teal,
    /// `purple`.
    Purple,
    /// `magenta`.
    Magenta,
    /// `gray`.
    Gray,
}

impl AvatarColor {
    /// Every color.
    pub const ALL: [AvatarColor; 5] = [
        Self::Blue,
        Self::Teal,
        Self::Purple,
        Self::Magenta,
        Self::Gray,
    ];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Blue => "blue",
            Self::Teal => "teal",
            Self::Purple => "purple",
            Self::Magenta => "magenta",
            Self::Gray => "gray",
        }
    }

    /// (background, text): `.cu-avatar--<c> { background: var(--tag-background-<c>);
    /// color: var(--tag-color-<c>) }`.
    pub fn colors(self) -> (Hsla, Hsla) {
        use ColorRole::*;
        let (bg, fg) = match self {
            Self::Blue => (TagBackgroundBlue, TagColorBlue),
            Self::Teal => (TagBackgroundTeal, TagColorTeal),
            Self::Purple => (TagBackgroundPurple, TagColorPurple),
            Self::Magenta => (TagBackgroundMagenta, TagColorMagenta),
            Self::Gray => (TagBackgroundGray, TagColorGray),
        };
        (color(bg), color(fg))
    }
}

/// `.cu-avatar-fallback { font-size: 0.75rem }`.
pub const FALLBACK_FONT_SIZE: f32 = 12.;
/// `.cu-avatar-group > .cu-avatar { box-shadow: 0 0 0 2px var(--background) }`.
pub const GROUP_RING: f32 = 2.;
/// `.cu-avatar-group > .cu-avatar + .cu-avatar { margin-left: -0.5rem }`.
pub const GROUP_OVERLAP: f32 = 8.;

/// An icon in the fallback: `CarbonUI.Icons.User size={16}` inside
/// `AvatarFallback` (u0's `Main` board, a pending review draft).
pub const FALLBACK_ICON_SIZE: f32 = 16.;

/// What an [`AvatarFallback`] shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FallbackContent {
    /// Initials (or any short text).
    Text(SharedString),
    /// An icon ([`FALLBACK_ICON_SIZE`], in the pair's text color).
    Icon(CarbonIcon),
}

/// `AvatarFallback`: initials, or an icon, on a tag color pair.
#[derive(Clone)]
pub struct AvatarFallback {
    content: FallbackContent,
    color: AvatarColor,
}

impl AvatarFallback {
    /// Initials (or any short text, e.g. `+3`).
    pub fn new(text: impl Into<SharedString>) -> Self {
        Self {
            content: FallbackContent::Text(text.into()),
            color: AvatarColor::Blue,
        }
    }

    /// An icon instead of initials (e.g. [`CarbonIcon::User`] for someone
    /// without a name or picture), drawn at [`FALLBACK_ICON_SIZE`].
    pub fn icon(icon: CarbonIcon) -> Self {
        Self {
            content: FallbackContent::Icon(icon),
            color: AvatarColor::Blue,
        }
    }

    /// What it shows.
    pub fn content(&self) -> &FallbackContent {
        &self.content
    }

    /// The color pair (default blue).
    pub fn color(mut self, color: AvatarColor) -> Self {
        self.color = color;
        self
    }

    fn element(&self) -> AnyElement {
        let (bg, fg) = self.color.colors();
        // GPUI clips children to rectangles, so every layer rounds itself.
        div()
            .size_full()
            .rounded_full()
            .flex()
            .items_center()
            .justify_center()
            .bg(bg)
            .text_color(fg)
            .font(font(FontFamilyKey::Sans, 600))
            .text_size(rems(FALLBACK_FONT_SIZE / crate::tokens::REM_PX))
            .line_height(rems(1.))
            .child(match &self.content {
                FallbackContent::Text(text) => text.clone().into_any_element(),
                FallbackContent::Icon(icon) => Icon::carbon(*icon)
                    .size_length(rems(FALLBACK_ICON_SIZE / crate::tokens::REM_PX))
                    .color(fg)
                    .into_any_element(),
            })
            .into_any_element()
    }
}

/// An avatar. See the module docs.
#[derive(IntoElement, Clone, Default)]
pub struct Avatar {
    size: AvatarSize,
    image: Option<ImageSource>,
    fallback: Option<AvatarFallback>,
    ring: Option<Hsla>,
}

impl Avatar {
    /// An empty `md` avatar.
    pub fn new() -> Self {
        Self::default()
    }

    /// The size.
    pub fn size(mut self, size: AvatarSize) -> Self {
        self.size = size;
        self
    }

    /// `AvatarImage`: a picture source (path, URL or image data).
    pub fn image(mut self, source: impl Into<ImageSource>) -> Self {
        self.image = Some(source.into());
        self
    }

    /// `AvatarFallback`: shown without an image, while it loads, or if it fails.
    pub fn fallback(mut self, fallback: AvatarFallback) -> Self {
        self.fallback = Some(fallback);
        self
    }

    /// The group ring (set by [`AvatarGroup`]).
    fn ring(mut self, ring: Hsla) -> Self {
        self.ring = Some(ring);
        self
    }
}

impl RenderOnce for Avatar {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let d = rems(self.size.diameter() / crate::tokens::REM_PX);
        let fallback = self.fallback.clone();
        let content: Option<AnyElement> = match (self.image, fallback) {
            (Some(source), fallback) => {
                let loading = fallback.clone();
                Some(
                    img(source)
                        .size_full()
                        .rounded_full()
                        .object_fit(ObjectFit::Cover)
                        .with_fallback(move || {
                            fallback
                                .as_ref()
                                .map(|f| f.element())
                                .unwrap_or_else(|| div().into_any_element())
                        })
                        .with_loading(move || {
                            loading
                                .as_ref()
                                .map(|f| f.element())
                                .unwrap_or_else(|| div().into_any_element())
                        })
                        .into_any_element(),
                )
            }
            (None, Some(fallback)) => Some(fallback.element()),
            (None, None) => None,
        };
        div()
            .flex_none()
            .size(d)
            .rounded_full()
            .overflow_hidden()
            .when_some(self.ring, |this, ring| {
                this.shadow(vec![
                    BoxShadow::new(px(0.), px(0.), ring).spread_radius(px(GROUP_RING)),
                ])
            })
            .children(content)
    }
}

/// `AvatarGroup`: overlapping avatars, each ringed in `background`.
#[derive(IntoElement, Default)]
pub struct AvatarGroup {
    avatars: Vec<Avatar>,
}

impl AvatarGroup {
    /// An empty group.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an avatar.
    pub fn avatar(mut self, avatar: Avatar) -> Self {
        self.avatars.push(avatar);
        self
    }

    /// Add avatars.
    pub fn avatars(mut self, avatars: impl IntoIterator<Item = Avatar>) -> Self {
        self.avatars.extend(avatars);
        self
    }
}

impl RenderOnce for AvatarGroup {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let ring = color(ColorRole::Background);
        div()
            .flex()
            .flex_row()
            .flex_none()
            .children(self.avatars.into_iter().enumerate().map(|(i, avatar)| {
                div()
                    .when(i > 0, |this| {
                        this.ml(rems(-GROUP_OVERLAP / crate::tokens::REM_PX))
                    })
                    .child(avatar.ring(ring))
            }))
    }
}

/// `MarkGroup`: overlapping marks, each `size` square on the ring's colour
/// and ringed in it, the next overlapping it by a quarter of `size`.
#[derive(IntoElement)]
pub struct MarkGroup {
    size: f32,
    ring: Hsla,
    marks: Vec<AnyElement>,
}

impl MarkGroup {
    /// An empty group of marks `size` px square, ringed in `background`.
    pub fn new(size: f32) -> Self {
        Self {
            size,
            ring: color(ColorRole::Background),
            marks: Vec::new(),
        }
    }

    /// The colour of what the group lies on, where that is not
    /// `background` (a layer, a sidebar).
    pub fn ring(mut self, ring: Hsla) -> Self {
        self.ring = ring;
        self
    }

    /// Add marks, drawn at the group's size.
    pub fn marks(mut self, marks: impl IntoIterator<Item = impl IntoElement>) -> Self {
        self.marks
            .extend(marks.into_iter().map(IntoElement::into_any_element));
        self
    }

    /// How far each mark after the first lies over the one before.
    pub fn overlap(size: f32) -> Pixels {
        px(size * GROUP_OVERLAP / AvatarSize::Md.diameter())
    }
}

impl RenderOnce for MarkGroup {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let (size, ring) = (rems(self.size / crate::tokens::REM_PX), self.ring);
        let overlap = Self::overlap(self.size);
        div().flex().flex_row().flex_none().items_center().children(
            self.marks.into_iter().enumerate().map(move |(i, mark)| {
                div()
                    .flex_none()
                    .size(size)
                    .flex()
                    .items_center()
                    .justify_center()
                    .bg(ring)
                    .when(i > 0, |this| this.ml(-overlap))
                    .shadow(vec![
                        BoxShadow::new(px(0.), px(0.), ring).spread_radius(px(GROUP_RING)),
                    ])
                    .child(mark)
            }),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tokens::CarbonTheme;

    fn hex(c: Hsla) -> String {
        let c = c.to_rgb();
        let b = |v: f32| (v * 255.).round() as u8;
        format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
    }

    #[test]
    fn sizes_and_colors_follow_custom_css() {
        crate::theme::tests_set(CarbonTheme::White);
        assert_eq!(AvatarSize::ALL.map(|s| s.diameter()), [24., 32., 48., 64.]);
        // `.cu-avatar--blue { background: tag-background-blue #d0e2ff; color: tag-color-blue #0043ce }`.
        let (bg, fg) = AvatarColor::Blue.colors();
        assert_eq!((hex(bg), hex(fg)), ("#d0e2ff".into(), "#0043ce".into()));
        let (bg, _) = AvatarColor::Gray.colors();
        assert_eq!(hex(bg), "#e0e0e0");
        assert_eq!(
            (FALLBACK_FONT_SIZE, GROUP_RING, GROUP_OVERLAP),
            (12., 2., 8.)
        );
    }

    #[test]
    fn marks_overlap_by_a_quarter_as_avatars_do() {
        // `-0.5rem` of a 2rem avatar: 8 of 32.
        assert_eq!(
            MarkGroup::overlap(AvatarSize::Md.diameter()),
            px(GROUP_OVERLAP)
        );
        assert_eq!(MarkGroup::overlap(12.), px(3.));
    }

    #[test]
    fn a_fallback_holds_initials_or_a_16px_icon() {
        assert_eq!(
            AvatarFallback::new("AL").content(),
            &FallbackContent::Text("AL".into())
        );
        let icon = AvatarFallback::icon(CarbonIcon::User).color(AvatarColor::Gray);
        assert_eq!(icon.content(), &FallbackContent::Icon(CarbonIcon::User));
        assert_eq!(FALLBACK_ICON_SIZE, 16.);
    }
}