use crate::{
density::Density,
icons::{CarbonIcon, Icon, IconSize},
theme::color,
tokens::{self, ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, Div, Hsla, IntoElement, ParentElement, Rems, SharedString, Styled, div,
prelude::FluentBuilder as _, px,
};
pub(crate) fn rem(px_value: f32) -> Rems {
gpui_kit::rems(px_value / tokens::REM_PX)
}
pub(crate) fn controlled<T: Clone + 'static>(
id: impl Into<gpui_kit::ElementId>,
value: Option<T>,
default: T,
window: &mut gpui_kit::Window,
cx: &mut gpui_kit::App,
) -> (T, gpui_kit::Entity<T>) {
let store = window.use_keyed_state(id, cx, |_, _| default);
let shown = value.unwrap_or_else(|| store.read(cx).clone());
(shown, store)
}
thread_local! {
static LAST_KEY_TAB: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static KEEP_CARET: std::cell::RefCell<std::collections::HashSet<gpui_kit::EntityId>> =
std::cell::RefCell::new(std::collections::HashSet::new());
}
pub(crate) fn init(cx: &mut gpui_kit::App) {
use gpui_kit::component::input::{InputEvent, InputState};
cx.intercept_keystrokes(|event, _, _| {
LAST_KEY_TAB.with(|t| t.set(event.keystroke.key == "tab"));
})
.detach();
cx.observe_new(|_: &mut InputState, _, cx| {
let state = cx.entity();
let app: &mut gpui_kit::App = cx;
app.subscribe(&state, |state, event: &InputEvent, cx| {
if !matches!(event, InputEvent::Focus)
|| KEEP_CARET.with(|k| k.borrow().contains(&state.entity_id()))
{
return;
}
cx.with_window(state.entity_id(), |window, cx| {
if tab_moved_focus(window) {
state.update(cx, |s, cx| s.select_all(window, cx));
}
});
})
.detach();
})
.detach();
}
fn tab_moved_focus(window: &gpui_kit::Window) -> bool {
window.last_input_was_keyboard() && LAST_KEY_TAB.with(|t| t.get())
}
pub fn keep_caret_on_tab_in(state: &gpui_kit::Entity<gpui_kit::component::input::InputState>) {
KEEP_CARET.with(|k| k.borrow_mut().insert(state.entity_id()));
}
pub fn select_all_on_tab_in(
_state: &gpui_kit::Entity<gpui_kit::component::input::InputState>,
_window: &mut gpui_kit::Window,
_cx: &mut gpui_kit::App,
) {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FieldSize {
Sm,
#[default]
Md,
Lg,
}
impl FieldSize {
pub const ALL: [FieldSize; 3] = [Self::Sm, Self::Md, Self::Lg];
pub const fn name(self) -> &'static str {
match self {
Self::Sm => "sm",
Self::Md => "md",
Self::Lg => "lg",
}
}
pub const fn carbon_height(self) -> f32 {
match self {
Self::Sm => tokens::SIZE_SM.px_value(),
Self::Md => tokens::SIZE_MD.px_value(),
Self::Lg => tokens::SIZE_LG.px_value(),
}
}
pub const fn height(self, density: Density) -> f32 {
match density {
Density::Compact => tokens::DENSITY_FIELD_MD.px_value(),
Density::Comfortable => self.carbon_height(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Validation {
#[default]
None,
Invalid(SharedString),
Warn(SharedString),
}
impl Validation {
pub fn from_flags(
invalid: bool,
invalid_text: Option<SharedString>,
warn: bool,
warn_text: Option<SharedString>,
) -> Self {
if invalid {
Self::Invalid(invalid_text.unwrap_or_default())
} else if warn {
Self::Warn(warn_text.unwrap_or_default())
} else {
Self::None
}
}
pub fn is_invalid(&self) -> bool {
matches!(self, Self::Invalid(_))
}
pub fn has_icon(&self) -> bool {
!matches!(self, Self::None)
}
pub fn message(&self) -> Option<&SharedString> {
match self {
Self::None => None,
Self::Invalid(text) | Self::Warn(text) => Some(text).filter(|t| !t.is_empty()),
}
}
pub fn message_color(&self) -> Hsla {
color(if self.is_invalid() {
ColorRole::TextError
} else {
ColorRole::TextPrimary
})
}
}
pub fn label(text: impl Into<SharedString>, disabled: bool) -> Div {
div()
.type_style(TypeStyle::Label01)
.text_color(label_color(disabled))
.mb(tokens::SPACING_03)
.child(text.into())
}
pub fn label_color(disabled: bool) -> Hsla {
color(if disabled {
ColorRole::TextDisabled
} else {
ColorRole::TextSecondary
})
}
pub fn helper_text(text: impl Into<SharedString>, disabled: bool) -> Div {
div()
.w_full()
.type_style(TypeStyle::HelperText01)
.text_color(color(if disabled {
ColorRole::TextDisabled
} else {
ColorRole::TextHelper
}))
.mt(tokens::SPACING_02)
.child(text.into())
}
pub fn requirement(validation: &Validation) -> Option<Div> {
validation.message().map(|text| {
div()
.w_full()
.type_style(TypeStyle::HelperText01)
.text_color(validation.message_color())
.mt(tokens::SPACING_02)
.child(text.clone())
})
}
pub fn message(
validation: &Validation,
helper: Option<&SharedString>,
disabled: bool,
) -> Option<AnyElement> {
if !disabled && let Some(requirement) = requirement(validation) {
return Some(requirement.into_any_element());
}
helper.map(|text| helper_text(text.clone(), disabled).into_any_element())
}
pub fn status_icon(validation: &Validation) -> Option<AnyElement> {
match validation {
Validation::None => None,
Validation::Invalid(_) => Some(
Icon::carbon(CarbonIcon::WarningFilled)
.size(IconSize::S16)
.color(color(ColorRole::SupportError))
.into_any_element(),
),
Validation::Warn(_) => Some(
div()
.relative()
.size(rem(16.))
.flex_shrink_0()
.child(
div()
.absolute()
.left(rem(7.))
.top(rem(6.))
.w(rem(2.))
.h(rem(7.5))
.bg(gpui_kit::black()),
)
.child(
Icon::carbon(CarbonIcon::WarningAltFilled)
.size(IconSize::S16)
.color(color(ColorRole::SupportWarning))
.absolute()
.top_0()
.left_0(),
)
.into_any_element(),
),
}
}
pub const FIELD_RULE: f32 = 1.;
pub fn bottom_rule(rule: Hsla) -> Div {
div()
.absolute()
.left_0()
.right_0()
.bottom_0()
.h(px(FIELD_RULE))
.bg(rule)
}
pub fn inset_outline(width: f32, outline: Hsla) -> Div {
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.border(px(width))
.border_color(outline)
}
pub fn field_outline(focused: bool, validation: &Validation) -> Option<Hsla> {
if focused {
Some(color(ColorRole::Focus))
} else if validation.is_invalid() {
Some(color(ColorRole::SupportError))
} else {
None
}
}
pub fn form_item() -> Div {
let item = div().flex().flex_col().w_full().min_w_0();
if super::direction::is_rtl() {
item.items_end().text_right()
} else {
item.items_start()
}
}
pub fn flex_form_item(content: impl IntoElement) -> Div {
div()
.flex()
.flex_col()
.items_start()
.flex_auto()
.child(content)
}
pub fn labeled(
label_text: Option<&SharedString>,
disabled: bool,
control: impl IntoElement,
message_row: Option<AnyElement>,
) -> Div {
form_item()
.when_some(label_text.filter(|l| !l.is_empty()), |this, text| {
this.child(label(text.clone(), disabled))
})
.child(control)
.children(message_row)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn flex_form_item_grows_like_cds_form_item() {
let mut item = flex_form_item(div());
let style = item.style();
assert_eq!(style.flex_grow, Some(1.));
assert_eq!(style.flex_shrink, Some(1.));
assert_eq!(style.flex_basis, Some(gpui_kit::Length::Auto));
assert_eq!(style.flex_direction, Some(gpui_kit::FlexDirection::Column));
assert_eq!(style.align_items, Some(gpui_kit::AlignItems::FlexStart));
}
#[test]
fn field_heights_follow_layout_size_and_density() {
let heights = FieldSize::ALL.map(|s| s.height(Density::Comfortable));
assert_eq!(heights, [32., 40., 48.]);
let compact = FieldSize::ALL.map(|s| s.height(Density::Compact));
assert_eq!(compact, [32., 32., 32.]);
}
#[test]
fn validation_colors_follow_form_requirement() {
crate::theme::tests_set(CarbonTheme::White);
let invalid = Validation::from_flags(true, Some("Bad".into()), true, None);
assert!(invalid.is_invalid());
assert_eq!(hex(invalid.message_color()), "#da1e28");
let warn = Validation::from_flags(false, None, true, Some("Hm".into()));
assert_eq!(hex(warn.message_color()), "#161616");
assert_eq!(warn.message().map(|s| s.as_ref()), Some("Hm"));
assert_eq!(Validation::None.message(), None);
assert_eq!(hex(label_color(false)), "#525252");
assert!(label_color(true).a < 1.);
}
#[test]
fn outline_prefers_focus_over_invalid() {
crate::theme::tests_set(CarbonTheme::White);
let invalid = Validation::Invalid("x".into());
assert_eq!(
field_outline(true, &invalid).map(hex).as_deref(),
Some("#0f62fe")
);
assert_eq!(
field_outline(false, &invalid).map(hex).as_deref(),
Some("#da1e28")
);
assert_eq!(field_outline(false, &Validation::Warn("w".into())), None);
}
}