use super::head::{Handler, ghost_icon, ghost_text};
use crate::u0::shell::{option_focus, toggles_checkbox};
use crate::{
components::{Button, ButtonSize, ButtonVariant, textarea},
density,
icons::{CarbonIcon, Icon},
t3::{
base::{Spin, visually_hidden},
craft::{mono, rem, sans},
review::{
ChecksGlyph, ChecksStatus, DiffFileStatus, DiffStat, FileStatus, IssueState,
IssueStateGlyph, PullRequestState, PullRequestStateGlyph,
},
},
theme::color,
tokens::{self, ColorRole},
u0::primitives::parts::{focus_ring, focus_visible, keyed_focus},
};
use gpui_kit::{
AnyElement, App, AppContext as _, Context, CursorStyle, Div, ElementId, Entity, Focusable as _,
Hsla, InteractiveElement as _, IntoElement, MouseButton, ParentElement, PathBuilder, Pixels,
Render, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, canvas,
component::{
Sizable as _, Size,
input::{Textarea as KitTextarea, TextareaState},
},
div, point,
prelude::FluentBuilder as _,
px, relative,
};
use std::collections::BTreeSet;
use std::rc::Rc;
fn hover_state(
id: ElementId,
window: &mut Window,
cx: &mut App,
) -> (bool, impl Fn(&bool, &mut Window, &mut App) + 'static) {
let store = window.use_keyed_state(id, cx, |_, _| false);
let over = *store.read(cx);
(over, move |h: &bool, _: &mut Window, cx: &mut App| {
store.update(cx, |v, cx| {
if *v != *h {
*v = *h;
cx.notify();
}
})
})
}
fn meta_line(runs: impl IntoIterator<Item = AnyElement>) -> Div {
sans(div(), 12., 400)
.flex()
.gap(tokens::SPACING_03)
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(color(ColorRole::TextSecondary))
.children(runs)
}
fn mono_run(text: impl Into<SharedString>) -> AnyElement {
mono(div(), 12., 400)
.flex_none()
.child(text.into())
.into_any_element()
}
fn run(text: impl Into<SharedString>) -> AnyElement {
div().flex_none().child(text.into()).into_any_element()
}
fn main_column() -> Div {
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(px(2.))
.py(tokens::SPACING_02)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CommitGraph {
Start,
#[default]
Line,
End,
}
impl CommitGraph {
pub const ALL: [Self; 3] = [Self::Start, Self::Line, Self::End];
pub const fn name(self) -> &'static str {
match self {
Self::Start => "start",
Self::Line => "line",
Self::End => "end",
}
}
pub const fn halves(self) -> (bool, bool) {
match self {
Self::Start => (false, true),
Self::Line => (true, true),
Self::End => (true, false),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RefKind {
Head,
Local,
Remote,
}
impl RefKind {
pub fn of(name: &str) -> Self {
if name == "HEAD" {
Self::Head
} else if name.starts_with("origin/") {
Self::Remote
} else {
Self::Local
}
}
pub fn colors(self) -> (Hsla, Hsla) {
use ColorRole::*;
let (bg, fg) = match self {
Self::Head => (TagBackgroundGreen, TagColorGreen),
Self::Local => (TagBackgroundBlue, TagColorBlue),
Self::Remote => (TagBackgroundPurple, TagColorPurple),
};
(color(bg), color(fg))
}
}
fn ref_chip(name: SharedString) -> AnyElement {
let (bg, fg) = RefKind::of(&name).colors();
mono(div(), 12., 400)
.flex_none()
.line_height(rem(16.))
.px(tokens::SPACING_02)
.bg(bg)
.text_color(fg)
.child(name)
.into_any_element()
}
pub fn commit_background(current: bool, hovered: bool) -> Hsla {
color(if current {
ColorRole::StateCurrentBackground
} else if hovered {
ColorRole::LayerHover01
} else {
ColorRole::Layer01
})
}
#[derive(IntoElement)]
pub struct CommitRow {
id: ElementId,
sha: SharedString,
message: SharedString,
author: SharedString,
time: SharedString,
refs: Vec<SharedString>,
stat: Option<(usize, usize)>,
current: bool,
graph: CommitGraph,
on_click: Option<Handler>,
}
impl CommitRow {
pub fn new(
id: impl Into<ElementId>,
sha: impl Into<SharedString>,
message: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
sha: sha.into(),
message: message.into(),
author: SharedString::default(),
time: SharedString::default(),
refs: Vec::new(),
stat: None,
current: false,
graph: CommitGraph::Line,
on_click: None,
}
}
pub fn author(mut self, author: impl Into<SharedString>) -> Self {
self.author = author.into();
self
}
pub fn time(mut self, time: impl Into<SharedString>) -> Self {
self.time = time.into();
self
}
pub fn refs(mut self, refs: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.refs = refs.into_iter().map(Into::into).collect();
self
}
pub fn stat(mut self, added: usize, removed: usize) -> Self {
self.stat = Some((added, removed));
self
}
pub fn current(mut self, current: bool) -> Self {
self.current = current;
self
}
pub fn graph(mut self, graph: CommitGraph) -> Self {
self.graph = graph;
self
}
pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_click = Some(Rc::new(f));
self
}
}
fn graph_lane(graph: CommitGraph, current: bool) -> Div {
let line = color(ColorRole::Charts1);
let (top, bottom) = graph.halves();
let half = |top_half: bool| {
div()
.absolute()
.left(relative(0.5))
.ml(px(-1.))
.w(px(2.))
.h(relative(0.5))
.bg(line)
.when(top_half, |d| d.top_0())
.when(!top_half, |d| d.bottom_0())
};
div()
.relative()
.flex_none()
.self_stretch()
.w(rem(24.))
.when(top, |d| d.child(half(true)))
.when(bottom, |d| d.child(half(false)))
.child(
div()
.absolute()
.left(relative(0.5))
.top(relative(0.5))
.ml(px(-5.))
.mt(px(-5.))
.size(px(10.))
.rounded_full()
.border_2()
.border_color(line)
.bg(if current {
line
} else {
color(ColorRole::Layer01)
}),
)
}
impl RenderOnce for CommitRow {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let focus = keyed_focus((id.clone(), "focus"), window, cx);
let ring = focus_visible(&focus, window);
let (over, on_hover) = hover_state((id.clone(), "hover").into(), window, cx);
let short: String = self.sha.chars().take(7).collect();
let on_click = self.on_click.clone();
sans(gpui_kit::base::Button::new(id), 14., 400)
.track_focus(&focus)
.relative()
.flex()
.items_center()
.w_full()
.gap(tokens::SPACING_03)
.min_h(density::current().row_lg())
.pl(tokens::SPACING_02)
.pr(tokens::SPACING_04)
.bg(commit_background(self.current, over))
.text_color(color(ColorRole::TextPrimary))
.cursor(CursorStyle::PointingHand)
.on_hover(on_hover)
.on_click(move |_, w, cx| {
if let Some(f) = &on_click {
f(w, cx);
}
})
.child(graph_lane(self.graph, self.current))
.child(
main_column()
.child(
div()
.flex()
.items_center()
.gap(tokens::SPACING_03)
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.child(div().min_w_0().truncate().child(self.message.clone()))
.children(self.refs.iter().cloned().map(ref_chip)),
)
.child(meta_line([
mono_run(short),
run(self.author.clone()),
run(self.time.clone()),
])),
)
.when_some(self.stat, |b, (a, r)| b.child(DiffStat::new(a, r)))
.when(ring, |b| b.child(focus_ring()))
}
}
#[derive(Clone)]
pub struct StashRowTexts {
pub files: Rc<dyn Fn(usize) -> SharedString>,
pub apply: SharedString,
pub pop: SharedString,
pub drop: SharedString,
}
impl Default for StashRowTexts {
fn default() -> Self {
Self {
files: Rc::new(|n| format!("{n} files").into()),
apply: "Apply".into(),
pop: "Pop".into(),
drop: "Drop stash".into(),
}
}
}
#[derive(IntoElement)]
pub struct StashRow {
id: ElementId,
index: usize,
message: SharedString,
branch: SharedString,
time: SharedString,
files: usize,
on_apply: Option<Handler>,
on_pop: Option<Handler>,
on_drop: Option<Handler>,
texts: StashRowTexts,
}
impl StashRow {
pub fn new(id: impl Into<ElementId>, index: usize, message: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
index,
message: message.into(),
branch: SharedString::default(),
time: SharedString::default(),
files: 0,
on_apply: None,
on_pop: None,
on_drop: None,
texts: StashRowTexts::default(),
}
}
pub fn branch(mut self, branch: impl Into<SharedString>) -> Self {
self.branch = branch.into();
self
}
pub fn files(mut self, files: usize) -> Self {
self.files = files;
self
}
pub fn time(mut self, time: impl Into<SharedString>) -> Self {
self.time = time.into();
self
}
pub fn on_apply(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_apply = Some(Rc::new(f));
self
}
pub fn on_pop(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_pop = Some(Rc::new(f));
self
}
pub fn on_drop(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_drop = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: StashRowTexts) -> Self {
self.texts = texts;
self
}
}
impl RenderOnce for StashRow {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
sans(div(), 14., 400)
.id(id.clone())
.flex()
.items_center()
.w_full()
.gap(tokens::SPACING_03)
.min_h(density::current().row_lg())
.pl(tokens::SPACING_05)
.pr(tokens::SPACING_02)
.bg(color(ColorRole::Layer01))
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.text_color(color(ColorRole::TextPrimary))
.child(
Icon::carbon(CarbonIcon::Archive)
.size_length(rem(16.))
.color(color(ColorRole::IconSecondary))
.flex_none(),
)
.child(
main_column()
.child(
div()
.flex()
.items_center()
.gap(tokens::SPACING_02)
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.child(
mono(div(), 12., 400)
.flex_none()
.text_color(color(ColorRole::TextSecondary))
.child(format!("stash@{{{}}}", self.index)),
)
.child(div().min_w_0().truncate().child(self.message.clone())),
)
.child(meta_line([
mono_run(self.branch.clone()),
run((self.texts.files)(self.files)),
run(self.time.clone()),
])),
)
.child(ghost_text(
(id.clone(), "apply"),
self.texts.apply.clone(),
self.on_apply,
))
.child(ghost_text(
(id.clone(), "pop"),
self.texts.pop.clone(),
self.on_pop,
))
.child(ghost_icon(
(id, "drop"),
self.texts.drop.clone(),
CarbonIcon::TrashCan,
false,
self.on_drop,
))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChangedFile {
pub path: SharedString,
pub status: FileStatus,
pub added: usize,
pub removed: usize,
}
impl ChangedFile {
pub fn new(
path: impl Into<SharedString>,
status: FileStatus,
added: usize,
removed: usize,
) -> Self {
Self {
path: path.into(),
status,
added,
removed,
}
}
}
pub fn can_commit(staged: usize, message: &str) -> bool {
staged > 0 && !message.trim().is_empty()
}
#[derive(Clone)]
pub struct CommitComposerTexts {
pub changes: SharedString,
pub staged: Rc<dyn Fn(usize, usize) -> SharedString>,
pub message: SharedString,
pub generate: SharedString,
pub generating: SharedString,
pub commit: Rc<dyn Fn(usize) -> SharedString>,
pub commit_and_push: SharedString,
pub ahead: Rc<dyn Fn(usize) -> SharedString>,
}
impl Default for CommitComposerTexts {
fn default() -> Self {
Self {
changes: "Changes".into(),
staged: Rc::new(|s, t| format!("{s} of {t} staged").into()),
message: "Commit message".into(),
generate: "Write it for me".into(),
generating: "Writing…".into(),
commit: Rc::new(|n| format!("Commit {n} file{}", if n == 1 { "" } else { "s" }).into()),
commit_and_push: "Commit & push".into(),
ahead: Rc::new(|n| format!("{n} ahead of origin").into()),
}
}
}
pub type MessageSetter = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
type GenerateHandler = Rc<dyn Fn(MessageSetter, &mut Window, &mut App)>;
type CommitHandler = Rc<dyn Fn(SharedString, Vec<SharedString>, &mut Window, &mut App)>;
type ToggleStagedHandler = Rc<dyn Fn(SharedString, bool, &mut Window, &mut App)>;
struct ComposerModel {
staged: BTreeSet<SharedString>,
message: Entity<TextareaState>,
height: f32,
drag: Option<(Pixels, f32)>,
}
pub const MESSAGE_HEIGHT: f32 = 3. * 18. + 8. + 32. + 1.;
pub const MESSAGE_MIN_HEIGHT: f32 = 18. + 8. + 32. + 1.;
const MESSAGE_CHROME: f32 = MESSAGE_HEIGHT - (3. * 18. + 4.);
pub fn resized_message_height(start: f32, dy: f32) -> f32 {
(start + dy).max(MESSAGE_MIN_HEIGHT)
}
struct MessageResize;
impl Render for MessageResize {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
gpui_kit::Empty
}
}
fn message_grip(id: &ElementId, model: Entity<ComposerModel>) -> impl IntoElement {
let down = model.clone();
div()
.id((id.clone(), "msg-grip"))
.absolute()
.right_0()
.bottom_0()
.size(rem(15.))
.cursor(CursorStyle::ResizeUpDown)
.on_mouse_down(MouseButton::Left, move |e, _, cx| {
cx.stop_propagation();
down.update(cx, |m, _| m.drag = Some((e.position.y, m.height)));
})
.on_drag(MessageResize, |_, _, _, cx| cx.new(|_| MessageResize))
.on_drag_move::<MessageResize>(move |e, window, cx| {
let scale = f32::from(window.rem_size()) / 16.;
model.update(cx, |m, cx| {
if let Some((y, start)) = m.drag {
let dy = f32::from(e.event.position.y - y) / scale;
m.height = resized_message_height(start, dy);
cx.notify();
}
});
})
.child(
canvas(
|_, _, _| (),
|b, _, window, _| {
let s = f32::from(window.rem_size()) / 16.;
let device = 1. / window.scale_factor();
let (r, bottom) = (b.right(), b.bottom());
let at =
|x: f32, y: f32, dy: f32| point(r - px(x * s), bottom - px(y * s) + px(dy));
for (ink, dy) in [
(gpui_kit::hsla(0., 0., 0., 0.6), 0.),
(gpui_kit::hsla(0., 0., 1., 0.6), device),
] {
for ((x0, y0), (x1, y1)) in
[((8.5, 2.5), (2.5, 8.5)), ((4.5, 2.5), (2.5, 4.5))]
{
let mut path = PathBuilder::stroke(px(s));
path.move_to(at(x0, y0, dy));
path.line_to(at(x1, y1, dy));
if let Ok(path) = path.build() {
window.paint_path(path, ink);
}
}
}
},
)
.size_full(),
)
}
#[derive(IntoElement)]
pub struct CommitComposer {
id: ElementId,
files: Vec<ChangedFile>,
branch: SharedString,
ahead: usize,
generating: bool,
message_state: Option<Entity<TextareaState>>,
unstaged: Option<BTreeSet<SharedString>>,
on_toggle_staged: Option<ToggleStagedHandler>,
push_variant: ButtonVariant,
warning: Option<AnyElement>,
on_generate: Option<GenerateHandler>,
on_commit: Option<CommitHandler>,
on_commit_and_push: Option<CommitHandler>,
texts: CommitComposerTexts,
}
impl CommitComposer {
pub fn new(id: impl Into<ElementId>, files: impl IntoIterator<Item = ChangedFile>) -> Self {
Self {
id: id.into(),
files: files.into_iter().collect(),
branch: "main".into(),
ahead: 0,
generating: false,
message_state: None,
unstaged: None,
on_toggle_staged: None,
push_variant: ButtonVariant::Secondary,
warning: None,
on_generate: None,
on_commit: None,
on_commit_and_push: None,
texts: CommitComposerTexts::default(),
}
}
pub fn message_state(mut self, state: Entity<TextareaState>) -> Self {
self.message_state = Some(state);
self
}
pub fn unstaged<S: Into<SharedString>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.unstaged = Some(paths.into_iter().map(Into::into).collect());
self
}
pub fn on_toggle_staged(
mut self,
f: impl Fn(SharedString, bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_toggle_staged = Some(Rc::new(f));
self
}
pub fn push_variant(mut self, variant: ButtonVariant) -> Self {
self.push_variant = variant;
self
}
pub fn warning(mut self, warning: impl IntoElement) -> Self {
self.warning = Some(warning.into_any_element());
self
}
pub fn branch(mut self, branch: impl Into<SharedString>) -> Self {
self.branch = branch.into();
self
}
pub fn ahead(mut self, ahead: usize) -> Self {
self.ahead = ahead;
self
}
pub fn generating(mut self, generating: bool) -> Self {
self.generating = generating;
self
}
pub fn on_generate(
mut self,
f: impl Fn(MessageSetter, &mut Window, &mut App) + 'static,
) -> Self {
self.on_generate = Some(Rc::new(f));
self
}
pub fn on_commit(
mut self,
f: impl Fn(SharedString, Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_commit = Some(Rc::new(f));
self
}
pub fn on_commit_and_push(
mut self,
f: impl Fn(SharedString, Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_commit_and_push = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: CommitComposerTexts) -> Self {
self.texts = texts;
self
}
}
pub fn check_box(checked: bool, ring: bool) -> Div {
let ink = color(ColorRole::IconPrimary);
div()
.relative()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(rem(16.))
.border_1()
.border_color(ink)
.rounded(tokens::BORDER_RADIUS_02.rems())
.when(checked, |d| {
d.bg(ink).child(
Icon::carbon(CarbonIcon::Checkmark)
.size_length(rem(12.))
.color(color(ColorRole::IconInverse)),
)
})
.when(ring, |d| {
d.child(
div()
.absolute()
.top(px(-4.))
.left(px(-4.))
.right(px(-4.))
.bottom(px(-4.))
.border_2()
.border_color(color(ColorRole::Focus)),
)
})
}
impl RenderOnce for CommitComposer {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let paths: Vec<SharedString> = self.files.iter().map(|f| f.path.clone()).collect();
let model = window.use_keyed_state((id.clone(), "model"), cx, {
let paths = paths.clone();
move |window, cx| ComposerModel {
staged: paths.into_iter().collect(),
message: cx.new(|cx| TextareaState::new(window, cx)),
height: MESSAGE_HEIGHT,
drag: None,
}
});
let (staged, message) = {
let m = model.read(cx);
let staged = match &self.unstaged {
Some(left_out) => paths
.iter()
.filter(|p| !left_out.contains(*p))
.cloned()
.collect(),
None => m.staged.clone(),
};
let message = self
.message_state
.clone()
.unwrap_or_else(|| m.message.clone());
(staged, message)
};
let text = message.read(cx).value().to_string();
let enabled = can_commit(staged.len(), &text);
let selected: Vec<SharedString> = paths
.iter()
.filter(|p| staged.contains(*p))
.cloned()
.collect();
let secondary = color(ColorRole::TextSecondary);
let head = sans(div(), 14., 400)
.flex()
.items_center()
.gap(tokens::SPACING_03)
.h(density::current().row_lg())
.px(tokens::SPACING_04)
.text_color(color(ColorRole::TextPrimary))
.child(
sans(div(), 14., 400)
.flex_none()
.child(self.texts.changes.clone()),
)
.child(
sans(div(), 12., 400)
.flex_none()
.text_color(secondary)
.child((self.texts.staged)(staged.len(), self.files.len())),
)
.child(div().flex_1())
.child(
mono(div(), 12., 400)
.flex()
.items_center()
.gap(px(4.))
.min_w_0()
.text_color(secondary)
.child(
Icon::carbon(CarbonIcon::Branch)
.size_length(rem(12.))
.color(secondary)
.flex_none(),
)
.child(div().min_w_0().truncate().child(self.branch.clone())),
);
let rows = self.files.iter().enumerate().map(|(i, f)| {
let rid: ElementId = (id.clone(), SharedString::from(format!("file-{i}"))).into();
let focus = keyed_focus((rid.clone(), "focus"), window, cx);
let ring = focus_visible(&focus, window);
let (over, on_hover) = hover_state((rid.clone(), "hover").into(), window, cx);
let on = staged.contains(&f.path);
let toggle = {
let model = model.clone();
let path = f.path.clone();
let on_toggle = self.on_toggle_staged.clone();
let controlled = self.unstaged.is_some();
move |w: &mut Window, cx: &mut App| {
let next = !on;
if !controlled {
model.update(cx, |m, cx| {
if !m.staged.remove(&path) {
m.staged.insert(path.clone());
}
cx.notify();
});
}
if let Some(cb) = &on_toggle {
cb(path.clone(), next, w, cx);
}
}
};
sans(div(), 14., 400)
.id(rid)
.track_focus(&option_focus(focus))
.flex()
.items_center()
.gap(tokens::SPACING_03)
.min_h(density::current().row())
.px(tokens::SPACING_04)
.when(over, |d| d.bg(color(ColorRole::LayerHover01)))
.cursor(CursorStyle::PointingHand)
.on_hover(on_hover)
.on_click(move |e, w, cx| {
if toggles_checkbox(e) {
toggle(w, cx)
}
})
.child(check_box(on, ring))
.child(DiffFileStatus::new(f.status))
.child(
mono(div(), 12., 400)
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis_start()
.child(f.path.clone()),
)
.child(DiffStat::new(f.added, f.removed))
.into_any_element()
});
let rows: Vec<AnyElement> = rows.collect();
let field_focus = message.read(cx).focus_handle(cx);
let focused = field_focus.is_focused(window);
let placeholder = text.is_empty().then(|| {
sans(div(), 14., 400)
.absolute()
.top(rem(8.))
.left(rem(12.))
.text_color(color(ColorRole::TextPlaceholder))
.child(self.texts.message.clone())
});
let (gen_over, gen_hover) = hover_state((id.clone(), "gen-hover").into(), window, cx);
let gen_focus = keyed_focus((id.clone(), "gen-focus"), window, cx);
let gen_ring = focus_visible(&gen_focus, window);
let generating = self.generating;
let link = color(ColorRole::LinkPrimary);
let on_generate = self.on_generate.clone();
let setter: MessageSetter = {
let message = message.clone();
Rc::new(move |text, window, cx| {
message.update(cx, |s, cx| s.set_value(text, window, cx));
})
};
let generate = sans(gpui_kit::base::Button::new((id.clone(), "gen")), 12., 400)
.track_focus(&gen_focus)
.disabled(generating)
.absolute()
.right(rem(16.))
.bottom(rem(14.))
.flex()
.items_center()
.gap(tokens::SPACING_02)
.h(rem(24.))
.px(tokens::SPACING_03)
.text_color(link)
.when(gen_over && !generating, |b| {
b.bg(color(ColorRole::LayerHover01))
})
.cursor(if generating {
CursorStyle::Arrow
} else {
CursorStyle::PointingHand
})
.on_hover(gen_hover)
.on_click(move |_, w, cx| {
if let Some(f) = &on_generate {
f(setter.clone(), w, cx);
}
})
.map(|b| {
if generating {
b.child(Spin::new((id.clone(), "spin")).size(14.).color(link))
.child(self.texts.generating.clone())
} else {
b.child(
Icon::carbon(CarbonIcon::MagicWand)
.size_length(rem(14.))
.color(link),
)
.child(self.texts.generate.clone())
}
})
.when(gen_ring, |b| b.child(focus_ring()));
let focus_box = field_focus.clone();
let height = model.read(cx).height;
let field = textarea::tab_moves_focus(div().id((id.clone(), "msg-box")))
.relative()
.w_full()
.h(rem(height))
.pt(rem(8. - 2.))
.pb(rem(32.))
.pl(rem(12. - 4.))
.pr(rem(12. - 4.))
.bg(color(ColorRole::Field02))
.border_b_1()
.border_color(color(ColorRole::BorderStrong01))
.cursor(CursorStyle::IBeam)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
focus_box.focus(window, cx);
})
.child(
KitTextarea::new(&message)
.appearance(false)
.with_size(Size::XSmall)
.aria_label(self.texts.message.clone())
.h(rem(height - MESSAGE_CHROME))
.w_full()
.text_size(rem(14.))
.line_height(rem(18.))
.text_color(color(ColorRole::TextPrimary)),
)
.children(placeholder)
.child(message_grip(&id, model.clone()))
.when(focused, |d| d.child(focus_ring()));
let msg = div()
.relative()
.py(tokens::SPACING_03)
.px(tokens::SPACING_04)
.border_t_1()
.border_color(color(ColorRole::BorderSubtle01))
.child(field)
.child(generate);
let commit =
|key: &'static str, label: SharedString, variant, handler: Option<CommitHandler>| {
let message = message.clone();
let selected = selected.clone();
Button::new((id.clone(), key), label)
.variant(variant)
.size(ButtonSize::Sm)
.disabled(!enabled)
.on_click(move |_, w, cx| {
let text: SharedString = message.read(cx).value().to_string().into();
if let Some(f) = &handler {
f(text, selected.clone(), w, cx);
}
})
};
let actions = div()
.flex()
.flex_wrap()
.items_center()
.gap(tokens::SPACING_03)
.px(tokens::SPACING_04)
.pb(tokens::SPACING_04)
.child(commit(
"commit",
(self.texts.commit)(staged.len()),
ButtonVariant::Primary,
self.on_commit.clone(),
))
.child(commit(
"push",
self.texts.commit_and_push.clone(),
self.push_variant,
self.on_commit_and_push.clone(),
))
.when(self.ahead > 0, |d| {
d.child(
sans(div(), 12., 400)
.text_color(secondary)
.child((self.texts.ahead)(self.ahead)),
)
});
div()
.id(id)
.flex()
.flex_col()
.w_full()
.bg(color(ColorRole::Layer01))
.child(head)
.child(
div()
.flex()
.flex_col()
.border_t_1()
.border_color(color(ColorRole::BorderSubtle01))
.children(rows),
)
.child(msg)
.when_some(self.warning, |d, w| {
d.child(div().px(tokens::SPACING_04).pb(tokens::SPACING_03).child(w))
})
.child(actions)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkedKind {
PullRequest(PullRequestState),
Issue(IssueState),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LinkedItem {
pub id: SharedString,
pub kind: LinkedKind,
pub title: SharedString,
pub checks: Option<ChecksStatus>,
}
impl LinkedItem {
pub fn pull_request(
id: impl Into<SharedString>,
state: PullRequestState,
title: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
kind: LinkedKind::PullRequest(state),
title: title.into(),
checks: None,
}
}
pub fn issue(
id: impl Into<SharedString>,
state: IssueState,
title: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
kind: LinkedKind::Issue(state),
title: title.into(),
checks: None,
}
}
pub fn checks(mut self, checks: ChecksStatus) -> Self {
self.checks = Some(checks);
self
}
}
#[derive(Clone)]
pub struct LinkedItemsTexts {
pub title: SharedString,
pub link: SharedString,
pub unlink: Rc<dyn Fn(&str) -> SharedString>,
pub empty: SharedString,
}
impl Default for LinkedItemsTexts {
fn default() -> Self {
Self {
title: "Linked".into(),
link: "Link".into(),
unlink: Rc::new(|id| format!("Unlink {id}").into()),
empty: "No pull requests or issues linked to this session.".into(),
}
}
}
type UnlinkHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct LinkedItemsSection {
id: ElementId,
items: Vec<LinkedItem>,
on_link: Option<Handler>,
on_unlink: Option<UnlinkHandler>,
texts: LinkedItemsTexts,
}
impl LinkedItemsSection {
pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = LinkedItem>) -> Self {
Self {
id: id.into(),
items: items.into_iter().collect(),
on_link: None,
on_unlink: None,
texts: LinkedItemsTexts::default(),
}
}
pub fn on_link(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_link = Some(Rc::new(f));
self
}
pub fn on_unlink(mut self, f: impl Fn(SharedString, &mut Window, &mut App) + 'static) -> Self {
self.on_unlink = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: LinkedItemsTexts) -> Self {
self.texts = texts;
self
}
}
fn linked_line() -> Div {
sans(div(), 14., 400)
.flex()
.items_center()
.gap(tokens::SPACING_03)
.min_h(density::current().row_lg())
.pl(tokens::SPACING_04)
.pr(tokens::SPACING_02)
.text_color(color(ColorRole::TextPrimary))
}
impl RenderOnce for LinkedItemsSection {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let secondary = color(ColorRole::TextSecondary);
let head = linked_line()
.child(
Icon::named("expand_more")
.size_length(rem(14.))
.color(color(ColorRole::IconSecondary))
.flex_none(),
)
.child(div().flex_none().child(self.texts.title.clone()))
.child(
sans(div(), 12., 400)
.flex_none()
.line_height(rem(16.))
.px(tokens::SPACING_02)
.rounded(tokens::BORDER_RADIUS_16.rems())
.bg(color(ColorRole::LayerAccent01))
.text_color(secondary)
.child(self.items.len().to_string()),
)
.child(div().flex_1())
.child(
Button::new((id.clone(), "link"), self.texts.link.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon(CarbonIcon::Add)
.when_some(self.on_link.clone(), |b, f| {
b.on_click(move |_, w, cx| f(w, cx))
}),
);
let rows: Vec<AnyElement> = if self.items.is_empty() {
vec![
sans(div(), 12., 400)
.py(tokens::SPACING_04)
.px(tokens::SPACING_05)
.text_color(secondary)
.child(self.texts.empty.clone())
.into_any_element(),
]
} else {
self.items
.iter()
.map(|it| {
let glyph = match it.kind {
LinkedKind::PullRequest(s) => {
PullRequestStateGlyph::new(s).into_any_element()
}
LinkedKind::Issue(s) => IssueStateGlyph::new(s).into_any_element(),
};
let unlink = self.on_unlink.clone();
let item_id = it.id.clone();
linked_line()
.border_t_1()
.border_color(color(ColorRole::BorderSubtle01))
.child(glyph)
.child(
div()
.flex()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.items_center()
.gap(px(4.))
.child(
mono(div(), 12., 400)
.flex_none()
.text_color(secondary)
.child(it.id.clone()),
)
.child(div().min_w_0().truncate().child(it.title.clone())),
)
.when_some(it.checks, |d, c| d.child(ChecksGlyph::new(c)))
.child(ghost_icon(
(id.clone(), SharedString::from(format!("unlink-{}", it.id))),
(self.texts.unlink)(&it.id),
CarbonIcon::Unlink,
false,
Some(Rc::new(move |w, cx| {
if let Some(f) = &unlink {
f(item_id.clone(), w, cx);
}
})),
))
.into_any_element()
})
.collect()
};
div()
.id(id)
.flex()
.flex_col()
.w_full()
.bg(color(ColorRole::Layer01))
.child(visually_hidden(self.texts.title.clone()))
.child(head)
.children(rows)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CarbonTheme, theme::color_in};
#[test]
fn refs_and_lanes() {
assert_eq!(RefKind::of("HEAD"), RefKind::Head);
assert_eq!(RefKind::of("origin/main"), RefKind::Remote);
assert_eq!(RefKind::of("feat/dark-tokens"), RefKind::Local);
crate::theme::tests_set(CarbonTheme::White);
let c = |r| color_in(CarbonTheme::White, r);
assert_eq!(
RefKind::Local.colors(),
(c(ColorRole::TagBackgroundBlue), c(ColorRole::TagColorBlue))
);
assert_eq!(
RefKind::Remote.colors().0,
c(ColorRole::TagBackgroundPurple)
);
assert_eq!(RefKind::Head.colors().1, c(ColorRole::TagColorGreen));
assert_eq!(CommitGraph::Start.halves(), (false, true));
assert_eq!(CommitGraph::End.halves(), (true, false));
assert_eq!(CommitGraph::Line.halves(), (true, true));
}
#[test]
fn commit_backgrounds() {
crate::theme::tests_set(CarbonTheme::G100);
let c = |r| color_in(CarbonTheme::G100, r);
assert_eq!(commit_background(false, false), c(ColorRole::Layer01));
assert_eq!(commit_background(false, true), c(ColorRole::LayerHover01));
assert_eq!(
commit_background(true, true),
c(ColorRole::StateCurrentBackground)
);
}
#[test]
fn commit_needs_files_and_a_message() {
assert!(can_commit(2, "Add tokens"));
assert!(!can_commit(0, "Add tokens"));
assert!(!can_commit(2, " \n "));
let t = CommitComposerTexts::default();
assert_eq!((t.commit)(1), "Commit 1 file");
assert_eq!((t.commit)(3), "Commit 3 files");
assert_eq!((t.staged)(2, 3), "2 of 3 staged");
}
}