u0ui 0.1.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
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
646
647
648
649
650
651
652
//! T3 · Usage & workflows: [`WorkflowStateWord`], [`WorkflowRunFeed`] and
//! [`WorkflowRunRow`] (`src/t3/workspace.jsx`, "Workflows" in `src/t3.css`).
use super::parts::{card_sub, child_id};
use crate::{
    components::{Badge, BadgeSize, BadgeVariant, Button, ButtonSize, ButtonVariant},
    icons::CarbonIcon,
    t3::{
        base::{Spin, fmt_elapsed, visually_hidden},
        craft::sans,
        press::{self, Handler, rem},
    },
    theme::color,
    tokens::ColorRole,
};
use gpui_kit::{
    AnyElement, App, CursorStyle, ElementId, Hsla, InteractiveElement as _, IntoElement,
    ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
    prelude::FluentBuilder as _, px,
};
use std::rc::Rc;

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

// ── WorkflowStateWord ───────────────────────────────────────────────────

/// A workflow run's state (`WorkflowStateWord` `state`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RunState {
    /// `running` (the default): blue.
    #[default]
    Running,
    /// `queued`: warm gray.
    Queued,
    /// `succeeded`: green.
    Succeeded,
    /// `failed`: red.
    Failed,
    /// `waiting`: purple.
    Waiting,
    /// `cancelled`: gray.
    Cancelled,
}

impl RunState {
    /// Every state.
    pub const ALL: [RunState; 6] = [
        Self::Running,
        Self::Queued,
        Self::Succeeded,
        Self::Failed,
        Self::Waiting,
        Self::Cancelled,
    ];

    /// The reference name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Running => "running",
            Self::Queued => "queued",
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
            Self::Waiting => "waiting",
            Self::Cancelled => "cancelled",
        }
    }

    /// The tag label (`state[0].toUpperCase() + state.slice(1)`).
    pub fn label(self) -> String {
        let n = self.name();
        let mut c = n.chars();
        c.next()
            .map(|f| f.to_uppercase().collect::<String>() + c.as_str())
            .unwrap_or_default()
    }

    /// The tag variant (`t`).
    pub const fn variant(self) -> BadgeVariant {
        match self {
            Self::Running => BadgeVariant::Blue,
            Self::Queued => BadgeVariant::WarmGray,
            Self::Succeeded => BadgeVariant::Green,
            Self::Failed => BadgeVariant::Red,
            Self::Waiting => BadgeVariant::Purple,
            Self::Cancelled => BadgeVariant::Gray,
        }
    }
}

/// A run state as a small tag (`WorkflowStateWord`).
#[derive(IntoElement, Clone, Debug)]
pub struct WorkflowStateWord {
    state: RunState,
    label: Option<SharedString>,
}

impl WorkflowStateWord {
    /// The tag for `state`.
    pub fn new(state: RunState) -> Self {
        Self { state, label: None }
    }

    /// Replace the label.
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }
}

impl RenderOnce for WorkflowStateWord {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        Badge::new(self.label.unwrap_or_else(|| self.state.label().into()))
            .variant(self.state.variant())
            .size(BadgeSize::Sm)
    }
}

// ── WorkflowRunFeed ─────────────────────────────────────────────────────

/// A step's status (`steps[].status`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StepStatus {
    /// `succeeded`: `CheckmarkFilled` in `support-success`.
    Succeeded,
    /// `failed`: `ErrorFilled` in `support-error`, with Resume.
    Failed,
    /// `running`: a spinner.
    Running,
    /// `pending` (the default): `CircleDash`, a quiet title.
    #[default]
    Pending,
    /// `waiting`: `Help` in `tag-color-purple`, with Answer.
    Waiting,
    /// `skipped`: `Subtract`.
    Skipped,
}

impl StepStatus {
    /// Every status.
    pub const ALL: [StepStatus; 6] = [
        Self::Succeeded,
        Self::Failed,
        Self::Running,
        Self::Pending,
        Self::Waiting,
        Self::Skipped,
    ];

    /// The reference name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
            Self::Running => "running",
            Self::Pending => "pending",
            Self::Waiting => "waiting",
            Self::Skipped => "skipped",
        }
    }

    /// The mark's glyph and fill (`None` while running: a spinner).
    /// `.t3-wf--succeeded .t3-wf-mark svg { fill: support-success }`, `--failed`
    /// `support-error`, `--pending, --skipped` `icon-secondary`, `--waiting`
    /// `tag-color-purple`.
    pub fn mark(self) -> Option<(CarbonIcon, Hsla)> {
        let (glyph, role) = match self {
            Self::Running => return None,
            Self::Succeeded => (CarbonIcon::CheckmarkFilled, ColorRole::SupportSuccess),
            Self::Failed => (CarbonIcon::ErrorFilled, ColorRole::SupportError),
            Self::Pending => (CarbonIcon::CircleDash, ColorRole::IconSecondary),
            Self::Waiting => (CarbonIcon::Help, ColorRole::TagColorPurple),
            Self::Skipped => (CarbonIcon::Subtract, ColorRole::IconSecondary),
        };
        Some((glyph, color(role)))
    }
}

/// One step (`{ title, status, elapsed, detail, branch }`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorkflowStep {
    /// `title`.
    pub title: SharedString,
    /// `status`.
    pub status: StepStatus,
    /// `elapsed` seconds.
    pub elapsed: Option<u64>,
    /// `detail`.
    pub detail: Option<SharedString>,
    /// `branch`: indented, with a branch elbow.
    pub branch: bool,
}

impl WorkflowStep {
    /// A step.
    pub fn new(title: impl Into<SharedString>, status: StepStatus) -> Self {
        Self {
            title: title.into(),
            status,
            ..Default::default()
        }
    }

    /// Seconds it took (`elapsed`).
    pub fn elapsed(mut self, secs: u64) -> Self {
        self.elapsed = Some(secs);
        self
    }

    /// The detail line (`detail`).
    pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// A branch step (`branch`).
    pub fn branch(mut self, branch: bool) -> Self {
        self.branch = branch;
        self
    }
}

/// Texts of a [`WorkflowRunFeed`] (hard-coded in the reference).
#[derive(Clone, Debug)]
pub struct WorkflowFeedTexts {
    /// The running spinner's label (`Running`).
    pub running: SharedString,
    /// `Resume`.
    pub resume: SharedString,
    /// `Only the failed step runs again.`
    pub resume_note: SharedString,
    /// `Answer`.
    pub answer: SharedString,
}

impl Default for WorkflowFeedTexts {
    fn default() -> Self {
        Self {
            running: "Running".into(),
            resume: "Resume".into(),
            resume_note: "Only the failed step runs again.".into(),
            answer: "Answer".into(),
        }
    }
}

/// `.t3-wf--branch { margin-left: spacing-07 }`.
pub const BRANCH_INDENT: f32 = 32.;
/// `.t3-wf-rail { left: 7.5px }`: the rail sits on the 16px mark's centre.
pub const RAIL_LEFT: f32 = 7.5;

/// A workflow run as a timeline (`WorkflowRunFeed`, `.t3-wf`): a rail
/// joining the step marks, branch steps indented under an elbow, Resume on a
/// failed step and Answer on a waiting one. Draw it on `background` (the
/// marks mask the rail in that color).
#[derive(IntoElement)]
pub struct WorkflowRunFeed {
    id: ElementId,
    steps: Vec<WorkflowStep>,
    texts: WorkflowFeedTexts,
    on_resume: Option<IndexHandler>,
    on_answer: Option<IndexHandler>,
}

impl WorkflowRunFeed {
    /// A feed of `steps`.
    pub fn new(id: impl Into<ElementId>, steps: impl IntoIterator<Item = WorkflowStep>) -> Self {
        Self {
            id: id.into(),
            steps: steps.into_iter().collect(),
            texts: WorkflowFeedTexts::default(),
            on_resume: None,
            on_answer: None,
        }
    }

    /// Replace the default texts.
    pub fn texts(mut self, texts: WorkflowFeedTexts) -> Self {
        self.texts = texts;
        self
    }

    /// Resume pressed on a failed step.
    pub fn on_resume(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_resume = Some(Rc::new(f));
        self
    }

    /// Answer pressed on a waiting step.
    pub fn on_answer(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_answer = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for WorkflowRunFeed {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let n = self.steps.len();
        let line = color(ColorRole::BorderSubtle01);
        let steps = self.steps.iter().enumerate().map(|(i, s)| {
            let mark: AnyElement = match s.status.mark() {
                None => Spin::new(child_id(&id, "spin", i))
                    .label(self.texts.running.clone())
                    .into_any_element(),
                Some((glyph, fill)) => press::icon(glyph, 16., fill).into_any_element(),
            };
            let pending = s.status == StepStatus::Pending;
            // `.t3-wf-head { display: flex; align-items: center; gap: spacing-03; 14px }`,
            // `b { font-weight: 600 }`, `.t3-wf--pending .t3-wf-head b { color: text-secondary;
            // font-weight: 400 }`.
            let head = sans(div(), 14., 400)
                .flex()
                .flex_row()
                .items_center()
                .gap(rem(8.))
                .child(
                    sans(div(), 14., if pending { 400 } else { 600 })
                        .text_color(color(if pending {
                            ColorRole::TextSecondary
                        } else {
                            ColorRole::TextPrimary
                        }))
                        .child(s.title.clone()),
                )
                .child(visually_hidden(format!(" ({})", s.status.name())))
                .children(s.elapsed.map(|e| card_sub(fmt_elapsed(e))));
            // `.t3-card-actions.t3-card-actions--start { justify-content: flex-start; gap: spacing-03 }`.
            let actions = match s.status {
                StepStatus::Failed => {
                    let f = self.on_resume.clone();
                    Some(
                        div()
                            .flex()
                            .flex_row()
                            .flex_wrap()
                            .items_center()
                            .gap(rem(8.))
                            .child(
                                Button::new(child_id(&id, "resume", i), self.texts.resume.clone())
                                    .size(ButtonSize::Sm)
                                    .variant(ButtonVariant::Secondary)
                                    .icon(CarbonIcon::Restart)
                                    .when_some(f, |b, f| b.on_click(move |_, w, cx| f(i, w, cx))),
                            )
                            .child(card_sub(self.texts.resume_note.clone())),
                    )
                }
                StepStatus::Waiting => {
                    let f = self.on_answer.clone();
                    Some(
                        div().flex().flex_row().child(
                            Button::new(child_id(&id, "answer", i), self.texts.answer.clone())
                                .size(ButtonSize::Sm)
                                .when_some(f, |b, f| b.on_click(move |_, w, cx| f(i, w, cx))),
                        ),
                    )
                }
                _ => None,
            };
            // `.t3-wf-step { position: relative; display: flex; gap: spacing-04;
            // padding-bottom: spacing-05 }`.
            div()
                .relative()
                .flex()
                .flex_row()
                .gap(rem(12.))
                .pb(rem(16.))
                .when(s.branch, |this| this.ml(rem(BRANCH_INDENT)))
                // `.t3-wf-rail { position: absolute; left: 7.5px; top: 1.25rem; bottom: 0;
                // width: 1px; background: border-subtle-01 }`, hidden on the last step.
                .when(i + 1 < n, |this| {
                    this.child(
                        div()
                            .absolute()
                            .left(px(RAIL_LEFT))
                            .top(rem(20.))
                            .bottom_0()
                            .w(px(1.))
                            .bg(line),
                    )
                })
                // `.t3-wf--branch::before { left: calc(-1 * spacing-07 + 7.5px); top: -0.75rem;
                // width: calc(spacing-07 - 4px); height: 1.25rem; border-left: 1px; border-bottom: 1px }`.
                .when(s.branch, |this| {
                    this.child(
                        div()
                            .absolute()
                            .left(px(-BRANCH_INDENT + RAIL_LEFT))
                            .top(rem(-12.))
                            .w(rem(BRANCH_INDENT - 4.))
                            .h(rem(20.))
                            .border_l_1()
                            .border_b_1()
                            .border_color(line),
                    )
                })
                // `.t3-wf-mark { position: relative; z-index: 1; display: flex; width: 1rem;
                // height: 1.25rem; flex: none; align-items: center; background: background }`.
                .child(
                    div()
                        .relative()
                        .flex()
                        .flex_none()
                        .items_center()
                        .w(rem(16.))
                        .h(rem(20.))
                        .bg(color(ColorRole::Background))
                        .child(mark),
                )
                .child(
                    // `.t3-wf-body { display: flex; flex: 1; flex-direction: column; gap: spacing-03;
                    // min-width: 0 }`.
                    div()
                        .flex()
                        .flex_col()
                        .flex_1()
                        .min_w_0()
                        .gap(rem(8.))
                        .child(head)
                        .when_some(s.detail.clone(), |this, d| {
                            // `.t3-wf-detail { font-size: 0.875rem; color: text-secondary }`.
                            this.child(
                                sans(div(), 14., 400)
                                    .text_color(color(ColorRole::TextSecondary))
                                    .child(d),
                            )
                        })
                        .children(actions),
                )
        });
        // `.t3-wf { margin: 0; padding: 0; list-style: none; max-width: 36rem }`.
        div()
            .id(id.clone())
            .flex()
            .flex_col()
            .w_full()
            .max_w(rem(576.))
            .children(steps)
    }
}

// ── WorkflowRunRow ──────────────────────────────────────────────────────

/// Surface and selection bar colors of a [`WorkflowRunRow`]: `(background, left_bar)`.
pub fn run_row_look(selected: bool, hovered: bool) -> (Option<Hsla>, Option<Hsla>) {
    let bg = if selected {
        Some(color(ColorRole::LayerSelected01))
    } else if hovered {
        Some(color(ColorRole::LayerHover01))
    } else {
        None
    };
    let bar = selected.then(|| color(ColorRole::BorderInteractive));
    (bg, bar)
}

/// A run in the list (`WorkflowRunRow`, `.t3-wfrow`): a flow glyph, name
/// and `project · trigger · started`, the state tag and the elapsed time.
/// A 48px button row over a bottom hairline.
#[derive(IntoElement)]
pub struct WorkflowRunRow {
    id: ElementId,
    name: SharedString,
    state: RunState,
    trigger: SharedString,
    started: SharedString,
    elapsed: u64,
    project: SharedString,
    selected: bool,
    show_icon: bool,
    on_click: Option<Handler>,
}

impl WorkflowRunRow {
    /// A row for the run `name`.
    pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>, state: RunState) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            state,
            trigger: SharedString::default(),
            started: SharedString::default(),
            elapsed: 0,
            project: SharedString::default(),
            selected: false,
            show_icon: true,
            on_click: None,
        }
    }

    /// Highlight as the selected run (`layer-selected-01` + 3px `border-interactive` start bar).
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Show the leading `Flow` icon (default `true`).
    pub fn show_icon(mut self, show: bool) -> Self {
        self.show_icon = show;
        self
    }

    /// What started it (`trigger`).
    pub fn trigger(mut self, trigger: impl Into<SharedString>) -> Self {
        self.trigger = trigger.into();
        self
    }

    /// When it started (`started`).
    pub fn started(mut self, started: impl Into<SharedString>) -> Self {
        self.started = started.into();
        self
    }

    /// Seconds it has run (`elapsed`).
    pub fn elapsed(mut self, secs: u64) -> Self {
        self.elapsed = secs;
        self
    }

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

    /// Pressed.
    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 WorkflowRunRow {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let (hovered, hover) = press::hover((id.clone(), "hover"), window, cx);
        let (focus, ring) = press::focus((id.clone(), "focus"), window, cx);
        let meta = format!(
            "{} \u{b7} {} \u{b7} {}",
            self.project, self.trigger, self.started
        );
        let (bg, bar) = run_row_look(self.selected, hovered);
        let on_click = self.on_click.clone();
        // `.t3-wfrow { display: flex; width: 100%; align-items: center; gap: spacing-04;
        // min-height: size-lg; padding: 0 spacing-05; border-bottom: 1px solid border-subtle-01;
        // color: text-primary }`, `:hover { background: layer-hover-01 }`.
        gpui_kit::base::Button::new(id)
            .track_focus(&focus)
            .accessibility_label(self.name.clone())
            .relative()
            .flex()
            .flex_row()
            .items_center()
            .justify_start()
            .gap(rem(12.))
            .w_full()
            .min_h(rem(48.))
            .px(rem(16.))
            .border_b_1()
            .border_color(color(ColorRole::BorderSubtle01))
            .when_some(bg, |this, bg| this.bg(bg))
            .text_color(color(ColorRole::TextPrimary))
            .cursor(CursorStyle::PointingHand)
            .on_hover(press::track_hover(hover))
            .when_some(on_click, |this, f| this.on_click(move |_, w, cx| f(w, cx)))
            .when(self.show_icon, |this| {
                this.child(
                    press::icon(CarbonIcon::Flow, 16., color(ColorRole::IconSecondary)).flex_none(),
                )
            })
            .child(
                // `.t3-wfrow-main { display: flex; flex: 1; flex-direction: column;
                // font-size: 0.875rem }`, `b { font-weight: 600 }`.
                sans(div(), 14., 400)
                    .flex()
                    .flex_col()
                    .flex_1()
                    .min_w_0()
                    .items_start()
                    .child(sans(div(), 14., 600).child(self.name.clone()))
                    .child(card_sub(meta)),
            )
            .child(WorkflowStateWord::new(self.state))
            .child(card_sub(fmt_elapsed(self.elapsed)))
            .when_some(bar, |this, bar| {
                this.child(
                    div()
                        .absolute()
                        .top_0()
                        .bottom_0()
                        .left_0()
                        .w(px(3.))
                        .bg(bar),
                )
            })
            .when(ring, |this| this.child(press::ring()))
    }
}

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

    #[test]
    fn state_words_capitalise_and_map_tags() {
        assert_eq!(RunState::Succeeded.label(), "Succeeded");
        assert_eq!(RunState::Waiting.variant(), BadgeVariant::Purple);
        assert_eq!(RunState::Queued.variant(), BadgeVariant::WarmGray);
        assert_eq!(RunState::Cancelled.variant(), BadgeVariant::Gray);
    }

    #[test]
    fn step_marks_follow_the_css() {
        assert!(StepStatus::Running.mark().is_none());
        assert_eq!(
            StepStatus::Waiting.mark(),
            Some((CarbonIcon::Help, color(ColorRole::TagColorPurple)))
        );
        assert_eq!(
            StepStatus::Failed.mark(),
            Some((CarbonIcon::ErrorFilled, color(ColorRole::SupportError)))
        );
    }

    #[test]
    fn branch_elbow_reaches_back_to_the_rail() {
        // `left: calc(-1 * spacing-07 + 7.5px)` lands on the parent rail.
        assert_eq!(-BRANCH_INDENT + RAIL_LEFT + BRANCH_INDENT, RAIL_LEFT);
    }

    #[test]
    fn run_row_selection_and_icon_options() {
        crate::theme::tests_set(crate::CarbonTheme::G100);
        assert_eq!(run_row_look(false, false), (None, None));
        assert_eq!(
            run_row_look(false, true),
            (Some(color(ColorRole::LayerHover01)), None)
        );
        assert_eq!(
            run_row_look(true, false),
            (
                Some(color(ColorRole::LayerSelected01)),
                Some(color(ColorRole::BorderInteractive)),
            )
        );
        let row = WorkflowRunRow::new("r", "Deploy", RunState::Running)
            .selected(true)
            .show_icon(false);
        assert!(row.selected);
        assert!(!row.show_icon);
    }
}