use super::{
cards::bullet,
parts::{card_sub, child_id, icon_button, title_tooltip},
};
use crate::{
components::{Button, ButtonSize, ButtonVariant, CopyButton},
icons::CarbonIcon,
t3::{
base::Spin,
craft::{mono, sans},
press::{self, Handler, rem},
shell::{EnvironmentMachineIcon, MachineKind},
},
theme::color,
tokens::ColorRole,
};
use gpui_kit::{
AnyElement, App, ClipboardItem, CursorStyle, ElementId, Hsla, InteractiveElement as _,
IntoElement, ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled,
Window, div, prelude::FluentBuilder as _, px, relative,
};
use std::{
rc::Rc,
time::{Duration, SystemTime},
};
type IndexHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
fn click(b: Button, f: Option<Handler>) -> Button {
match f {
Some(f) => b.on_click(move |_, w, cx| f(w, cx)),
None => b,
}
}
#[derive(Clone, Debug)]
pub struct NoProjectsTexts {
pub title: SharedString,
pub add: SharedString,
pub skip: SharedString,
}
impl Default for NoProjectsTexts {
fn default() -> Self {
Self {
title: "What should we work on?".into(),
add: "Add project".into(),
skip: "Start without a project".into(),
}
}
}
#[derive(IntoElement)]
pub struct NoProjectsHero {
id: ElementId,
texts: NoProjectsTexts,
on_add: Option<Handler>,
on_skip: Option<Handler>,
}
impl NoProjectsHero {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
texts: NoProjectsTexts::default(),
on_add: None,
on_skip: None,
}
}
pub fn texts(mut self, texts: NoProjectsTexts) -> Self {
self.texts = texts;
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 on_skip(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_skip = Some(Rc::new(f));
self
}
}
impl RenderOnce for NoProjectsHero {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
div()
.id(id.clone())
.flex()
.flex_col()
.items_center()
.gap(rem(32.))
.py(rem(64.))
.px(rem(16.))
.text_center()
.child(
sans(div(), 42., 300)
.line_height(relative(1.199))
.text_color(color(ColorRole::TextPrimary))
.child(self.texts.title.clone()),
)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.justify_center()
.gap(rem(8.))
.child(click(
Button::new((id.clone(), "add"), self.texts.add.clone())
.icon(CarbonIcon::FolderOpen),
self.on_add.clone(),
))
.child(click(
Button::new((id.clone(), "skip"), self.texts.skip.clone())
.variant(ButtonVariant::Ghost),
self.on_skip.clone(),
)),
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SetupState {
#[default]
Waiting,
Off,
}
impl SetupState {
pub const ALL: [SetupState; 2] = [Self::Waiting, Self::Off];
pub const fn name(self) -> &'static str {
match self {
Self::Waiting => "waiting",
Self::Off => "off",
}
}
}
#[derive(Clone, Debug)]
pub struct SetupTexts {
pub title: [SharedString; 2],
pub body: [SharedString; 2],
pub run: SharedString,
pub copy: SharedString,
pub copied: SharedString,
pub sign_in: SharedString,
pub waiting: SharedString,
pub pair: SharedString,
pub download: SharedString,
}
impl Default for SetupTexts {
fn default() -> Self {
Self {
title: [
"No computer connected".into(),
"This computer is off".into(),
],
body: [
"Your agents run on your computer. Start the app there first.".into(),
"Turn it back on, or connect a different computer.".into(),
],
run: "Run on your computer:".into(),
copy: "Copy command".into(),
copied: "Copied!".into(),
sign_in: "Sign in with the same account.".into(),
waiting: "Waiting for your computer\u{2026}".into(),
pair: "Add pairing link".into(),
download: "Or download the desktop app".into(),
}
}
}
#[derive(IntoElement)]
pub struct ComputerSetupSteps {
id: ElementId,
state: SetupState,
command: SharedString,
texts: SetupTexts,
on_pair: Option<Handler>,
on_download: Option<Handler>,
}
impl ComputerSetupSteps {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
state: SetupState::Waiting,
command: "npx t3@latest".into(),
texts: SetupTexts::default(),
on_pair: None,
on_download: None,
}
}
pub fn state(mut self, state: SetupState) -> Self {
self.state = state;
self
}
pub fn command(mut self, command: impl Into<SharedString>) -> Self {
self.command = command.into();
self
}
pub fn texts(mut self, texts: SetupTexts) -> Self {
self.texts = texts;
self
}
pub fn on_pair(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_pair = Some(Rc::new(f));
self
}
pub fn on_download(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_download = Some(Rc::new(f));
self
}
}
impl RenderOnce for ComputerSetupSteps {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let k = match self.state {
SetupState::Waiting => 0,
SetupState::Off => 1,
};
let (fill, ink) = (
color(ColorRole::LayerAccent01),
color(ColorRole::TextPrimary),
);
let number = |n: &'static str| bullet(fill, ink, n.into_any_element());
let step = |mark: gpui_kit::Div, content: AnyElement| {
div()
.flex()
.flex_row()
.items_start()
.gap(rem(12.))
.child(mark)
.child(div().min_w_0().child(content))
};
let command = mono(div(), 14., 400)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(rem(12.))
.mt(rem(8.))
.pl(rem(12.))
.bg(color(ColorRole::Layer01))
.child(self.command.clone())
.child(
CopyButton::new((id.clone(), "copy"), self.command.clone())
.label(self.texts.copy.clone())
.feedback(self.texts.copied.clone())
.size(32.)
.quiet(true),
);
let steps = sans(div(), 14., 400)
.flex()
.flex_col()
.gap(rem(12.))
.my(rem(8.))
.max_w_full()
.child(step(
number("1"),
div()
.flex()
.flex_col()
.child(self.texts.run.clone())
.child(command)
.into_any_element(),
))
.child(step(
number("2"),
self.texts.sign_in.clone().into_any_element(),
))
.child(step(
bullet(
gpui_kit::transparent_black(),
ink,
Spin::new((id.clone(), "wait")).into_any_element(),
),
self.texts.waiting.clone().into_any_element(),
));
sans(div(), 14., 400)
.id(id.clone())
.flex()
.flex_col()
.items_start()
.gap(rem(12.))
.max_w(rem(512.))
.py(rem(32.))
.px(rem(16.))
.text_color(color(ColorRole::TextPrimary))
.child(EnvironmentMachineIcon::new(MachineKind::Laptop).size(32.))
.child(sans(div(), 20., 400).child(self.texts.title[k].clone()))
.child(
sans(div(), 14., 400)
.text_color(color(ColorRole::TextSecondary))
.child(self.texts.body[k].clone()),
)
.child(steps)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.items_center()
.gap(rem(8.))
.child(click(
Button::new((id.clone(), "pair"), self.texts.pair.clone())
.variant(ButtonVariant::Secondary)
.size(ButtonSize::Md)
.icon(CarbonIcon::QrCode),
self.on_pair.clone(),
))
.child(click(
Button::new((id.clone(), "download"), self.texts.download.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Md)
.icon(CarbonIcon::Download),
self.on_download.clone(),
)),
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Permission {
pub label: SharedString,
pub why: SharedString,
pub granted: bool,
}
impl Permission {
pub fn new(
label: impl Into<SharedString>,
why: impl Into<SharedString>,
granted: bool,
) -> Self {
Self {
label: label.into(),
why: why.into(),
granted,
}
}
}
#[derive(Clone, Debug)]
pub struct PermissionTexts {
pub granted: SharedString,
pub open: SharedString,
}
impl Default for PermissionTexts {
fn default() -> Self {
Self {
granted: "Granted".into(),
open: "Open settings".into(),
}
}
}
#[derive(IntoElement)]
pub struct PermissionChecklist {
id: ElementId,
items: Vec<Permission>,
texts: PermissionTexts,
on_open: Option<IndexHandler>,
}
impl PermissionChecklist {
pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = Permission>) -> Self {
Self {
id: id.into(),
items: items.into_iter().collect(),
texts: PermissionTexts::default(),
on_open: None,
}
}
pub fn texts(mut self, texts: PermissionTexts) -> Self {
self.texts = texts;
self
}
pub fn on_open_settings(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_open = Some(Rc::new(f));
self
}
}
impl RenderOnce for PermissionChecklist {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let rows = self.items.iter().enumerate().map(|(i, p)| {
let (glyph, fill) = if p.granted {
(CarbonIcon::CheckmarkFilled, ColorRole::SupportSuccess)
} else {
(CarbonIcon::CircleDash, ColorRole::IconSecondary)
};
let end = if p.granted {
card_sub(self.texts.granted.clone()).into_any_element()
} else {
let f = self.on_open.clone();
Button::new(child_id(&id, "open", i), self.texts.open.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.when_some(f, |b, f| b.on_click(move |_, w, cx| f(i, w, cx)))
.into_any_element()
};
div()
.flex()
.flex_row()
.items_center()
.gap(rem(12.))
.min_h(rem(64.))
.py(rem(8.))
.px(rem(12.))
.bg(color(ColorRole::Layer01))
.child(press::icon(glyph, 20., color(fill)).flex_none())
.child(
sans(div(), 14., 400)
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(px(2.))
.text_color(color(ColorRole::TextPrimary))
.child(sans(div(), 14., 600).child(p.label.clone()))
.child(card_sub(p.why.clone())),
)
.child(end)
});
div()
.id(id.clone())
.flex()
.flex_col()
.gap(px(1.))
.w_full()
.children(rows)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToastKind {
#[default]
Error,
Success,
Info,
}
impl ToastKind {
pub const ALL: [ToastKind; 3] = [Self::Error, Self::Success, Self::Info];
pub const fn name(self) -> &'static str {
match self {
Self::Error => "error",
Self::Success => "success",
Self::Info => "info",
}
}
pub fn accent(self) -> Hsla {
color(match self {
Self::Error => ColorRole::SupportError,
Self::Success => ColorRole::SupportSuccess,
Self::Info => ColorRole::SupportInfo,
})
}
pub const fn glyph(self) -> CarbonIcon {
match self {
Self::Error => CarbonIcon::ErrorFilled,
Self::Success => CarbonIcon::CheckmarkFilled,
Self::Info => CarbonIcon::InformationFilled,
}
}
}
#[derive(Clone, Debug)]
pub struct ExpandableToastTexts {
pub show: SharedString,
pub hide: SharedString,
pub copy: SharedString,
pub close: SharedString,
}
impl Default for ExpandableToastTexts {
fn default() -> Self {
Self {
show: "Show details".into(),
hide: "Hide details".into(),
copy: "Copy error".into(),
close: "Close".into(),
}
}
}
#[derive(IntoElement)]
pub struct ExpandableToast {
id: ElementId,
kind: ToastKind,
title: SharedString,
description: Option<SharedString>,
details: Option<SharedString>,
texts: ExpandableToastTexts,
on_close: Option<Handler>,
}
impl ExpandableToast {
pub fn new(id: impl Into<ElementId>, kind: ToastKind, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
kind,
title: title.into(),
description: None,
details: None,
texts: ExpandableToastTexts::default(),
on_close: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn details(mut self, details: impl Into<SharedString>) -> Self {
self.details = Some(details.into());
self
}
pub fn texts(mut self, texts: ExpandableToastTexts) -> Self {
self.texts = texts;
self
}
pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_close = Some(Rc::new(f));
self
}
}
impl RenderOnce for ExpandableToast {
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, |_, _| false);
let open = *open_state.read(cx);
let accent = self.kind.accent();
let link = self.details.clone().map(|_| {
let link_id = ElementId::from((id.clone(), "details-link"));
let (hovered, hover) = press::hover((link_id.clone(), "hover"), window, cx);
let (focus, ring) = press::focus((link_id.clone(), "focus"), window, cx);
let label = if open {
self.texts.hide.clone()
} else {
self.texts.show.clone()
};
sans(
gpui_kit::base::Button::new(link_id)
.track_focus(&focus)
.accessibility_label(label.clone()),
12.,
400,
)
.relative()
.self_start()
.text_color(color(ColorRole::LinkPrimary))
.when(hovered, |this| this.underline())
.cursor(CursorStyle::PointingHand)
.on_hover(press::track_hover(hover))
.on_click(move |_, _, cx| {
open_state.update(cx, |o, cx| {
*o = !*o;
cx.notify();
})
})
.child(label)
.when(ring, |this| this.child(press::ring()))
});
let details = self.details.clone().filter(|_| open).map(|d| {
crate::components::ScrollArea::new((id.clone(), "pre"))
.max_h(rem(128.))
.bg(color(ColorRole::Layer02))
.child(
mono(div(), 12., 400)
.p(rem(8.))
.text_color(color(ColorRole::TextPrimary))
.children(d.split('\n').map(|l| {
div().child(SharedString::from(if l.is_empty() {
" ".to_string()
} else {
l.to_string()
}))
})),
)
});
let copy = self.details.clone().map(|d| {
icon_button(
(id.clone(), "copy"),
self.texts.copy.clone(),
CarbonIcon::Copy,
)
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(d.to_string()))
})
});
let on_close = self.on_close.clone();
let mut shadows = crate::components::overlay::floating_shadow();
shadows.push(gpui_kit::BoxShadow::new(px(3.), px(0.), accent).inset());
div()
.id(id.clone())
.relative()
.flex()
.flex_row()
.items_start()
.gap(rem(12.))
.w(rem(384.))
.max_w_full()
.py(rem(12.))
.pl(rem(12.))
.pr(rem(4.))
.bg(color(ColorRole::Layer01))
.shadow(shadows)
.child(press::icon(self.kind.glyph(), 20., accent).flex_none())
.child(
sans(div(), 14., 400)
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(rem(4.))
.text_color(color(ColorRole::TextPrimary))
.child(sans(div(), 14., 600).child(self.title.clone()))
.when_some(self.description.clone(), |this, d| {
this.child(div().text_color(color(ColorRole::TextSecondary)).child(d))
})
.children(link)
.children(details),
)
.child(
div()
.flex()
.flex_row()
.flex_none()
.children(copy)
.child(click(
icon_button(
(id.clone(), "close"),
self.texts.close.clone(),
CarbonIcon::Close,
),
on_close,
)),
)
}
}
pub fn middle_truncate(text: &str, keep: usize) -> Option<String> {
let chars: Vec<char> = text.chars().collect();
if chars.len() <= keep * 2 + 1 {
return None;
}
let head: String = chars[..keep].iter().collect();
let tail: String = chars[chars.len() - keep..].iter().collect();
Some(format!("{head}\u{2026}{tail}"))
}
#[derive(IntoElement, Clone, Debug)]
pub struct MiddleTruncate {
id: ElementId,
text: SharedString,
keep: usize,
}
impl MiddleTruncate {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
keep: 8,
}
}
pub fn keep(mut self, keep: usize) -> Self {
self.keep = keep;
self
}
}
impl RenderOnce for MiddleTruncate {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
match middle_truncate(&self.text, self.keep) {
None => div().id(self.id).child(self.text),
Some(short) => mono(div(), 12., 400)
.id(self.id)
.tooltip(title_tooltip(self.text.clone()))
.child(short),
}
}
}
pub fn relative_label(secs: f64) -> String {
let round = |x: f64| (x + 0.5).floor() as i64;
if secs < 45. {
"now".into()
} else if secs < 3600. {
format!("{}m", round(secs / 60.))
} else if secs < 86400. {
format!("{}h", round(secs / 3600.))
} else {
format!("{}d", round(secs / 86400.))
}
}
pub fn locale_string(date: SystemTime) -> String {
let t: chrono::DateTime<chrono::Local> = date.into();
t.format("%-m/%-d/%Y, %-I:%M:%S %p").to_string()
}
#[derive(IntoElement, Clone, Debug)]
pub struct RelativeTime {
id: ElementId,
date: SystemTime,
}
impl RelativeTime {
pub fn new(id: impl Into<ElementId>, date: SystemTime) -> Self {
Self {
id: id.into(),
date,
}
}
}
impl RenderOnce for RelativeTime {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let age = SystemTime::now()
.duration_since(self.date)
.unwrap_or(Duration::ZERO)
.as_secs_f64();
sans(div(), 12., 400)
.id(self.id)
.text_color(color(ColorRole::TextHelper))
.tooltip(title_tooltip(locale_string(self.date).into()))
.child(relative_label(age))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn middle_truncate_keeps_both_ends() {
assert_eq!(
middle_truncate("sha256:9f2c1e0a7b4d5e6f8a9b0c1d2e3f4a5b", 10).as_deref(),
Some("sha256:9f2\u{2026}1d2e3f4a5b")
);
assert_eq!(middle_truncate("short", 8), None);
assert_eq!(middle_truncate("abcdefghi", 4), None);
assert_eq!(
middle_truncate("abcdefghij", 4).as_deref(),
Some("abcd\u{2026}ghij")
);
}
#[test]
fn relative_labels_round_to_the_unit() {
assert_eq!(relative_label(10.), "now");
assert_eq!(relative_label(44.9), "now");
assert_eq!(relative_label(45.), "1m");
assert_eq!(relative_label(180.), "3m");
assert_eq!(relative_label(7200.), "2h");
assert_eq!(relative_label(86400. * 5.), "5d");
}
#[test]
fn toast_accents_follow_the_kind() {
assert_eq!(ToastKind::Error.accent(), color(ColorRole::SupportError));
assert_eq!(ToastKind::Info.glyph(), CarbonIcon::InformationFilled);
}
}