use crate::{
components::{
DropdownMenu, DropdownMenuKind, DropdownMenuSize, MenuItem,
button::{ButtonKind, ButtonSize, ButtonState, ButtonVariant, Geometry, Look},
},
density,
icons::{CarbonIcon, Icon},
motion::{self, Motion},
t3::{
base::{Spin, Status, warning_glyph},
craft::{self, focus_handle, focus_visible, mono, press, rem, sans, sub},
shell::{
BadgeSize, ConnectionStatus, Count, EnvironmentBadge, IconMenu, IdentitySize,
LayoutPanel, MachineKind, PanelLayoutControls, ProjectFavicon, StatusPill,
},
},
theme::color,
tokens::ColorRole,
};
use gpui_kit::{
AnyElement, App, BoxShadow, ElementId, Hsla, InteractiveElement, IntoElement, MouseButton,
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)>;
#[derive(Clone, Debug)]
pub struct HeaderEnvironment {
pub name: SharedString,
pub kind: MachineKind,
pub status: ConnectionStatus,
}
impl HeaderEnvironment {
pub fn new(name: impl Into<SharedString>, kind: MachineKind, status: ConnectionStatus) -> Self {
Self {
name: name.into(),
kind,
status,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HeaderLayout {
pub sidebar: bool,
pub right_panel: bool,
pub terminal: bool,
}
impl Default for HeaderLayout {
fn default() -> Self {
Self {
sidebar: true,
right_panel: false,
terminal: false,
}
}
}
type PanelHandler = Rc<dyn Fn(LayoutPanel, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct ChatHeader {
id: ElementId,
title: SharedString,
project: Option<SharedString>,
branch: Option<SharedString>,
status: Option<Status>,
status_label: Option<SharedString>,
environment: Option<HeaderEnvironment>,
actions: Vec<AnyElement>,
layout: Option<HeaderLayout>,
inline: bool,
on_rename: Option<Handler>,
on_layout: Option<PanelHandler>,
rename_label: SharedString,
}
impl ChatHeader {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
project: None,
branch: None,
status: None,
status_label: None,
environment: None,
actions: Vec::new(),
layout: Some(HeaderLayout::default()),
inline: false,
on_rename: None,
on_layout: None,
rename_label: "Rename thread".into(),
}
}
pub fn project(mut self, project: impl Into<SharedString>) -> Self {
self.project = Some(project.into());
self
}
pub fn branch(mut self, branch: impl Into<SharedString>) -> Self {
self.branch = Some(branch.into());
self
}
pub fn status(mut self, status: Status) -> Self {
self.status = Some(status);
self
}
pub fn status_label(mut self, label: impl Into<SharedString>) -> Self {
self.status_label = Some(label.into());
self
}
pub fn environment(mut self, environment: HeaderEnvironment) -> Self {
self.environment = Some(environment);
self
}
pub fn action(mut self, action: impl IntoElement) -> Self {
self.actions.push(action.into_any_element());
self
}
pub fn layout(mut self, layout: Option<HeaderLayout>) -> Self {
self.layout = layout;
self
}
pub fn inline(mut self, inline: bool) -> Self {
self.inline = inline;
self
}
pub fn on_rename(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_rename = Some(Rc::new(f));
self
}
pub fn on_layout(mut self, f: impl Fn(LayoutPanel, &mut Window, &mut App) + 'static) -> Self {
self.on_layout = Some(Rc::new(f));
self
}
pub fn rename_label(mut self, label: impl Into<SharedString>) -> Self {
self.rename_label = label.into();
self
}
}
impl RenderOnce for ChatHeader {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let title_id: ElementId = (id.clone(), "title").into();
let focus = focus_handle(&title_id, window, cx);
let ring = focus_visible(&focus, window);
let on_rename = self.on_rename.clone();
let secondary = color(ColorRole::TextSecondary);
let floor = self.inline.then(|| {
let run = gpui_kit::TextRun {
len: self.title.len(),
font: crate::typography::font(crate::tokens::FontFamilyKey::Sans, 600),
color: color(ColorRole::TextPrimary),
background_color: None,
underline: None,
strikethrough: None,
};
let width = window
.text_system()
.shape_line(
self.title.clone(),
window.rem_size() * (14. / 16.),
&[run],
None,
)
.width;
title_floor(width, window.rem_size())
});
let title = sans(press(title_id, &focus), 14., 600)
.self_start()
.max_w_full()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.cursor_text()
.text_color(color(ColorRole::TextPrimary))
.tooltip(craft::title_tooltip(self.rename_label.clone()))
.when_some(on_rename, |b, f| b.on_click(move |_, w, cx| f(w, cx)))
.child(div().min_w_0().truncate().child(self.title.clone()))
.when(ring, |b| b.child(craft::focus_ring_offset(2.)));
let sub_line = sans(div(), 12., 400)
.flex()
.items_center()
.gap(rem(8.))
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(secondary)
.when_some(self.project.clone(), |d, p| {
d.child(
div()
.flex()
.flex_none()
.items_center()
.gap(rem(4.))
.child(ProjectFavicon::new(p.clone()).size(IdentitySize::Xs))
.child(p),
)
})
.when_some(self.branch.clone(), |d, b| {
let face = if self.inline {
sans(div(), 12., 400)
} else {
mono(div(), 12., 400)
};
d.child(
face.flex()
.flex_none()
.items_center()
.gap(rem(4.))
.child(
Icon::carbon(CarbonIcon::Branch)
.size_length(rem(12.))
.color(secondary),
)
.child(b),
)
})
.when_some(self.environment.clone(), |d, e| {
d.child(
EnvironmentBadge::new(e.name)
.kind(e.kind)
.status(e.status)
.size(BadgeSize::Sm),
)
})
.when_some(self.status, |d, s| {
d.child(StatusPill::new(s).when_some(self.status_label.clone(), |p, l| p.label(l)))
});
let on_layout = self.on_layout.clone();
let layout = self.layout.map(|l| {
PanelLayoutControls::new((id.clone(), "layout"))
.sidebar(l.sidebar)
.right_panel(l.right_panel)
.terminal(l.terminal)
.when_some(on_layout, |c, f| c.on_toggle(move |p, w, cx| f(p, w, cx)))
});
div()
.id(id)
.flex()
.items_center()
.gap(rem(16.))
.map(|d| {
if self.inline {
d.flex_initial().min_w_0().overflow_hidden()
} else {
d.min_h(rem(48.))
.pt(rem(4.))
.pb(rem(4.))
.pr(rem(8.))
.pl(rem(16.))
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.bg(color(ColorRole::Background))
}
})
.child(
div()
.flex()
.min_w_0()
.map(|d| {
if self.inline {
d.flex_initial().flex_row().items_center().gap(rem(12.))
} else {
d.flex_col().gap(px(2.))
}
})
.when(!self.inline, |d| d.flex_1())
.child(title.when_some(floor, |t, floor| {
t.flex_shrink_1().min_w(floor).self_center()
}))
.child(sub_line.when(self.inline, |l| l.flex_none())),
)
.child(
div()
.flex()
.flex_none()
.items_center()
.gap(rem(8.))
.children(self.actions)
.children(layout),
)
}
}
const TITLE_FLOOR: f32 = 160.;
fn title_floor(width: gpui_kit::Pixels, rem_size: gpui_kit::Pixels) -> gpui_kit::Pixels {
width.min(rem_size * (TITLE_FLOOR / 16.)).ceil()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WorkspaceMode {
Local,
#[default]
Worktree,
}
impl WorkspaceMode {
pub const ALL: [WorkspaceMode; 2] = [Self::Local, Self::Worktree];
pub const fn name(self) -> &'static str {
match self {
Self::Local => "local",
Self::Worktree => "worktree",
}
}
}
#[derive(Clone, Debug)]
pub struct BranchToolbarTexts {
pub run_on: SharedString,
pub this_computer: SharedString,
pub add_machine: SharedString,
pub workspace: SharedString,
pub local: SharedString,
pub worktree: SharedString,
pub main: SharedString,
}
impl Default for BranchToolbarTexts {
fn default() -> Self {
Self {
run_on: "Run on".into(),
this_computer: "This computer".into(),
add_machine: "Add to another machine".into(),
workspace: "Workspace".into(),
local: "Local".into(),
worktree: "New worktree".into(),
main: "main".into(),
}
}
}
type ModeHandler = Rc<dyn Fn(WorkspaceMode, &mut Window, &mut App)>;
type NameHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct BranchToolbar {
id: ElementId,
environments: Vec<SharedString>,
environment: Option<SharedString>,
mode: Option<WorkspaceMode>,
default_mode: WorkspaceMode,
branch: Option<SharedString>,
branches: Vec<SharedString>,
on_mode_change: Option<ModeHandler>,
on_environment: Option<NameHandler>,
on_branch: Option<NameHandler>,
on_add_machine: Option<Handler>,
texts: BranchToolbarTexts,
}
impl BranchToolbar {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
environments: Vec::new(),
environment: None,
mode: None,
default_mode: WorkspaceMode::Worktree,
branch: None,
branches: Vec::new(),
on_mode_change: None,
on_environment: None,
on_branch: None,
on_add_machine: None,
texts: BranchToolbarTexts::default(),
}
}
pub fn environments<S: Into<SharedString>>(
mut self,
names: impl IntoIterator<Item = S>,
) -> Self {
self.environments = names.into_iter().map(Into::into).collect();
self
}
pub fn environment(mut self, name: impl Into<SharedString>) -> Self {
self.environment = Some(name.into());
self
}
pub fn mode(mut self, mode: WorkspaceMode) -> Self {
self.mode = Some(mode);
self
}
pub fn default_mode(mut self, mode: WorkspaceMode) -> Self {
self.default_mode = mode;
self
}
pub fn branch(mut self, branch: impl Into<SharedString>) -> Self {
self.branch = Some(branch.into());
self
}
pub fn branches<S: Into<SharedString>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
self.branches = names.into_iter().map(Into::into).collect();
self
}
pub fn on_mode_change(
mut self,
f: impl Fn(WorkspaceMode, &mut Window, &mut App) + 'static,
) -> Self {
self.on_mode_change = Some(Rc::new(f));
self
}
pub fn on_environment(
mut self,
f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_environment = Some(Rc::new(f));
self
}
pub fn on_branch(mut self, f: impl Fn(SharedString, &mut Window, &mut App) + 'static) -> Self {
self.on_branch = Some(Rc::new(f));
self
}
pub fn on_add_machine(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_add_machine = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: BranchToolbarTexts) -> Self {
self.texts = texts;
self
}
}
fn separator() -> AnyElement {
div()
.flex_none()
.w(px(1.))
.self_stretch()
.my(rem(4.))
.bg(color(ColorRole::BorderSubtle01))
.into_any_element()
}
fn picks(names: &[SharedString], icon: CarbonIcon, handler: &Option<NameHandler>) -> Vec<MenuItem> {
names
.iter()
.map(|n| {
let item = MenuItem::item(n.clone()).icon(icon);
match handler.clone() {
Some(f) => {
let n = n.clone();
item.on_select(move |w, cx| f(n.clone(), w, cx))
}
None => item,
}
})
.collect()
}
impl RenderOnce for BranchToolbar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let (mode, store) = crate::components::form::controlled(
(id.clone(), "mode"),
self.mode,
self.default_mode,
window,
cx,
);
let mut env_items = picks(&self.environments, CarbonIcon::Laptop, &self.on_environment);
env_items.push(MenuItem::divider());
let mut add = MenuItem::item(self.texts.add_machine.clone()).icon(CarbonIcon::Add);
if let Some(f) = self.on_add_machine.clone() {
add = add.on_select(move |w, cx| f(w, cx));
}
env_items.push(add);
let segs = [
(
WorkspaceMode::Local,
self.texts.local.clone(),
CarbonIcon::Folder,
),
(
WorkspaceMode::Worktree,
self.texts.worktree.clone(),
CarbonIcon::Branch,
),
]
.into_iter()
.enumerate()
.map(|(i, (m, label, icon))| {
let on = m == mode;
let sid = sub(&id, "seg", i);
let focus = focus_handle(&sid, window, cx);
let ring = focus_visible(&focus, window);
let store = store.clone();
let on_change = self.on_mode_change.clone();
let ink = color(if on {
ColorRole::TextPrimary
} else {
ColorRole::TextSecondary
});
sans(press(sid, &focus), 12., if on { 600 } else { 400 })
.role(gpui_kit::Role::RadioButton)
.accessibility_label(label.clone())
.gap(rem(4.))
.h(rem(24.))
.px(rem(8.))
.text_color(ink)
.when(on, |b| {
b.bg(color(ColorRole::Layer02)).child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.border_1()
.border_color(color(ColorRole::BorderInverse)),
)
})
.on_click(move |_, window, cx| {
store.update(cx, |v, cx| {
*v = m;
cx.notify();
});
if let Some(f) = &on_change {
f(m, window, cx);
}
})
.child(Icon::carbon(icon).size_length(rem(14.)).color(ink))
.child(label)
.when(ring, |b| b.child(craft::focus_ring()))
});
sans(div(), 12., 400)
.id(id.clone())
.flex()
.flex_wrap()
.items_center()
.gap(rem(4.))
.px(rem(8.))
.bg(color(ColorRole::Layer01))
.child(
craft::text(self.texts.run_on.clone(), 12., ColorRole::TextSecondary).pl(rem(8.)),
)
.child(
DropdownMenu::new((id.clone(), "env"))
.label(
self.environment
.clone()
.unwrap_or_else(|| self.texts.this_computer.clone()),
)
.kind(DropdownMenuKind::Ghost)
.size(DropdownMenuSize::Sm)
.items(env_items),
)
.child(separator())
.child(
div()
.flex()
.p(px(2.))
.bg(color(ColorRole::LayerAccent01))
.children(segs),
)
.child(separator())
.child(
DropdownMenu::new((id, "branch"))
.label(
self.branch
.clone()
.unwrap_or_else(|| self.texts.main.clone()),
)
.kind(DropdownMenuKind::Ghost)
.size(DropdownMenuSize::Sm)
.items(picks(&self.branches, CarbonIcon::Branch, &self.on_branch)),
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum GitState {
#[default]
Changes,
Ahead,
Pushed,
Pr,
Behind,
None,
Init,
Publish,
}
impl GitState {
pub const ALL: [GitState; 8] = [
Self::Changes,
Self::Ahead,
Self::Pushed,
Self::Pr,
Self::Behind,
Self::None,
Self::Init,
Self::Publish,
];
pub const fn name(self) -> &'static str {
match self {
Self::Changes => "changes",
Self::Ahead => "ahead",
Self::Pushed => "pushed",
Self::Pr => "pr",
Self::Behind => "behind",
Self::None => "none",
Self::Init => "init",
Self::Publish => "publish",
}
}
pub const fn icon(self) -> CarbonIcon {
match self {
Self::Pr => CarbonIcon::Launch,
Self::Pushed => CarbonIcon::PullRequest,
_ => CarbonIcon::Commit,
}
}
}
fn plural(n: usize, one: &str) -> String {
format!("{n} {one}{}", if n == 1 { "" } else { "s" })
}
pub fn git_label(state: GitState, files: usize, ahead: usize) -> String {
match state {
GitState::Changes if files > 0 => format!("Commit {}", plural(files, "file")),
GitState::Changes => "Commit\u{2026}".into(),
GitState::Ahead => format!("Push {}", plural(ahead, "commit")),
GitState::Pushed => "Create PR".into(),
GitState::Pr => "View PR".into(),
GitState::Behind => "Pull".into(),
GitState::None => "No changes".into(),
GitState::Init => "Initialize Git".into(),
GitState::Publish => "Publish repository...".into(),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GitAction {
Commit,
CommitBranch,
Push,
Pr,
Discard,
}
pub fn git_menu_enabled(state: GitState, files: usize) -> [bool; 5] {
let f = files > 0;
[
f,
f,
state == GitState::Ahead,
matches!(state, GitState::Pushed | GitState::Ahead),
f,
]
}
type ActionHandler = Rc<dyn Fn(GitAction, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct GitActionsControl {
id: ElementId,
state: GitState,
ahead: usize,
files: usize,
progress: Option<SharedString>,
disabled: bool,
approval_pending: bool,
note: Option<SharedString>,
label: Option<SharedString>,
on_primary: Option<Handler>,
on_action: Option<ActionHandler>,
menu_label: SharedString,
menu_items: [SharedString; 5],
behind_note: SharedString,
}
impl GitActionsControl {
pub fn new(id: impl Into<ElementId>, state: GitState) -> Self {
Self {
id: id.into(),
state,
ahead: 0,
files: 0,
progress: None,
disabled: false,
approval_pending: false,
note: None,
label: None,
on_primary: None,
on_action: None,
menu_label: "Git action options".into(),
menu_items: [
"Commit".into(),
"Commit on new branch".into(),
"Push".into(),
"Create pull request".into(),
"Discard all changes".into(),
],
behind_note: "Behind upstream. Pull/rebase first.".into(),
}
}
pub fn ahead(mut self, ahead: usize) -> Self {
self.ahead = ahead;
self
}
pub fn files(mut self, files: usize) -> Self {
self.files = files;
self
}
pub fn progress(mut self, progress: impl Into<SharedString>) -> Self {
self.progress = Some(progress.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn approval_pending(mut self, pending: bool) -> Self {
self.approval_pending = pending;
self
}
pub fn note(mut self, note: impl Into<SharedString>) -> Self {
self.note = Some(note.into());
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn on_primary(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_primary = Some(Rc::new(f));
self
}
pub fn on_action(mut self, f: impl Fn(GitAction, &mut Window, &mut App) + 'static) -> Self {
self.on_action = Some(Rc::new(f));
self
}
pub fn texts(
mut self,
menu_label: impl Into<SharedString>,
items: [SharedString; 5],
behind_note: impl Into<SharedString>,
) -> Self {
self.menu_label = menu_label.into();
self.menu_items = items;
self.behind_note = behind_note.into();
self
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GitQuiet {
pub text: Hsla,
pub icon: Hsla,
pub chip: (Hsla, Hsla),
}
impl GitQuiet {
pub fn current() -> Self {
Self {
text: color(ColorRole::TextSecondary),
icon: color(ColorRole::IconSecondary),
chip: (
color(ColorRole::LayerAccent01),
color(ColorRole::TextSecondary),
),
}
}
}
pub fn git_chip_colors(approval_pending: bool) -> (Hsla, Hsla) {
if approval_pending {
GitQuiet::current().chip
} else {
(color(ColorRole::Layer02), color(ColorRole::TextPrimary))
}
}
fn warn(text: SharedString) -> AnyElement {
sans(div(), 12., 400)
.flex()
.flex_none()
.items_center()
.gap(rem(4.))
.ml(rem(8.))
.text_color(color(ColorRole::TextSecondary))
.child(warning_glyph(14.))
.child(text)
.into_any_element()
}
#[derive(Default)]
struct Pointer {
hovered: bool,
pressed: bool,
}
impl RenderOnce for GitActionsControl {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
if let Some(progress) = self.progress.clone() {
return sans(div(), 12., 400)
.flex()
.flex_none()
.items_center()
.gap(rem(8.))
.h(rem(32.))
.px(rem(12.))
.bg(color(ColorRole::Layer01))
.text_color(color(ColorRole::TextPrimary))
.child(Spin::new((id, "spin")))
.child(progress)
.into_any_element();
}
let off = self.state == GitState::None || self.disabled;
let count_in_label =
self.state == GitState::Changes && self.label.is_none() && self.files > 0;
let label: SharedString = self
.label
.clone()
.unwrap_or_else(|| git_label(self.state, self.files, self.ahead).into());
let kind = if off {
ButtonKind::Ghost
} else {
ButtonKind::Secondary
};
let main_id: ElementId = (id.clone(), "primary").into();
let focus = focus_handle(&main_id, window, cx);
let pointer =
window.use_keyed_state((id.clone(), "pointer"), cx, |_, _| Pointer::default());
let state = {
let p = pointer.read(cx);
ButtonState {
hovered: p.hovered && !off,
pressed: p.pressed && !off,
focused: focus.is_focused(window),
disabled: off,
}
};
let mut look = Look::of(kind, state, false);
let quiet = (self.approval_pending && !off).then(GitQuiet::current);
if let Some(q) = quiet {
look.background = Hsla::transparent_black();
look.text = q.text;
look.icon = q.icon;
if !state.focused {
look.border = Hsla::transparent_black();
}
}
let geometry = Geometry::of(ButtonSize::Sm, density::current(), kind, false);
let bg = motion::animate_color(
(id.clone(), "bg"),
look.background,
Motion::HOVER,
window,
cx,
);
let ink = motion::animate_color((id.clone(), "ink"), look.text, Motion::HOVER, window, cx);
let on_primary = self.on_primary.clone();
let chip = (self.files > 0 && !count_in_label).then(|| {
let (chip_bg, chip_ink) = git_chip_colors(self.approval_pending);
sans(div(), 12., 400)
.ml(rem(8.))
.px(rem(4.))
.line_height(rem(16.))
.rounded(rem(16.))
.bg(chip_bg)
.text_color(chip_ink)
.child(self.files.to_string())
});
let icon = Icon::carbon(self.state.icon())
.size_length(rem(16.))
.color(look.icon);
let mut primary = gpui_kit::base::Button::new(main_id)
.track_focus(&focus)
.disabled(off)
.accessibility_label(label.clone())
.relative()
.flex()
.flex_none()
.items_start()
.justify_start()
.whitespace_nowrap()
.type_style_body()
.h(rem(geometry.height))
.pt(rem(geometry.padding_top))
.pl(rem(geometry.padding_left))
.pr(rem(geometry.padding_right))
.bg(bg)
.border_1()
.border_color(look.border)
.text_color(ink)
.cursor(if off {
gpui_kit::CursorStyle::OperationNotAllowed
} else {
gpui_kit::CursorStyle::PointingHand
})
.on_hover({
let pointer = pointer.clone();
move |h, _, cx| {
pointer.update(cx, |p, cx| {
p.hovered = *h;
if !h {
p.pressed = false;
}
cx.notify();
})
}
})
.on_mouse_down(MouseButton::Left, {
let pointer = pointer.clone();
move |_, _, cx| {
pointer.update(cx, |p, cx| {
p.pressed = true;
cx.notify();
})
}
})
.on_mouse_up(MouseButton::Left, {
let pointer = pointer.clone();
move |_, _, cx| {
pointer.update(cx, |p, cx| {
p.pressed = false;
cx.notify();
})
}
})
.when_some(on_primary, |b, f| b.on_click(move |_, w, cx| f(w, cx)))
.child(label)
.children(chip);
primary = match geometry.icon_top {
Some(top) => primary.child(
div()
.absolute()
.top(rem(top))
.right(rem(geometry.icon_right))
.size(rem(16.))
.child(icon),
),
None => primary.child(
div()
.self_center()
.ml(rem(8.))
.mt(rem(-geometry.padding_top))
.size(rem(16.))
.child(icon),
),
};
let primary = primary.children(
[
look.focus_ring.map(|c| (0., c)),
look.focus_inset.map(|c| (1., c)),
]
.into_iter()
.flatten()
.map(|(inset, c)| {
div()
.absolute()
.top(px(inset))
.left(px(inset))
.right(px(inset))
.bottom(px(inset))
.border_1()
.border_color(c)
}),
);
let enabled = git_menu_enabled(self.state, self.files);
let keys = [
GitAction::Commit,
GitAction::CommitBranch,
GitAction::Push,
GitAction::Pr,
GitAction::Discard,
];
let mut items: Vec<MenuItem> = Vec::new();
for i in 0..5 {
if i == 4 {
items.push(MenuItem::divider());
}
let mut item = MenuItem::item(self.menu_items[i].clone())
.disabled(!enabled[i])
.danger(i == 4);
if let Some(f) = self.on_action.clone() {
let key = keys[i];
item = item.on_select(move |w, cx| f(key, w, cx));
}
items.push(item);
}
let variant = if off || quiet.is_some() {
ButtonVariant::Ghost
} else {
ButtonVariant::Secondary
};
div()
.flex()
.flex_none()
.items_center()
.gap(px(1.))
.child(primary)
.child(
IconMenu::new((id, "menu"), self.menu_label.clone())
.variant(variant)
.size(ButtonSize::Sm)
.disabled(off)
.when_some(quiet, |m, q| {
m.icon_color(q.icon).fill(Hsla::transparent_black())
})
.items(items),
)
.when_some(self.note.clone(), |d, n| d.child(warn(n)))
.when(self.state == GitState::Behind, |d| {
d.child(warn(self.behind_note.clone()))
})
.into_any_element()
}
}
trait BodyType: Styled + Sized {
fn type_style_body(self) -> Self {
use crate::typography::TypeStyled as _;
self.type_style(crate::tokens::TypeStyle::BodyCompact01)
}
}
impl<T: Styled> BodyType for T {}
#[derive(IntoElement)]
pub struct ThreadDetailsSection {
id: ElementId,
title: SharedString,
count: Option<usize>,
action: Option<AnyElement>,
default_open: bool,
children: Vec<AnyElement>,
}
impl ThreadDetailsSection {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
count: None,
action: None,
default_open: true,
children: Vec::new(),
}
}
pub fn count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
pub fn action(mut self, action: impl IntoElement) -> Self {
self.action = Some(action.into_any_element());
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
}
impl ParentElement for ThreadDetailsSection {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for ThreadDetailsSection {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let open_state = window.use_keyed_state((id.clone(), "open"), cx, {
let d = self.default_open;
move |_, _| d
});
let open = *open_state.read(cx);
let head_id: ElementId = (id.clone(), "head").into();
let focus = focus_handle(&head_id, window, cx);
let ring = focus_visible(&focus, window);
let head = sans(press(head_id, &focus), 14., 400)
.accessibility_label(self.title.clone())
.flex_1()
.w_full()
.gap(rem(8.))
.h(rem(40.))
.pl(rem(12.))
.pr(rem(8.))
.text_color(color(ColorRole::TextPrimary))
.on_click(move |_, _, cx| {
open_state.update(cx, |o, cx| {
*o = !*o;
cx.notify();
})
})
.child(
Icon::carbon(CarbonIcon::ChevronDown)
.size_length(rem(14.))
.color(color(ColorRole::IconSecondary))
.rotate(gpui_kit::radians(if open {
0.
} else {
-std::f32::consts::FRAC_PI_2
})),
)
.child(sans(div(), 14., 400).child(self.title.clone()))
.when_some(self.count, |b, n| b.child(Count::new(n)))
.when(ring, |b| b.child(craft::focus_ring()));
div()
.id(id)
.flex()
.flex_col()
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.child(
div()
.flex()
.items_center()
.pr(rem(8.))
.child(head)
.children(self.action),
)
.when(open, |d| {
d.child(
div()
.flex()
.flex_col()
.gap(rem(8.))
.px(rem(12.))
.pb(rem(12.))
.children(self.children),
)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MeterTone {
Ok,
Warning,
Error,
}
impl MeterTone {
pub fn of(pct: u32) -> Self {
if pct > 90 {
Self::Error
} else if pct > 70 {
Self::Warning
} else {
Self::Ok
}
}
pub fn fill(self) -> Hsla {
color(match self {
Self::Ok => ColorRole::IconSecondary,
Self::Warning => ColorRole::SupportWarning,
Self::Error => ColorRole::SupportError,
})
}
}
pub fn meter_percent(used: u64, total: u64) -> u32 {
if total == 0 {
return 0;
}
((used as f64 / total as f64) * 100.).round() as u32
}
#[derive(IntoElement, Clone, Debug)]
pub struct ContextMeter {
used: u64,
total: u64,
label: SharedString,
tokens_label: SharedString,
}
impl ContextMeter {
pub fn new(used: u64, total: u64) -> Self {
Self {
used,
total,
label: "Context window".into(),
tokens_label: "tokens".into(),
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn tokens_label(mut self, label: impl Into<SharedString>) -> Self {
self.tokens_label = label.into();
self
}
}
impl RenderOnce for ContextMeter {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let pct = meter_percent(self.used, self.total);
let tone = MeterTone::of(pct);
let k = |n: u64| (n as f64 / 1000.).round() as u64;
sans(div(), 12., 400)
.flex()
.flex_col()
.gap(rem(4.))
.child(
div()
.flex()
.justify_between()
.text_color(color(ColorRole::TextSecondary))
.child(self.label.clone())
.child(
sans(div(), 12., 400)
.text_color(color(ColorRole::TextPrimary))
.child(format!("{pct}%")),
),
)
.child(
div().h(px(4.)).bg(color(ColorRole::LayerAccent01)).child(
div()
.h_full()
.w(relative((pct.min(100) as f32) / 100.))
.bg(tone.fill()),
),
)
.child(craft::text(
format!(
"{}k of {}k {}",
k(self.used),
k(self.total),
self.tokens_label
),
12.,
ColorRole::TextHelper,
))
}
}
#[derive(IntoElement, Clone, Debug)]
pub struct ThreadHoverCard {
title: SharedString,
project: SharedString,
status: Status,
provider: SharedString,
last_message: SharedString,
time: SharedString,
}
impl ThreadHoverCard {
pub fn new(title: impl Into<SharedString>, project: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
project: project.into(),
status: Status::Idle,
provider: SharedString::default(),
last_message: SharedString::default(),
time: SharedString::default(),
}
}
pub fn status(mut self, status: Status) -> Self {
self.status = status;
self
}
pub fn provider(mut self, provider: impl Into<SharedString>) -> Self {
self.provider = provider.into();
self
}
pub fn last_message(mut self, message: impl Into<SharedString>) -> Self {
self.last_message = message.into();
self
}
pub fn time(mut self, time: impl Into<SharedString>) -> Self {
self.time = time.into();
self
}
}
impl RenderOnce for ThreadHoverCard {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
sans(div(), 14., 400)
.flex()
.flex_col()
.gap(rem(8.))
.w(rem(320.))
.max_w_full()
.p(rem(16.))
.bg(color(ColorRole::Layer01))
.shadow(vec![
BoxShadow::new(px(0.), px(2.), color(ColorRole::Shadow)).blur_radius(px(6.)),
])
.text_color(color(ColorRole::TextPrimary))
.child(
sans(div(), 12., 400)
.flex()
.items_center()
.gap(rem(8.))
.text_color(color(ColorRole::TextSecondary))
.child(ProjectFavicon::new(self.project.clone()).size(IdentitySize::Sm))
.child(self.project.clone())
.child(div().flex_1())
.child(StatusPill::new(self.status)),
)
.child(sans(div(), 14., 600).child(self.title.clone()))
.child(
crate::typography::paragraph()
.line_clamp(3)
.overflow_hidden()
.text_color(color(ColorRole::TextSecondary))
.child(self.last_message.clone()),
)
.child(
sans(div(), 12., 400)
.flex()
.text_color(color(ColorRole::TextHelper))
.child(self.provider.clone())
.child(div().px(px(2.)).child("\u{b7}"))
.child(self.time.clone()),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_header_says_its_status_in_the_words_given() {
let h = ChatHeader::new("h", "t").status(Status::NeedsYou);
assert_eq!(h.status_label, None);
let h = h.status_label("需要你");
assert_eq!(h.status_label.as_deref(), Some("需要你"));
}
#[test]
fn an_inline_title_keeps_160px_or_its_whole_width_when_shorter() {
let rem = px(16.);
assert_eq!(title_floor(px(400.), rem), px(160.));
assert_eq!(title_floor(px(90.4), rem), px(91.));
assert_eq!(title_floor(px(800.), px(32.)), px(320.));
}
#[test]
fn git_labels_follow_the_reference() {
assert_eq!(git_label(GitState::Changes, 6, 0), "Commit 6 files");
assert_eq!(git_label(GitState::Changes, 1, 0), "Commit 1 file");
assert_eq!(git_label(GitState::Changes, 0, 0), "Commit\u{2026}");
assert_eq!(git_label(GitState::Ahead, 0, 2), "Push 2 commits");
assert_eq!(git_label(GitState::Publish, 0, 0), "Publish repository...");
assert_eq!(GitState::Pr.icon(), CarbonIcon::Launch);
assert_eq!(
git_menu_enabled(GitState::Ahead, 0),
[false, false, true, true, false]
);
assert_eq!(
git_menu_enabled(GitState::Changes, 6),
[true, true, false, false, true]
);
}
#[test]
fn approval_pending_quiets_the_control() {
let q = GitQuiet::current();
assert_eq!(q.text, color(ColorRole::TextSecondary));
assert_eq!(q.icon, color(ColorRole::IconSecondary));
assert_eq!(
git_chip_colors(true),
(
color(ColorRole::LayerAccent01),
color(ColorRole::TextSecondary)
)
);
assert_eq!(
git_chip_colors(false),
(color(ColorRole::Layer02), color(ColorRole::TextPrimary))
);
assert!(!GitActionsControl::new("g", GitState::Changes).approval_pending);
assert!(
GitActionsControl::new("g", GitState::Changes)
.approval_pending(true)
.approval_pending
);
}
#[test]
fn meter_tones() {
assert_eq!(meter_percent(142_000, 200_000), 71);
assert_eq!(MeterTone::of(71), MeterTone::Warning);
assert_eq!(MeterTone::of(70), MeterTone::Ok);
assert_eq!(MeterTone::of(91), MeterTone::Error);
assert_eq!(meter_percent(1, 0), 0);
}
}