use super::pr_detail::icon_button;
use super::pull_request::{ReviewDecision, ReviewDecisionBadge};
use crate::{
components::{AvatarColor, Button, ButtonSize, ButtonVariant, Textarea, TextareaState},
icons::{CarbonIcon, Icon},
t3::craft::{self, AvatarTone, focus_handle, focus_visible, press, rem, sans},
theme::{LayerLevel, color},
tokens::ColorRole,
};
use gpui_kit::{
AnyElement, App, AppContext as _, ElementId, FocusHandle, Hsla, InteractiveElement,
IntoElement, KeyDownEvent, ParentElement, RenderOnce, SharedString,
StatefulInteractiveElement as _, Styled, Window, div, prelude::FluentBuilder as _, px,
relative,
};
use std::rc::Rc;
type Handler = Rc<dyn Fn(&mut Window, &mut App)>;
type IndexHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type EventEmojiHandler = Rc<dyn Fn(usize, SharedString, &mut Window, &mut App)>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reaction {
pub emoji: SharedString,
pub count: usize,
pub mine: bool,
}
impl Reaction {
pub fn new(emoji: impl Into<SharedString>, count: usize) -> Self {
Self {
emoji: emoji.into(),
count,
mine: false,
}
}
pub fn mine(mut self, mine: bool) -> Self {
self.mine = mine;
self
}
}
type EmojiHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct ReactionBar {
id: ElementId,
reactions: Vec<Reaction>,
square: bool,
on_react: Option<EmojiHandler>,
on_add: Option<Handler>,
add_label: SharedString,
}
impl ReactionBar {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
reactions: Vec::new(),
square: false,
on_react: None,
on_add: None,
add_label: "Add reaction".into(),
}
}
pub fn square(mut self, square: bool) -> Self {
self.square = square;
self
}
pub fn reactions(mut self, reactions: impl IntoIterator<Item = Reaction>) -> Self {
self.reactions = reactions.into_iter().collect();
self
}
pub fn on_react(mut self, f: impl Fn(SharedString, &mut Window, &mut App) + 'static) -> Self {
self.on_react = Some(Rc::new(f));
self
}
pub fn on_add(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_add = Some(Rc::new(f));
self
}
pub fn add_label(mut self, label: impl Into<SharedString>) -> Self {
self.add_label = label.into();
self
}
}
pub fn reaction_look(mine: bool, hovered: bool) -> (Hsla, Hsla, Option<Hsla>) {
if mine {
(
color(if hovered {
ColorRole::LayerAccentHover01
} else {
ColorRole::TagBackgroundBlue
}),
color(ColorRole::TagColorBlue),
Some(color(ColorRole::BorderInteractive)),
)
} else {
(
color(if hovered {
ColorRole::LayerAccentHover01
} else {
ColorRole::LayerAccent01
}),
color(ColorRole::TextPrimary),
None,
)
}
}
impl RenderOnce for ReactionBar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
div()
.flex()
.flex_wrap()
.items_center()
.gap(rem(4.))
.children(self.reactions.iter().enumerate().map(|(i, r)| {
let rid = craft::sub(&id, "r", i);
let focus = focus_handle(&rid, window, cx);
let ring = focus_visible(&focus, window);
let hovered = window
.use_keyed_state((rid.clone(), "hover"), cx, |_, _| false)
.clone();
let (fill, ink, edge) = reaction_look(r.mine, *hovered.read(cx));
let on_react = self.on_react.clone();
let emoji = r.emoji.clone();
let pill_radius = if self.square { rem(0.) } else { rem(16.) };
sans(press(rid, &focus), 12., 400)
.gap(rem(4.))
.h(rem(24.))
.px(rem(8.))
.rounded(pill_radius)
.bg(fill)
.text_color(ink)
.when_some(edge, |this, c| this.border_1().border_color(c).px(rem(7.)))
.on_hover(move |h, _, cx| {
hovered.update(cx, |v, cx| {
*v = *h;
cx.notify();
})
})
.when_some(on_react, |this, f| {
this.on_click(move |_, w, cx| f(emoji.clone(), w, cx))
})
.child(r.emoji.clone())
.child(r.count.to_string())
.when(ring, |this| {
this.child(
div()
.absolute()
.top(px(-2.))
.left(px(-2.))
.right(px(-2.))
.bottom(px(-2.))
.rounded(pill_radius)
.border_2()
.border_color(color(ColorRole::Focus)),
)
})
}))
.child(icon_button(
(id, "add"),
self.add_label.clone(),
CarbonIcon::FaceAdd,
self.on_add.clone(),
))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum EventKind {
#[default]
Commit,
Label,
Merged,
Push,
Ref,
Comment,
Review,
}
impl EventKind {
pub const ALL: [EventKind; 7] = [
Self::Commit,
Self::Label,
Self::Merged,
Self::Push,
Self::Ref,
Self::Comment,
Self::Review,
];
pub const fn is_card(self) -> bool {
matches!(self, Self::Comment | Self::Review)
}
pub const fn icon(self) -> CarbonIcon {
match self {
Self::Commit => CarbonIcon::Commit,
Self::Label => CarbonIcon::Tag,
Self::Merged => CarbonIcon::Merge,
Self::Push => CarbonIcon::Upload,
Self::Ref => CarbonIcon::Link,
Self::Comment | Self::Review => CarbonIcon::CircleFilled,
}
}
pub fn ink(self) -> Hsla {
color(match self {
Self::Merged => ColorRole::TagColorPurple,
_ => ColorRole::IconSecondary,
})
}
}
pub struct TimelineEvent {
kind: EventKind,
actor: SharedString,
text: SharedString,
body: SharedString,
review: Option<ReviewDecision>,
time: SharedString,
color: Option<AvatarColor>,
marker: Option<AnyElement>,
reactions: Option<Vec<Reaction>>,
}
impl TimelineEvent {
pub fn new(
kind: EventKind,
actor: impl Into<SharedString>,
time: impl Into<SharedString>,
) -> Self {
Self {
kind,
actor: actor.into(),
text: SharedString::default(),
body: SharedString::default(),
review: None,
time: time.into(),
color: None,
marker: None,
reactions: None,
}
}
pub fn kind(&self) -> EventKind {
self.kind
}
pub fn text(mut self, text: impl Into<SharedString>) -> Self {
self.text = text.into();
self
}
pub fn body(mut self, body: impl Into<SharedString>) -> Self {
self.body = body.into();
self
}
pub fn review(mut self, review: ReviewDecision) -> Self {
self.review = Some(review);
self
}
pub fn color(mut self, color: AvatarColor) -> Self {
self.color = Some(color);
self
}
pub fn marker(mut self, marker: impl IntoElement) -> Self {
self.marker = Some(marker.into_any_element());
self
}
pub fn reactions(mut self, reactions: impl IntoIterator<Item = Reaction>) -> Self {
self.reactions = Some(reactions.into_iter().collect());
self
}
}
#[derive(IntoElement)]
pub struct PullRequestTimeline {
id: ElementId,
events: Vec<TimelineEvent>,
add_label: SharedString,
square_reactions: bool,
on_add_to_thread: Option<IndexHandler>,
on_react: Option<EventEmojiHandler>,
}
impl PullRequestTimeline {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
events: Vec::new(),
add_label: "Add to thread".into(),
square_reactions: false,
on_add_to_thread: None,
on_react: None,
}
}
pub fn square_reactions(mut self, square: bool) -> Self {
self.square_reactions = square;
self
}
pub fn events(mut self, events: impl IntoIterator<Item = TimelineEvent>) -> Self {
self.events = events.into_iter().collect();
self
}
pub fn add_label(mut self, label: impl Into<SharedString>) -> Self {
self.add_label = label.into();
self
}
pub fn on_add_to_thread(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_add_to_thread = Some(Rc::new(f));
self
}
pub fn on_react(
mut self,
f: impl Fn(usize, SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_react = Some(Rc::new(f));
self
}
}
impl RenderOnce for PullRequestTimeline {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let square_reactions = self.square_reactions;
let secondary = color(ColorRole::TextSecondary);
let items = self.events.into_iter().enumerate().map(|(i, e)| {
let marker = if e.kind.is_card() {
e.marker.unwrap_or_else(|| {
let tone = e
.color
.map(AvatarTone::Avatar)
.unwrap_or_else(|| craft::actor_tone(&e.actor));
craft::initials(craft::two_letters(&e.actor), tone, 24.).into_any_element()
})
} else {
Icon::carbon(e.kind.icon())
.size_length(rem(16.))
.color(e.kind.ink())
.into_any_element()
};
let marker = div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(rem(24.))
.bg(color(ColorRole::Background))
.child(marker);
let content = if e.kind.is_card() {
let on_add = self.on_add_to_thread.clone();
let on_react = self.on_react.clone();
div()
.flex_1()
.min_w_0()
.bg(color(ColorRole::Layer01))
.child(
sans(div(), 12., 400)
.flex()
.items_center()
.gap(rem(8.))
.min_h(rem(40.))
.pl(rem(12.))
.pr(rem(4.))
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.text_color(secondary)
.child(
sans(div(), 14., 400)
.text_color(color(ColorRole::TextPrimary))
.child(e.actor.clone()),
)
.when_some(e.review, |this, r| this.child(ReviewDecisionBadge::new(r)))
.child(e.time.clone())
.child(div().flex_1())
.child(
Button::new(craft::sub(&id, "add", i), self.add_label.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon(CarbonIcon::Chat)
.when_some(on_add, |b, f| {
b.on_click(move |_, w, cx| f(i, w, cx))
}),
),
)
.child(
sans(div(), 14., 400)
.p(rem(12.))
.line_height(relative(1.42857))
.text_color(color(ColorRole::TextPrimary))
.child(e.body.clone()),
)
.when_some(e.reactions, |this, reactions| {
this.child(
div().px(rem(12.)).pb(rem(12.)).child(
ReactionBar::new(craft::sub(&id, "reactions", i))
.square(square_reactions)
.reactions(reactions)
.when_some(on_react, |bar, f| {
bar.on_react(move |emoji, w, cx| f(i, emoji, w, cx))
}),
),
)
})
.into_any_element()
} else {
sans(div(), 14., 400)
.flex()
.flex_wrap()
.items_center()
.gap_x(rem(8.))
.gap_y(rem(4.))
.min_h(rem(24.))
.text_color(secondary)
.child(
sans(div(), 14., 400)
.text_color(color(ColorRole::TextPrimary))
.child(e.actor.clone()),
)
.child(e.text.clone())
.child(craft::text(e.time.clone(), 12., ColorRole::TextSecondary))
.into_any_element()
};
div()
.flex()
.gap(rem(12.))
.pb(rem(16.))
.child(marker)
.child(content)
});
div()
.relative()
.flex()
.flex_col()
.child(
div()
.absolute()
.left(px(11.))
.top_0()
.bottom_0()
.w(px(1.))
.bg(color(ColorRole::BorderSubtle01)),
)
.children(items)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ReviewVerdict {
#[default]
Comment,
Approve,
Changes,
}
impl ReviewVerdict {
pub const ALL: [ReviewVerdict; 3] = [Self::Comment, Self::Approve, Self::Changes];
pub const fn name(self) -> &'static str {
match self {
Self::Comment => "comment",
Self::Approve => "approve",
Self::Changes => "changes",
}
}
}
#[derive(Clone, Debug)]
pub struct ReviewFormTexts {
pub summary: SharedString,
pub placeholder: SharedString,
pub group: SharedString,
pub options: [(SharedString, SharedString); 3],
}
impl Default for ReviewFormTexts {
fn default() -> Self {
Self {
summary: "Review summary".into(),
placeholder: "Leave a comment".into(),
group: "Review type".into(),
options: [
(
"Comment".into(),
"Submit general feedback without explicit approval.".into(),
),
(
"Approve".into(),
"Submit feedback and approve merging these changes.".into(),
),
(
"Request changes".into(),
"Submit feedback that must be addressed before merging.".into(),
),
],
}
}
}
type VerdictHandler = Rc<dyn Fn(ReviewVerdict, &mut Window, &mut App)>;
type ReviewSubmitHandler = Rc<dyn Fn(ReviewVerdict, SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct ReviewForm {
id: ElementId,
submit_label: SharedString,
submit_disabled: bool,
flat: bool,
hint: Option<SharedString>,
require_content_unless_approve: bool,
has_line_comments: bool,
on_submit: Option<VerdictHandler>,
on_submit_review: Option<ReviewSubmitHandler>,
texts: ReviewFormTexts,
}
impl ReviewForm {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
submit_label: "Submit review".into(),
submit_disabled: false,
flat: false,
hint: None,
require_content_unless_approve: false,
has_line_comments: false,
on_submit: None,
on_submit_review: None,
texts: ReviewFormTexts::default(),
}
}
pub fn submit_label(mut self, label: impl Into<SharedString>) -> Self {
self.submit_label = label.into();
self
}
pub fn submit_disabled(mut self, disabled: bool) -> Self {
self.submit_disabled = disabled;
self
}
pub fn flat(mut self, flat: bool) -> Self {
self.flat = flat;
self
}
pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
self.hint = Some(hint.into());
self
}
pub fn require_content_unless_approve(mut self, require: bool) -> Self {
self.require_content_unless_approve = require;
self
}
pub fn has_line_comments(mut self, has: bool) -> Self {
self.has_line_comments = has;
self
}
pub fn on_submit(mut self, f: impl Fn(ReviewVerdict, &mut Window, &mut App) + 'static) -> Self {
self.on_submit = Some(Rc::new(f));
self
}
pub fn on_submit_review(
mut self,
f: impl Fn(ReviewVerdict, SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_submit_review = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: ReviewFormTexts) -> Self {
self.texts = texts;
self
}
}
fn radio_circle(checked: bool) -> gpui_kit::Div {
let ink = color(ColorRole::IconPrimary);
div()
.flex()
.flex_none()
.items_center()
.justify_center()
.mt(px(2.))
.size(px(16.))
.rounded_full()
.border_1()
.border_color(ink)
.when(checked, |this| {
this.child(div().size(px(7.)).rounded_full().bg(ink))
})
}
impl RenderOnce for ReviewForm {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let flat = self.flat;
let text = window
.use_keyed_state((id.clone(), "text"), cx, |window, cx| {
let ts = cx.new(|cx| TextareaState::new(window, cx));
cx.observe(&ts, |_, _, cx| cx.notify()).detach();
ts
})
.read(cx)
.clone();
let verdict = window
.use_keyed_state((id.clone(), "verdict"), cx, |_, _| ReviewVerdict::Comment)
.clone();
let chosen = *verdict.read(cx);
let empty_blocked = self.require_content_unless_approve
&& chosen != ReviewVerdict::Approve
&& !self.has_line_comments
&& text.read(cx).value().trim().is_empty();
let submit_disabled = self.submit_disabled || empty_blocked;
let handles: Vec<FocusHandle> = (0..3)
.map(|i| focus_handle(&craft::sub(&id, "opt", i), window, cx))
.collect();
let options = ReviewVerdict::ALL.iter().enumerate().map(|(i, v)| {
let on = *v == chosen;
let focus = handles[i].clone();
let ring = focus.is_focused(window);
let (title, desc) = self.texts.options[i].clone();
let verdict = verdict.clone();
let v = *v;
let hovered = window
.use_keyed_state(craft::sub(&id, "opt-hover", i), cx, |_, _| false)
.clone();
let is_hovered = *hovered.read(cx);
let card_bg = if flat {
if is_hovered {
ColorRole::LayerHover01
} else if on {
ColorRole::LayerSelected01
} else {
ColorRole::Layer01
}
} else if is_hovered {
ColorRole::LayerHover02
} else {
ColorRole::Layer02
};
press(craft::sub(&id, "opt", i), &focus)
.role(gpui_kit::Role::RadioButton)
.accessibility_label(title.clone())
.tab_stop(on)
.w_full()
.items_start()
.gap(rem(12.))
.py(rem(12.))
.px(rem(if flat { 16. } else { 12. }))
.bg(color(card_bg))
.on_hover(move |h, _, cx| {
hovered.update(cx, |x, cx| {
*x = *h;
cx.notify();
})
})
.on_click(move |_, _, cx| {
verdict.update(cx, |x, cx| {
*x = v;
cx.notify();
})
})
.child(radio_circle(on))
.child(
sans(div(), 14., 400)
.flex()
.flex_col()
.text_color(color(ColorRole::TextPrimary))
.child(sans(div(), 14., 600).child(title))
.child(craft::text(desc, 12., ColorRole::TextSecondary).mt(px(2.))),
)
.when(on, |this| {
if flat {
this.child(super::pull_request::start_bar(color(
ColorRole::BorderInteractive,
)))
} else {
this.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.border_2()
.border_color(color(ColorRole::BorderInteractive)),
)
}
})
.when(ring, |this| this.child(craft::focus_ring()))
});
let group_keys = {
let verdict = verdict.clone();
let handles = handles.clone();
move |e: &KeyDownEvent, window: &mut Window, cx: &mut App| {
let current = ReviewVerdict::ALL
.iter()
.position(|v| *v == *verdict.read(cx))
.unwrap_or(0);
if let Some(next) =
crate::t3::base::radio_step(e.keystroke.key.as_str(), 3, Some(current))
{
cx.stop_propagation();
verdict.update(cx, |x, cx| {
*x = ReviewVerdict::ALL[next];
cx.notify();
});
handles[next].focus(window, cx);
}
}
};
let on_submit = self.on_submit.clone();
let on_submit_review = self.on_submit_review.clone();
let text_for_submit = text.clone();
let has_submit_cb = on_submit.is_some() || on_submit_review.is_some();
sans(div(), 14., 400)
.id(id.clone())
.flex()
.flex_col()
.gap(rem(16.))
.w_full()
.when(!flat, |d| {
d.max_w(rem(480.)).p(rem(16.)).bg(color(ColorRole::Layer01))
})
.child(
Textarea::new((id.clone(), "summary"), &text)
.label(self.texts.summary.clone())
.placeholder(self.texts.placeholder.clone())
.rows(3)
.layer(if flat {
LayerLevel::One
} else {
LayerLevel::Two
}),
)
.child(
div()
.id((id.clone(), "group"))
.flex()
.flex_col()
.map(|d| if flat { d.gap(rem(8.)) } else { d.gap(px(1.)) })
.on_key_down(group_keys)
.children(options),
)
.child(
div()
.flex()
.flex_wrap()
.justify_end()
.items_center()
.gap(rem(if flat { 16. } else { 8. }))
.when_some(self.hint, |row, hint| {
row.child(
craft::text(hint, 12., ColorRole::TextHelper)
.flex_1()
.min_w_0(),
)
})
.child(
Button::new((id, "submit"), self.submit_label.clone())
.size(ButtonSize::Sm)
.disabled(submit_disabled)
.when(has_submit_cb, |b| {
b.on_click(move |_, w, cx| {
let v = *verdict.read(cx);
if let Some(f) = &on_submit {
f(v, w, cx);
}
if let Some(f) = &on_submit_review {
let body = SharedString::from(
text_for_submit.read(cx).value().to_string(),
);
text_for_submit.update(cx, |s, cx| s.set_value("", w, cx));
f(v, body, w, cx);
}
})
}),
),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reaction_and_event_colors() {
crate::theme::tests_set(crate::tokens::CarbonTheme::White);
assert_eq!(EventKind::Merged.ink(), color(ColorRole::TagColorPurple));
let (fill, ink, ring) = reaction_look(true, false);
assert_eq!(fill, color(ColorRole::TagBackgroundBlue));
assert_eq!(ink, color(ColorRole::TagColorBlue));
assert_eq!(ring, Some(color(ColorRole::BorderInteractive)));
let (fill, _, ring) = reaction_look(false, true);
assert_eq!(fill, color(ColorRole::LayerAccentHover01));
assert!(ring.is_none());
let form = ReviewForm::new("test")
.flat(true)
.require_content_unless_approve(true)
.has_line_comments(true)
.hint("Hint");
assert!(form.flat && form.require_content_unless_approve && form.has_line_comments);
}
}