ui_input.rs

  1//! # UI – Text Field
  2//!
  3//! This crate provides a text field component that can be used to create text fields like search inputs, form fields, etc.
  4//!
  5//! It can't be located in the `ui` crate because it depends on `editor`.
  6//!
  7
  8use component::{example_group, single_example};
  9use editor::{Editor, EditorElement, EditorStyle};
 10use gpui::{App, Entity, FocusHandle, Focusable, FontStyle, Hsla, TextStyle};
 11use settings::Settings;
 12use theme::ThemeSettings;
 13use ui::prelude::*;
 14
 15pub struct SingleLineInputStyle {
 16    text_color: Hsla,
 17    background_color: Hsla,
 18    border_color: Hsla,
 19}
 20
 21/// A Text Field that can be used to create text fields like search inputs, form fields, etc.
 22///
 23/// It wraps a single line [`Editor`] and allows for common field properties like labels, placeholders, icons, etc.
 24#[derive(RegisterComponent)]
 25pub struct SingleLineInput {
 26    /// An optional label for the text field.
 27    ///
 28    /// Its position is determined by the [`FieldLabelLayout`].
 29    label: Option<SharedString>,
 30    /// The size of the label text.
 31    label_size: LabelSize,
 32    /// The placeholder text for the text field.
 33    placeholder: SharedString,
 34    /// Exposes the underlying [`Entity<Editor>`] to allow for customizing the editor beyond the provided API.
 35    ///
 36    /// This likely will only be public in the short term, ideally the API will be expanded to cover necessary use cases.
 37    pub editor: Entity<Editor>,
 38    /// An optional icon that is displayed at the start of the text field.
 39    ///
 40    /// For example, a magnifying glass icon in a search field.
 41    start_icon: Option<IconName>,
 42    /// Whether the text field is disabled.
 43    disabled: bool,
 44}
 45
 46impl Focusable for SingleLineInput {
 47    fn focus_handle(&self, cx: &App) -> FocusHandle {
 48        self.editor.focus_handle(cx)
 49    }
 50}
 51
 52impl SingleLineInput {
 53    pub fn new(window: &mut Window, cx: &mut App, placeholder: impl Into<SharedString>) -> Self {
 54        let placeholder_text = placeholder.into();
 55
 56        let editor = cx.new(|cx| {
 57            let mut input = Editor::single_line(window, cx);
 58            input.set_placeholder_text(placeholder_text.clone(), cx);
 59            input
 60        });
 61
 62        Self {
 63            label: None,
 64            label_size: LabelSize::Small,
 65            placeholder: placeholder_text,
 66            editor,
 67            start_icon: None,
 68            disabled: false,
 69        }
 70    }
 71
 72    pub fn start_icon(mut self, icon: IconName) -> Self {
 73        self.start_icon = Some(icon);
 74        self
 75    }
 76
 77    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
 78        self.label = Some(label.into());
 79        self
 80    }
 81
 82    pub fn label_size(mut self, size: LabelSize) -> Self {
 83        self.label_size = size;
 84        self
 85    }
 86
 87    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
 88        self.disabled = disabled;
 89        self.editor
 90            .update(cx, |editor, _| editor.set_read_only(disabled))
 91    }
 92
 93    pub fn is_empty(&self, cx: &App) -> bool {
 94        self.editor().read(cx).text(cx).trim().is_empty()
 95    }
 96
 97    pub fn editor(&self) -> &Entity<Editor> {
 98        &self.editor
 99    }
100}
101
102impl Render for SingleLineInput {
103    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
104        let settings = ThemeSettings::get_global(cx);
105        let theme_color = cx.theme().colors();
106
107        let mut style = SingleLineInputStyle {
108            text_color: theme_color.text,
109            background_color: theme_color.editor_background,
110            border_color: theme_color.border_variant,
111        };
112
113        if self.disabled {
114            style.text_color = theme_color.text_disabled;
115            style.background_color = theme_color.editor_background;
116            style.border_color = theme_color.border_disabled;
117        }
118
119        // if self.error_message.is_some() {
120        //     style.text_color = cx.theme().status().error;
121        //     style.border_color = cx.theme().status().error_border
122        // }
123
124        let text_style = TextStyle {
125            font_family: settings.ui_font.family.clone(),
126            font_features: settings.ui_font.features.clone(),
127            font_size: rems(0.875).into(),
128            font_weight: settings.buffer_font.weight,
129            font_style: FontStyle::Normal,
130            line_height: relative(1.2),
131            color: style.text_color,
132            ..Default::default()
133        };
134
135        let editor_style = EditorStyle {
136            background: theme_color.ghost_element_background,
137            local_player: cx.theme().players().local(),
138            text: text_style,
139            ..Default::default()
140        };
141
142        v_flex()
143            .id(self.placeholder.clone())
144            .w_full()
145            .gap_1()
146            .when_some(self.label.clone(), |this, label| {
147                this.child(
148                    Label::new(label)
149                        .size(self.label_size)
150                        .color(if self.disabled {
151                            Color::Disabled
152                        } else {
153                            Color::Default
154                        }),
155                )
156            })
157            .child(
158                h_flex()
159                    .min_w_48()
160                    .min_h_8()
161                    .w_full()
162                    .px_2()
163                    .py_1p5()
164                    .flex_grow()
165                    .text_color(style.text_color)
166                    .rounded_lg()
167                    .bg(style.background_color)
168                    .border_1()
169                    .border_color(style.border_color)
170                    .when_some(self.start_icon, |this, icon| {
171                        this.gap_1()
172                            .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
173                    })
174                    .child(EditorElement::new(&self.editor, editor_style)),
175            )
176    }
177}
178
179impl Component for SingleLineInput {
180    fn scope() -> ComponentScope {
181        ComponentScope::Input
182    }
183
184    fn preview(window: &mut Window, cx: &mut App) -> Option<AnyElement> {
185        let input_small =
186            cx.new(|cx| SingleLineInput::new(window, cx, "placeholder").label("Small Label"));
187
188        let input_regular = cx.new(|cx| {
189            SingleLineInput::new(window, cx, "placeholder")
190                .label("Regular Label")
191                .label_size(LabelSize::Default)
192        });
193
194        Some(
195            v_flex()
196                .gap_6()
197                .children(vec![example_group(vec![
198                    single_example(
199                        "Small Label (Default)",
200                        div().child(input_small.clone()).into_any_element(),
201                    ),
202                    single_example(
203                        "Regular Label",
204                        div().child(input_regular.clone()).into_any_element(),
205                    ),
206                ])])
207                .into_any_element(),
208        )
209    }
210}