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)>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RunState {
#[default]
Running,
Queued,
Succeeded,
Failed,
Waiting,
Cancelled,
}
impl RunState {
pub const ALL: [RunState; 6] = [
Self::Running,
Self::Queued,
Self::Succeeded,
Self::Failed,
Self::Waiting,
Self::Cancelled,
];
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",
}
}
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()
}
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,
}
}
}
#[derive(IntoElement, Clone, Debug)]
pub struct WorkflowStateWord {
state: RunState,
label: Option<SharedString>,
}
impl WorkflowStateWord {
pub fn new(state: RunState) -> Self {
Self { state, label: None }
}
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)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StepStatus {
Succeeded,
Failed,
Running,
#[default]
Pending,
Waiting,
Skipped,
}
impl StepStatus {
pub const ALL: [StepStatus; 6] = [
Self::Succeeded,
Self::Failed,
Self::Running,
Self::Pending,
Self::Waiting,
Self::Skipped,
];
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",
}
}
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)))
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorkflowStep {
pub title: SharedString,
pub status: StepStatus,
pub elapsed: Option<u64>,
pub detail: Option<SharedString>,
pub branch: bool,
}
impl WorkflowStep {
pub fn new(title: impl Into<SharedString>, status: StepStatus) -> Self {
Self {
title: title.into(),
status,
..Default::default()
}
}
pub fn elapsed(mut self, secs: u64) -> Self {
self.elapsed = Some(secs);
self
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn branch(mut self, branch: bool) -> Self {
self.branch = branch;
self
}
}
#[derive(Clone, Debug)]
pub struct WorkflowFeedTexts {
pub running: SharedString,
pub resume: SharedString,
pub resume_note: SharedString,
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(),
}
}
}
pub const BRANCH_INDENT: f32 = 32.;
pub const RAIL_LEFT: f32 = 7.5;
#[derive(IntoElement)]
pub struct WorkflowRunFeed {
id: ElementId,
steps: Vec<WorkflowStep>,
texts: WorkflowFeedTexts,
on_resume: Option<IndexHandler>,
on_answer: Option<IndexHandler>,
}
impl WorkflowRunFeed {
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,
}
}
pub fn texts(mut self, texts: WorkflowFeedTexts) -> Self {
self.texts = texts;
self
}
pub fn on_resume(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_resume = Some(Rc::new(f));
self
}
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;
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))));
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,
};
div()
.relative()
.flex()
.flex_row()
.gap(rem(12.))
.pb(rem(16.))
.when(s.branch, |this| this.ml(rem(BRANCH_INDENT)))
.when(i + 1 < n, |this| {
this.child(
div()
.absolute()
.left(px(RAIL_LEFT))
.top(rem(20.))
.bottom_0()
.w(px(1.))
.bg(line),
)
})
.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),
)
})
.child(
div()
.relative()
.flex()
.flex_none()
.items_center()
.w(rem(16.))
.h(rem(20.))
.bg(color(ColorRole::Background))
.child(mark),
)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(rem(8.))
.child(head)
.when_some(s.detail.clone(), |this, d| {
this.child(
sans(div(), 14., 400)
.text_color(color(ColorRole::TextSecondary))
.child(d),
)
})
.children(actions),
)
});
div()
.id(id.clone())
.flex()
.flex_col()
.w_full()
.max_w(rem(576.))
.children(steps)
}
}
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)
}
#[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 {
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,
}
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn show_icon(mut self, show: bool) -> Self {
self.show_icon = show;
self
}
pub fn trigger(mut self, trigger: impl Into<SharedString>) -> Self {
self.trigger = trigger.into();
self
}
pub fn started(mut self, started: impl Into<SharedString>) -> Self {
self.started = started.into();
self
}
pub fn elapsed(mut self, secs: u64) -> Self {
self.elapsed = secs;
self
}
pub fn project(mut self, project: impl Into<SharedString>) -> Self {
self.project = project.into();
self
}
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();
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(
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() {
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);
}
}