mod options;
pub use options::{
ApprovalOption, PermissionOptionKind, approval_head_icon, default_option, escape_option,
option_tooltip,
};
use super::card;
use crate::components::badge::{Badge, BadgeSize, BadgeVariant};
use crate::components::button::{Button, ButtonKind, ButtonSize, ButtonVariant};
use crate::t3::action::{ActionButton, ActionKind, KeyCap, Part};
use crate::t3::press::{self, Handler, rem};
use crate::{
icons::{CarbonIcon, Icon},
theme::color,
tokens::{ColorRole, FontFamilyKey},
typography::font,
};
use gpui_kit::{
AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _,
};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ApprovalKind {
#[default]
Command,
File,
Read,
Permission,
Access,
}
impl ApprovalKind {
pub const ALL: [ApprovalKind; 5] = [
Self::Command,
Self::File,
Self::Read,
Self::Permission,
Self::Access,
];
pub const fn name(self) -> &'static str {
match self {
Self::Command => "command",
Self::File => "file",
Self::Read => "read",
Self::Permission => "permission",
Self::Access => "access",
}
}
pub const fn default_title(self) -> &'static str {
match self {
Self::Command => "Command approval",
Self::File => "File change approval",
Self::Read => "File read approval",
Self::Permission => "App permission approval",
Self::Access => "App access approval",
}
}
pub const fn default_label(self) -> &'static str {
match self {
Self::Command => "Command",
Self::File => "File change",
Self::Read => "File to read",
Self::Permission => "Permission request",
Self::Access => "App access request",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ApprovalState {
#[default]
Pending,
Approved,
Declined,
}
impl ApprovalState {
pub const ALL: [ApprovalState; 3] = [Self::Pending, Self::Approved, Self::Declined];
pub const fn name(self) -> &'static str {
match self {
Self::Pending => "pending",
Self::Approved => "approved",
Self::Declined => "declined",
}
}
}
pub fn approval_look(state: ApprovalState, destructive: bool) -> (Hsla, Hsla, CarbonIcon) {
match state {
ApprovalState::Approved => (
color(ColorRole::SupportSuccess),
color(ColorRole::SupportSuccess),
CarbonIcon::CheckmarkFilled,
),
ApprovalState::Declined => (
color(ColorRole::BorderStrong01),
color(ColorRole::IconSecondary),
CarbonIcon::ErrorFilled,
),
ApprovalState::Pending if destructive => (
color(ColorRole::SupportWarning),
color(ColorRole::SupportError),
CarbonIcon::ErrorFilled,
),
ApprovalState::Pending => (
color(ColorRole::SupportWarning),
color(ColorRole::SupportWarning),
CarbonIcon::WarningAltFilled,
),
}
}
#[derive(Clone)]
pub struct ApprovalTexts {
pub approved: SharedString,
pub declined: SharedString,
pub decline: SharedString,
pub approve: SharedString,
pub always: SharedString,
pub return_key: SharedString,
pub escape_key: SharedString,
}
impl Default for ApprovalTexts {
fn default() -> Self {
Self {
approved: "Approved".into(),
declined: "Declined".into(),
decline: "Decline".into(),
approve: "Approve".into(),
always: "Always allow this session".into(),
return_key: "Return".into(),
escape_key: "Esc".into(),
}
}
}
pub fn approval_shortcut(key: &str, shift: bool, command: bool) -> Option<bool> {
if !shift || !command {
return None;
}
match key {
"enter" => Some(true),
"backspace" => Some(false),
_ => None,
}
}
#[derive(IntoElement)]
pub struct ApprovalCard {
id: ElementId,
kind: ApprovalKind,
title: Option<SharedString>,
detail: SharedString,
reason: Option<SharedString>,
provider: Option<SharedString>,
context: Option<SharedString>,
always_hint: Option<SharedString>,
always_label: Option<Option<SharedString>>,
approve_label: Option<SharedString>,
state: ApprovalState,
shortcuts: bool,
destructive: bool,
texts: ApprovalTexts,
on_approve: Option<Handler>,
on_decline: Option<Handler>,
on_always: Option<Handler>,
options: Option<Vec<ApprovalOption>>,
tool: bool,
facts: Vec<(SharedString, SharedString)>,
plan: Option<AnyElement>,
extras: Vec<options::Extra>,
note: Option<SharedString>,
editor: Option<AnyElement>,
answer: Option<options::Answer>,
show_kinds: bool,
on_pick: Option<options::PickHandler>,
}
impl ApprovalCard {
pub fn new(
id: impl Into<ElementId>,
kind: ApprovalKind,
detail: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
kind,
title: None,
detail: detail.into(),
reason: None,
provider: None,
context: None,
always_hint: None,
always_label: None,
approve_label: None,
state: ApprovalState::Pending,
shortcuts: false,
destructive: false,
texts: ApprovalTexts::default(),
on_approve: None,
on_decline: None,
on_always: None,
options: None,
tool: false,
facts: Vec::new(),
plan: None,
extras: Vec::new(),
note: None,
editor: None,
answer: None,
show_kinds: false,
on_pick: None,
}
}
pub fn options(id: impl Into<ElementId>, options: Vec<ApprovalOption>) -> Self {
let mut card = Self::new(id, ApprovalKind::Command, "");
card.options = Some(options);
card
}
pub fn kind(mut self, kind: ApprovalKind) -> Self {
self.kind = kind;
self
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = detail.into();
self
}
pub fn tool(mut self, tool: bool) -> Self {
self.tool = tool;
self
}
pub fn facts<L: Into<SharedString>, V: Into<SharedString>>(
mut self,
facts: impl IntoIterator<Item = (L, V)>,
) -> Self {
self.facts = facts
.into_iter()
.map(|(l, v)| (l.into(), v.into()))
.collect();
self
}
pub fn plan(mut self, plan: impl IntoElement) -> Self {
self.plan = Some(plan.into_any_element());
self
}
pub fn extra_action(
mut self,
label: impl Into<SharedString>,
icon: impl Into<Icon>,
f: impl Fn(&mut Window, &mut App) + 'static,
) -> Self {
self.extras.push(options::Extra {
label: label.into(),
icon: icon.into(),
on_click: Rc::new(f),
});
self
}
pub fn note(mut self, note: impl Into<SharedString>) -> Self {
self.note = Some(note.into());
self
}
pub fn editor(mut self, editor: impl IntoElement) -> Self {
self.editor = Some(editor.into_any_element());
self
}
pub fn answered(
mut self,
allowed: bool,
spoken: impl Into<SharedString>,
tail: impl Into<SharedString>,
) -> Self {
self.answer = Some(options::Answer {
allowed,
spoken: spoken.into(),
tail: tail.into(),
});
self
}
pub fn show_kinds(mut self, show: bool) -> Self {
self.show_kinds = show;
self
}
pub fn on_pick(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_pick = Some(Rc::new(f));
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn reason(mut self, reason: impl Into<SharedString>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn provider(mut self, provider: impl Into<SharedString>) -> Self {
self.provider = Some(provider.into());
self
}
pub fn context(mut self, context: impl Into<SharedString>) -> Self {
self.context = Some(context.into());
self
}
pub fn always_hint(mut self, hint: impl Into<SharedString>) -> Self {
self.always_hint = Some(hint.into());
self
}
pub fn always_label(mut self, label: Option<SharedString>) -> Self {
self.always_label = Some(label);
self
}
pub fn approve_label(mut self, label: impl Into<SharedString>) -> Self {
self.approve_label = Some(label.into());
self
}
pub fn state(mut self, state: ApprovalState) -> Self {
self.state = state;
self
}
pub fn shortcuts(mut self, shortcuts: bool) -> Self {
self.shortcuts = shortcuts;
self
}
pub fn destructive(mut self, destructive: bool) -> Self {
self.destructive = destructive;
self
}
pub fn texts(mut self, texts: ApprovalTexts) -> Self {
self.texts = texts;
self
}
pub fn on_approve(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_approve = Some(Rc::new(f));
self
}
pub fn on_decline(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_decline = Some(Rc::new(f));
self
}
pub fn on_always(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_always = Some(Rc::new(f));
self
}
}
impl RenderOnce for ApprovalCard {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
if self.options.is_some() {
return self.render_options(window, cx);
}
let id = self.id.clone();
let pending = self.state == ApprovalState::Pending;
let shortcuts = self.shortcuts && !self.destructive && pending;
let (rail, icon_ink, icon) = approval_look(self.state, self.destructive);
let (focus, ring) = press::focus((id.clone(), "focus"), window, cx);
let head_text = self
.title
.clone()
.unwrap_or_else(|| self.kind.default_title().into());
let texts = self.texts.clone();
let head = card::head()
.child(if icon == CarbonIcon::WarningAltFilled {
crate::t3::base::warning_glyph(16.).into_any_element()
} else {
card::head_icon(icon, icon_ink)
})
.child(card::head_title(head_text.clone()))
.when_some(self.provider.clone(), |this, p| this.child(card::sub(p)))
.child(card::grow())
.when(!pending, |this| {
let approved = self.state == ApprovalState::Approved;
this.child(
Badge::new(if approved {
texts.approved.clone()
} else {
texts.declined.clone()
})
.size(BadgeSize::Sm)
.variant(if approved {
BadgeVariant::Green
} else {
BadgeVariant::Gray
}),
)
});
let mut body = Vec::new();
if pending {
body.push(card::label(self.kind.default_label()).into_any_element());
body.push(
div()
.id((id.clone(), "detail"))
.p(rem(12.))
.max_h(rem(160.))
.overflow_y_scroll()
.bg(color(ColorRole::Layer02))
.font(font(FontFamilyKey::Mono, 400))
.text_size(rem(12.))
.line_height(rem(16.))
.child(self.detail.clone())
.into_any_element(),
);
if let Some(context) = self.context.clone() {
body.push(
card::note(context)
.text_size(rem(12.))
.line_height(rem(16.))
.into_any_element(),
);
}
if let Some(reason) = self.reason.clone() {
body.push(card::note(reason).into_any_element());
}
if let Some(hint) = self.always_hint.clone() {
body.push(
card::note(hint)
.text_size(rem(12.))
.line_height(rem(16.))
.text_color(color(ColorRole::TextHelper))
.into_any_element(),
);
}
let always = match self.always_label.clone() {
Some(None) => None,
Some(Some(label)) => Some(label),
None => Some(texts.always.clone()),
};
let on_always = self.on_always.clone();
let decline = ActionButton::new(
(id.clone(), "decline"),
texts.decline.clone(),
ActionKind::NeutralOutline,
)
.part(Part::Text(texts.decline.clone()))
.when(shortcuts, |b| {
b.part(Part::Key("⇧⌘⌫".into(), KeyCap::Framed))
})
.when(shortcuts, |b| b.tooltip(format!("{} (⇧⌘⌫)", texts.decline)))
.on_click(self.on_decline.clone());
let approve_label = self
.approve_label
.clone()
.unwrap_or_else(|| texts.approve.clone());
let approve = ActionButton::new(
(id.clone(), "approve"),
approve_label.clone(),
ActionKind::Carbon(if self.destructive {
ButtonKind::Danger
} else {
ButtonKind::Primary
}),
)
.part(Part::Text(approve_label.clone()))
.when(shortcuts, |b| {
b.part(Part::Key("⇧⌘↵".into(), KeyCap::Framed))
})
.when(shortcuts, |b| b.tooltip(format!("{approve_label} (⇧⌘↵)")))
.on_click(self.on_approve.clone());
body.push(
card::actions()
.when_some(always, |this, label| {
this.child(
div().ml(rem(-16.)).child(
Button::new((id.clone(), "always"), label)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.when_some(on_always, |b, f| {
b.on_click(move |_, w, cx| f(w, cx))
}),
),
)
})
.child(card::grow())
.child(decline)
.child(approve)
.into_any_element(),
);
}
let on_approve = self.on_approve.clone();
let on_decline = self.on_decline.clone();
card::framed(Some(rail))
.id(id.clone())
.when(!pending, |this| this.gap_0().py(rem(12.)))
.when(pending, |this| {
this.track_focus(&focus.tab_index(0).tab_stop(true))
.on_key_down(move |e: &KeyDownEvent, window, cx| {
if !shortcuts {
return;
}
let m = &e.keystroke.modifiers;
match approval_shortcut(&e.keystroke.key, m.shift, m.platform || m.control)
{
Some(true) => {
cx.stop_propagation();
if let Some(f) = on_approve.as_ref() {
f(window, cx)
}
}
Some(false) => {
cx.stop_propagation();
if let Some(f) = on_decline.as_ref() {
f(window, cx)
}
}
None => {}
}
})
})
.child(head)
.children(body)
.when(ring && pending, |this| this.child(press::ring()))
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
#[test]
fn rails_follow_the_state() {
crate::theme::tests_set(CarbonTheme::White);
let (rail, icon, glyph) = approval_look(ApprovalState::Pending, false);
assert_eq!(rail, color(ColorRole::SupportWarning));
assert_eq!(icon, color(ColorRole::SupportWarning));
assert_eq!(glyph, CarbonIcon::WarningAltFilled);
let (rail, icon, _) = approval_look(ApprovalState::Declined, false);
assert_eq!(rail, color(ColorRole::BorderStrong01));
assert_eq!(icon, color(ColorRole::IconSecondary));
let (_, icon, glyph) = approval_look(ApprovalState::Pending, true);
assert_eq!(icon, color(ColorRole::SupportError));
assert_eq!(glyph, CarbonIcon::ErrorFilled);
}
#[test]
fn shortcuts_need_shift_and_command() {
assert_eq!(approval_shortcut("enter", true, true), Some(true));
assert_eq!(approval_shortcut("backspace", true, true), Some(false));
assert_eq!(approval_shortcut("enter", false, true), None);
assert_eq!(approval_shortcut("enter", true, false), None);
assert_eq!(approval_shortcut("a", true, true), None);
assert_eq!(ApprovalKind::Read.default_label(), "File to read");
}
}