use crate::{
components::{
button::{Button, ButtonSize, ButtonVariant},
overlay::floating_shadow,
},
icons::{CarbonIcon, Icon},
theme::color,
tokens::{self, ColorRole, REM_PX, TokenLength, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
SharedString, Styled, Window, div, prelude::FluentBuilder as _, px, rems,
};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameGeometry {
pub head_top: TokenLength,
pub head_end: TokenLength,
pub head_start: TokenLength,
pub label_gap: TokenLength,
pub body_pad: TokenLength,
pub body_bottom: TokenLength,
pub danger_rule: f32,
pub default_width: f32,
}
impl FrameGeometry {
pub const REFERENCE: Self = Self {
head_top: tokens::SPACING_05,
head_end: tokens::SIZE_LG,
head_start: tokens::SPACING_05,
label_gap: tokens::SPACING_01,
body_pad: tokens::SPACING_05,
body_bottom: tokens::SPACING_07,
danger_rule: 3.,
default_width: 340.,
};
}
#[derive(Clone)]
pub struct FrameButton {
label: SharedString,
variant: ButtonVariant,
weight: f32,
disabled: bool,
icon: Option<Icon>,
}
impl FrameButton {
pub fn new(label: impl Into<SharedString>, variant: ButtonVariant) -> Self {
Self {
label: label.into(),
variant,
weight: 1.,
disabled: false,
icon: None,
}
}
pub fn weight(mut self, weight: f32) -> Self {
self.weight = weight;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[deprecated(note = "ignores each button's padding; use `foot_widths`")]
pub fn foot_shares(lead: f32, weights: &[f32]) -> Vec<f32> {
let total: f32 = lead.max(0.) + weights.iter().sum::<f32>();
if total <= 0. {
return Vec::new();
}
std::iter::once(lead)
.filter(|l| *l > 0.)
.chain(weights.iter().copied())
.map(|w| w / total)
.collect()
}
pub fn foot_widths(width: f32, lead: f32, buttons: &[(f32, f32)]) -> Vec<f32> {
let lead = (lead > 0.).then_some((lead, 0.));
let slots: Vec<(f32, f32)> = lead.into_iter().chain(buttons.iter().copied()).collect();
let weights: f32 = slots.iter().map(|(w, _)| w).sum();
if weights <= 0. {
return Vec::new();
}
let free = (width - slots.iter().map(|(_, b)| b).sum::<f32>()).max(0.);
slots
.iter()
.map(|(w, basis)| basis + free * w / weights)
.collect()
}
type ButtonHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct PatternFrame {
id: ElementId,
label: Option<SharedString>,
title: SharedString,
close_label: SharedString,
danger: bool,
width: Option<f32>,
lead: f32,
buttons: Vec<FrameButton>,
children: Vec<AnyElement>,
on_button: Option<ButtonHandler>,
on_close: Option<CloseHandler>,
}
impl PatternFrame {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: None,
title: SharedString::default(),
close_label: SharedString::default(),
danger: false,
width: Some(FrameGeometry::REFERENCE.default_width),
lead: 0.,
buttons: Vec::new(),
children: Vec::new(),
on_button: None,
on_close: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = title.into();
self
}
pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
self.close_label = label.into();
self
}
pub fn danger(mut self, danger: bool) -> Self {
self.danger = danger;
self
}
pub fn width(mut self, width: Option<f32>) -> Self {
self.width = width;
self
}
pub fn lead_gap(mut self, weight: f32) -> Self {
self.lead = weight;
self
}
pub fn button(mut self, button: FrameButton) -> Self {
self.buttons.push(button);
self
}
pub fn on_button(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_button = Some(Rc::new(f));
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 ParentElement for PatternFrame {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for PatternFrame {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let g = FrameGeometry::REFERENCE;
let id = self.id;
let close = {
let on_close = self.on_close.clone();
Button::new((id.clone(), "close"), self.close_label.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Lg)
.icon_only(true)
.icon(Icon::carbon(CarbonIcon::Close))
.on_click(move |_, window, cx| {
if let Some(f) = &on_close {
f(window, cx)
}
})
};
let head = div()
.relative()
.flex()
.flex_col()
.pt(g.head_top)
.pr(g.head_end)
.pl(g.head_start)
.when_some(self.label, |this, label| {
this.child(
div()
.mb(g.label_gap)
.type_style(TypeStyle::Label01)
.text_color(color(ColorRole::TextSecondary))
.child(label),
)
})
.child(
div()
.type_style(TypeStyle::Heading03)
.text_color(color(ColorRole::TextPrimary))
.child(self.title),
)
.child(div().absolute().top_0().right_0().child(close));
let body = div()
.flex()
.flex_col()
.pt(g.body_pad)
.px(g.body_pad)
.pb(g.body_bottom)
.type_style(TypeStyle::Body01)
.text_color(color(ColorRole::TextPrimary))
.children(self.children);
let foot = (!self.buttons.is_empty()).then(|| {
let buttons = self.buttons.into_iter().enumerate().map(|(i, b)| {
let on_button = self.on_button.clone();
let mut button = Button::new((id.clone(), format!("b{i}")), b.label)
.variant(b.variant)
.size(ButtonSize::Xl)
.flex_share(b.weight)
.disabled(b.disabled)
.on_click(move |_, window, cx| {
if let Some(f) = &on_button {
f(i, window, cx)
}
});
if let Some(icon) = b.icon {
button = button.icon(icon);
}
button
});
div()
.flex()
.flex_row()
.w_full()
.when(self.lead > 0., |this| {
this.child(
div()
.min_w_0()
.flex_grow(self.lead)
.flex_shrink(1.)
.flex_basis(px(0.)),
)
})
.children(buttons)
});
div()
.id(id.clone())
.flex()
.flex_col()
.max_w_full()
.map(|this| match self.width {
Some(w) => this.w(rems(w / REM_PX)),
None => this.w_full(),
})
.bg(color(ColorRole::Layer01))
.shadow(floating_shadow())
.when(self.danger, |this| {
this.border_t(gpui_kit::px(g.danger_rule))
.border_color(color(ColorRole::SupportError))
})
.child(head)
.child(body)
.children(foot)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn geometry_matches_the_css() {
let g = FrameGeometry::REFERENCE;
assert_eq!(
(
g.head_top.px_value(),
g.head_end.px_value(),
g.head_start.px_value()
),
(16., 48., 16.)
);
assert_eq!(g.label_gap.px_value(), 2.);
assert_eq!(
(g.body_pad.px_value(), g.body_bottom.px_value()),
(16., 32.)
);
assert_eq!((g.danger_rule, g.default_width), (3., 340.));
}
#[test]
fn button_counts_take_their_dialog_widths() {
use crate::components::button::{ButtonKind, Geometry};
use crate::density::Density;
let basis = |kind| {
Geometry::for_content(ButtonSize::Xl, Density::Compact, kind, false, false).flex_basis()
};
let (ghost, filled) = (basis(ButtonKind::Ghost), basis(ButtonKind::Primary));
assert_eq!((ghost, filled), (32., 33.));
assert_eq!(foot_widths(340., 0., &[(1., filled); 2]), vec![170.; 2]);
assert_eq!(foot_widths(340., 1., &[(1., filled)]), vec![153.5, 186.5]);
assert_eq!(
foot_widths(420., 1., &[(1., ghost), (1., filled), (1., filled)]),
vec![80.5, 112.5, 113.5, 113.5]
);
assert!(foot_widths(340., 0., &[]).is_empty());
}
}