use super::form::{self, rem};
use crate::{
theme::color,
tokens::{self, ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
LayoutId, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window, div,
prelude::FluentBuilder as _, px,
};
use std::cell::Cell;
thread_local! {
static INVALID_DEPTH: Cell<u32> = const { Cell::new(0) };
}
pub fn in_invalid_field() -> bool {
INVALID_DEPTH.with(|d| d.get() > 0)
}
pub fn with_invalid_field<R>(invalid: bool, f: impl FnOnce() -> R) -> R {
if !invalid {
return f();
}
INVALID_DEPTH.with(|d| d.set(d.get() + 1));
struct Pop;
impl Drop for Pop {
fn drop(&mut self) {
INVALID_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
let _pop = Pop;
f()
}
pub struct FieldScope {
invalid: bool,
child: AnyElement,
}
impl Element for FieldScope {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
let child = &mut self.child;
let id = with_invalid_field(self.invalid, || child.request_layout(window, cx));
(id, ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
let child = &mut self.child;
with_invalid_field(self.invalid, || {
child.prepaint(window, cx);
});
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
let child = &mut self.child;
with_invalid_field(self.invalid, || child.paint(window, cx));
}
}
macro_rules! parent {
($name:ident) => {
impl ParentElement for $name {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
};
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FieldOrientation {
#[default]
Vertical,
Horizontal,
}
impl FieldOrientation {
pub const ALL: [Self; 2] = [Self::Vertical, Self::Horizontal];
pub const fn name(self) -> &'static str {
match self {
Self::Vertical => "vertical",
Self::Horizontal => "horizontal",
}
}
}
#[derive(IntoElement, Default)]
pub struct Field {
orientation: FieldOrientation,
invalid: bool,
children: Vec<AnyElement>,
}
impl Field {
pub fn new() -> Self {
Self::default()
}
pub fn orientation(mut self, orientation: FieldOrientation) -> Self {
self.orientation = orientation;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn is_invalid(&self) -> bool {
self.invalid
}
}
parent!(Field);
impl RenderOnce for Field {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let body = match self.orientation {
FieldOrientation::Vertical => form::form_item().children(self.children),
FieldOrientation::Horizontal => div()
.flex()
.map(|d| {
if super::direction::is_rtl() {
d.flex_row_reverse()
} else {
d.flex_row()
}
})
.items_center()
.gap(tokens::SPACING_05)
.w_full()
.children(self.children),
}
.type_style(TypeStyle::BodyCompact01);
FieldScope {
invalid: self.invalid,
child: body.into_any_element(),
}
}
}
#[derive(IntoElement)]
pub struct FieldLabel {
text: SharedString,
disabled: bool,
no_margin: bool,
}
impl FieldLabel {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: text.into(),
disabled: false,
no_margin: false,
}
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn no_margin(mut self, no_margin: bool) -> Self {
self.no_margin = no_margin;
self
}
}
impl RenderOnce for FieldLabel {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
form::label(self.text, self.disabled).when(self.no_margin, |this| this.mb_0())
}
}
#[derive(IntoElement)]
pub struct FieldDescription {
text: SharedString,
disabled: bool,
}
impl FieldDescription {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: text.into(),
disabled: false,
}
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl RenderOnce for FieldDescription {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
form::helper_text(self.text, self.disabled)
}
}
#[derive(IntoElement, Default)]
pub struct FieldError {
text: Option<SharedString>,
errors: Vec<SharedString>,
}
impl FieldError {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: Some(text.into()),
errors: Vec::new(),
}
}
pub fn errors<S: Into<SharedString>>(errors: impl IntoIterator<Item = S>) -> Self {
Self {
text: None,
errors: errors.into_iter().map(Into::into).collect(),
}
}
pub fn message(&self) -> Option<SharedString> {
if let Some(text) = self.text.clone().filter(|t| !t.is_empty()) {
return Some(text);
}
let joined = self
.errors
.iter()
.filter(|e| !e.is_empty())
.map(|e| e.as_ref())
.collect::<Vec<_>>()
.join(" ");
(!joined.is_empty()).then(|| joined.into())
}
}
impl RenderOnce for FieldError {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let message = self.message();
div().when_some(message, |_, text| {
form::requirement(&form::Validation::Invalid(text)).unwrap_or_else(div)
})
}
}
#[derive(IntoElement, Default)]
pub struct FieldGroup {
children: Vec<AnyElement>,
}
impl FieldGroup {
pub fn new() -> Self {
Self::default()
}
}
parent!(FieldGroup);
impl RenderOnce for FieldGroup {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap(tokens::SPACING_06)
.w_full()
.children(self.children)
}
}
#[derive(IntoElement, Default)]
pub struct FieldSet {
children: Vec<AnyElement>,
}
impl FieldSet {
pub fn new() -> Self {
Self::default()
}
}
parent!(FieldSet);
impl RenderOnce for FieldSet {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div().flex().flex_col().w_full().children(self.children)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FieldLegendVariant {
#[default]
Legend,
Label,
}
#[derive(IntoElement)]
pub struct FieldLegend {
text: SharedString,
variant: FieldLegendVariant,
}
impl FieldLegend {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: text.into(),
variant: FieldLegendVariant::Legend,
}
}
pub fn variant(mut self, variant: FieldLegendVariant) -> Self {
self.variant = variant;
self
}
}
impl RenderOnce for FieldLegend {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let label = form::label(self.text, false);
match self.variant {
FieldLegendVariant::Label => label,
FieldLegendVariant::Legend => label
.type_style(TypeStyle::HeadingCompact01)
.text_color(color(ColorRole::TextPrimary)),
}
}
}
#[derive(IntoElement, Default)]
pub struct FieldSeparator {
text: Option<SharedString>,
}
impl FieldSeparator {
pub fn new() -> Self {
Self::default()
}
pub fn text(mut self, text: impl Into<SharedString>) -> Self {
self.text = Some(text.into());
self
}
}
impl RenderOnce for FieldSeparator {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.relative()
.w_full()
.my(tokens::SPACING_03)
.h(px(1.))
.bg(color(ColorRole::BorderSubtle01))
.when_some(self.text, |this, text| {
this.child(
div()
.absolute()
.left_0()
.right_0()
.top(rem(-8.))
.h(rem(16.))
.flex()
.justify_center()
.child(
div()
.px(tokens::SPACING_03)
.bg(color(ColorRole::Background))
.type_style(TypeStyle::Label01)
.text_color(color(ColorRole::TextSecondary))
.child(text),
),
)
})
}
}
#[derive(IntoElement, Default)]
pub struct FieldContent {
children: Vec<AnyElement>,
}
impl FieldContent {
pub fn new() -> Self {
Self::default()
}
}
parent!(FieldContent);
impl RenderOnce for FieldContent {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(tokens::SPACING_02)
.children(self.children)
}
}
#[derive(IntoElement)]
pub struct FieldTitle {
text: SharedString,
}
impl FieldTitle {
pub fn new(text: impl Into<SharedString>) -> Self {
Self { text: text.into() }
}
}
impl RenderOnce for FieldTitle {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.type_style(TypeStyle::HeadingCompact01)
.text_color(color(ColorRole::TextPrimary))
.child(self.text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_mark_nests_and_clears() {
assert!(!in_invalid_field());
with_invalid_field(true, || {
assert!(in_invalid_field());
with_invalid_field(false, || assert!(in_invalid_field()));
});
assert!(!in_invalid_field());
with_invalid_field(false, || assert!(!in_invalid_field()));
}
#[test]
fn field_error_joins_errors_like_the_reference() {
assert_eq!(
FieldError::new("Required.").message().as_deref(),
Some("Required.")
);
let joined = FieldError::errors(["Too short.", "", "Use digits."]);
assert_eq!(joined.message().as_deref(), Some("Too short. Use digits."));
assert_eq!(FieldError::errors(Vec::<String>::new()).message(), None);
}
}