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
442
443
444
445
//! T3 ยท Pull requests & issues: [`IssueStateGlyph`] and [`IssueRow`]
//! (`src/t3.css` "Issues").
use super::pull_request::{Label, LabelChip, icon_count};
use crate::{
    components::AvatarColor,
    icons::CarbonIcon,
    t3::craft::{self, focus_handle, focus_visible, mono, press, rem, sans},
    theme::color,
    tokens::ColorRole,
};
use gpui_kit::{
    AnyElement, App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce,
    SharedString, Styled, Window, div, prelude::FluentBuilder as _, px,
};
use std::rc::Rc;

/// An issue's state (`IS`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum IssueState {
    /// `open`, the default.
    #[default]
    Open,
    /// `progress`.
    Progress,
    /// `done`.
    Done,
    /// `cancelled`.
    Cancelled,
    /// `backlog`.
    Backlog,
}

impl IssueState {
    /// Every state.
    pub const ALL: [IssueState; 5] = [
        Self::Open,
        Self::Progress,
        Self::Done,
        Self::Cancelled,
        Self::Backlog,
    ];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Progress => "progress",
            Self::Done => "done",
            Self::Cancelled => "cancelled",
            Self::Backlog => "backlog",
        }
    }

    /// The reference label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Open => "Open",
            Self::Progress => "In progress",
            Self::Done => "Done",
            Self::Cancelled => "Cancelled",
            Self::Backlog => "Backlog",
        }
    }

    /// `CircleDash`, `InProgress`, `CheckmarkFilled`, `Close`.
    pub const fn icon(self) -> CarbonIcon {
        match self {
            Self::Open | Self::Backlog => CarbonIcon::CircleDash,
            Self::Progress => CarbonIcon::InProgress,
            Self::Done => CarbonIcon::CheckmarkFilled,
            Self::Cancelled => CarbonIcon::Close,
        }
    }

    /// `.t3-is--open, --backlog` `icon-secondary`; `--progress`
    /// `support-warning`; `--done` `tag-color-purple`; `--cancelled`
    /// `text-disabled`.
    pub fn ink(self) -> Hsla {
        color(match self {
            Self::Open | Self::Backlog => ColorRole::IconSecondary,
            Self::Progress => ColorRole::SupportWarning,
            Self::Done => ColorRole::TagColorPurple,
            Self::Cancelled => ColorRole::TextDisabled,
        })
    }
}

/// The issue state icon (`.t3-isglyph`, 16px).
#[derive(IntoElement, Clone, Copy, Debug, PartialEq, Eq)]
pub struct IssueStateGlyph {
    state: IssueState,
    interactive_progress: bool,
}

impl IssueStateGlyph {
    /// A glyph.
    pub fn new(state: IssueState) -> Self {
        Self {
            state,
            interactive_progress: false,
        }
    }

    /// Paint `IssueState::Progress` in `ColorRole::Interactive` (`Issues` board).
    pub fn interactive_progress(mut self, interactive: bool) -> Self {
        self.interactive_progress = interactive;
        self
    }
}

impl RenderOnce for IssueStateGlyph {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let ink = if self.interactive_progress && self.state == IssueState::Progress {
            color(ColorRole::Interactive)
        } else {
            self.state.ink()
        };
        super::pull_request::glyph(self.state.icon(), ink, 16., self.state.label())
    }
}

/// Issue priority (`priority`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Priority {
    /// `low`: one bar.
    Low,
    /// `medium`: two bars.
    Medium,
    /// `high`: three bars.
    High,
    /// `urgent`: three red bars.
    Urgent,
}

impl Priority {
    /// Every priority.
    pub const ALL: [Priority; 4] = [Self::Low, Self::Medium, Self::High, Self::Urgent];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Urgent => "urgent",
        }
    }
}

/// The three priority bars' fills (`.t3-issue-pri i`: 3px wide, 5/8/12px
/// tall; `layer-accent-01`, lit `icon-primary`, urgent `support-error`).
pub fn priority_bars(priority: Option<Priority>) -> [Hsla; 3] {
    let lit = match priority {
        None => 0,
        Some(Priority::Low) => 1,
        Some(Priority::Medium) => 2,
        Some(Priority::High | Priority::Urgent) => 3,
    };
    std::array::from_fn(|i| {
        if priority == Some(Priority::Urgent) {
            color(ColorRole::SupportError)
        } else if i < lit {
            color(ColorRole::IconPrimary)
        } else {
            color(ColorRole::LayerAccent01)
        }
    })
}

/// `.t3-issue-pri i:nth-child(n) { height }`.
pub const PRIORITY_HEIGHTS: [f32; 3] = [5., 8., 12.];

type Handler = Rc<dyn Fn(&mut Window, &mut App)>;

/// An issue list row (`.t3-issue`, 40px): priority bars, mono id, state,
/// title, labels, linked-thread count, assignee and time.
#[derive(IntoElement)]
pub struct IssueRow {
    id: ElementId,
    key: SharedString,
    title: SharedString,
    state: IssueState,
    priority: Option<Priority>,
    labels: Vec<Label>,
    assignee: Option<SharedString>,
    time: SharedString,
    linked_threads: usize,
    selected: bool,
    divided: bool,
    dash_when_unprioritized: bool,
    show_assignee_avatar: bool,
    interactive_progress: bool,
    trailing: Vec<AnyElement>,
    on_click: Option<Handler>,
}

impl IssueRow {
    /// A row for issue `key` (e.g. `CUI-142`) titled `title`.
    pub fn new(
        id: impl Into<ElementId>,
        key: impl Into<SharedString>,
        title: impl Into<SharedString>,
    ) -> Self {
        Self {
            id: id.into(),
            key: key.into(),
            title: title.into(),
            state: IssueState::Open,
            priority: None,
            labels: Vec::new(),
            assignee: None,
            time: SharedString::default(),
            linked_threads: 0,
            selected: false,
            divided: true,
            dash_when_unprioritized: false,
            show_assignee_avatar: true,
            interactive_progress: false,
            trailing: Vec::new(),
            on_click: None,
        }
    }

    /// Mark this row selected (`layer-selected-01` + 3px interactive bar).
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Show the bottom divider rule (`true` by default; `false` inside project-grouped lists).
    pub fn divided(mut self, divided: bool) -> Self {
        self.divided = divided;
        self
    }

    /// Show an em-dash (`โ€”`) when no priority is set (`Issues` board).
    pub fn dash_when_unprioritized(mut self, dash: bool) -> Self {
        self.dash_when_unprioritized = dash;
        self
    }

    /// Show the assignee avatar circle (`true` by default).
    pub fn show_assignee_avatar(mut self, show: bool) -> Self {
        self.show_assignee_avatar = show;
        self
    }

    /// Paint `IssueState::Progress` in `ColorRole::Interactive` (`Issues` board).
    pub fn interactive_progress(mut self, interactive: bool) -> Self {
        self.interactive_progress = interactive;
        self
    }

    /// Append a trailing status pill or badge before assignee/time.
    pub fn trailing(mut self, element: impl IntoElement) -> Self {
        self.trailing.push(element.into_any_element());
        self
    }

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

    /// The priority.
    pub fn priority(mut self, priority: Priority) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Labels.
    pub fn labels(mut self, labels: impl IntoIterator<Item = Label>) -> Self {
        self.labels = labels.into_iter().collect();
        self
    }

    /// The assignee's initials (shown as given).
    pub fn assignee(mut self, assignee: impl Into<SharedString>) -> Self {
        self.assignee = Some(assignee.into());
        self
    }

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

    /// Number of linked threads (shown when non-zero).
    pub fn linked_threads(mut self, n: usize) -> Self {
        self.linked_threads = n;
        self
    }

    /// Activation.
    pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for IssueRow {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let focus = focus_handle(&id, window, cx);
        let ring = focus_visible(&focus, window);
        let on_click = self.on_click.clone();
        let bars = priority_bars(self.priority);
        let priority_el: AnyElement = if self.priority.is_none() && self.dash_when_unprioritized {
            craft::titled(div(), "priority", "Priority: none")
                .flex()
                .flex_none()
                .items_center()
                .justify_center()
                .w(px(11.))
                .h(px(12.))
                .child(craft::text("โ€”", 12., ColorRole::TextHelper))
                .into_any_element()
        } else {
            craft::titled(
                div(),
                "priority",
                format!(
                    "Priority: {}",
                    self.priority.map(Priority::name).unwrap_or("none")
                ),
            )
            .flex()
            .flex_none()
            .items_end()
            .gap(px(1.))
            .h(px(12.))
            .children((0..3).map(|i| div().w(px(3.)).h(px(PRIORITY_HEIGHTS[i])).bg(bars[i])))
            .into_any_element()
        };
        sans(press(id, &focus), 14., 400)
            .accessibility_label(self.title.clone())
            .relative()
            .w_full()
            .items_center()
            .gap(rem(12.))
            .h(rem(if self.divided { 40. } else { 36. }))
            .px(rem(if self.divided { 16. } else { 12. }))
            .when(self.divided, |this| {
                this.border_b_1()
                    .border_color(color(ColorRole::BorderSubtle01))
            })
            .text_color(color(ColorRole::TextPrimary))
            .when(self.selected, |this| {
                this.bg(color(ColorRole::LayerSelected01)).child(
                    div()
                        .absolute()
                        .top_0()
                        .bottom_0()
                        .left_0()
                        .w(px(3.))
                        .bg(color(ColorRole::BorderInteractive)),
                )
            })
            .when(!self.selected, |this| {
                this.hover(|s| s.bg(color(ColorRole::LayerHover01)))
            })
            .when_some(on_click, |this, f| this.on_click(move |_, w, cx| f(w, cx)))
            .child(priority_el)
            .child(
                mono(div(), 12., 400)
                    .flex_none()
                    .w(rem(72.))
                    .text_color(color(ColorRole::TextSecondary))
                    .child(self.key.clone()),
            )
            .child(IssueStateGlyph::new(self.state).interactive_progress(self.interactive_progress))
            .child(
                div()
                    .min_w_0()
                    .overflow_hidden()
                    .whitespace_nowrap()
                    .text_ellipsis()
                    .child(self.title.clone()),
            )
            .children(
                self.labels
                    .iter()
                    .map(|l| LabelChip::new(l.name.clone(), l.color)),
            )
            .child(div().flex_1())
            .children(self.trailing)
            .when(self.linked_threads > 0, |this| {
                let n = self.linked_threads;
                this.child(craft::titled(
                    icon_count(CarbonIcon::Link, n.to_string()),
                    "links",
                    format!("{n} linked thread{}", if n == 1 { "" } else { "s" }),
                ))
            })
            .when_some(
                self.assignee.clone().filter(|_| self.show_assignee_avatar),
                |this, a| {
                    // `.t3-issue .cu-avatar--sm { 1.25rem }`; the fallback text stays 12px.
                    this.child(craft::initials(
                        a,
                        craft::AvatarTone::Avatar(AvatarColor::Blue),
                        20.,
                    ))
                },
            )
            .child(craft::text(self.time.clone(), 12., ColorRole::TextSecondary).flex_none())
            .when(ring, |this| this.child(craft::focus_ring()))
    }
}

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

    #[test]
    fn priority_bars_light_up() {
        crate::theme::tests_set(crate::tokens::CarbonTheme::White);
        let on = color(ColorRole::IconPrimary);
        let off = color(ColorRole::LayerAccent01);
        let red = color(ColorRole::SupportError);
        assert_eq!(priority_bars(None), [off; 3]);
        assert_eq!(priority_bars(Some(Priority::Low)), [on, off, off]);
        assert_eq!(priority_bars(Some(Priority::Medium)), [on, on, off]);
        assert_eq!(priority_bars(Some(Priority::High)), [on; 3]);
        assert_eq!(priority_bars(Some(Priority::Urgent)), [red; 3]);
    }

    #[test]
    fn state_glyphs() {
        crate::theme::tests_set(crate::tokens::CarbonTheme::White);
        assert_eq!(IssueState::Backlog.icon(), CarbonIcon::CircleDash);
        assert_eq!(IssueState::Done.ink(), color(ColorRole::TagColorPurple));
        assert_eq!(IssueState::Cancelled.ink(), color(ColorRole::TextDisabled));
        let glyph = IssueStateGlyph::new(IssueState::Progress).interactive_progress(true);
        assert_eq!(
            glyph,
            IssueStateGlyph {
                state: IssueState::Progress,
                interactive_progress: true
            }
        );
    }
}