Skip to main content

ui/components/
text_input.rs

1use std::ops::Range;
2use std::rc::Rc;
3
4use gpui::{
5    AnyElement, Bounds, Context, ElementInputHandler, EntityInputHandler, FocusHandle, Focusable,
6    KeyDownEvent, MouseButton, Pixels, Render, UTF16Selection, canvas,
7};
8
9use crate::prelude::*;
10
11/// Visual validation state of a [`TextInput`], reflected in its border/focus
12/// ring color.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum InputValidationState {
15    #[default]
16    Neutral,
17    Error,
18    Success,
19    Warning,
20}
21
22/// A focusable single-line (or multi-line) text field backed by a real
23/// `String` buffer. Keyboard input is handled via key events (`key_char` +
24/// editing keys), so typed characters genuinely appear and backspace deletes.
25/// IME composition (e.g. Vietnamese/CJK input methods) is handled via the
26/// [`EntityInputHandler`] impl, so composed text commits correctly.
27///
28/// This is a stateful view: create with `cx.new(|cx| TextInput::new(cx))` and
29/// store the resulting `Entity<TextInput>`.
30pub struct TextInput {
31    content: String,
32    placeholder: SharedString,
33    focus_handle: FocusHandle,
34    multiline: bool,
35    submit_on_enter: bool,
36    validation: InputValidationState,
37    read_only: bool,
38    /// Byte range of in-progress IME marked (composition) text within
39    /// `content`, if any. `None` when no composition is active.
40    marked_range: Option<Range<usize>>,
41    on_submit: Option<Rc<dyn Fn(&mut Window, &mut Context<Self>) + 'static>>,
42}
43
44impl TextInput {
45    pub fn new(cx: &mut App) -> Self {
46        Self {
47            content: String::new(),
48            placeholder: SharedString::default(),
49            focus_handle: cx.focus_handle(),
50            multiline: false,
51            submit_on_enter: false,
52            validation: InputValidationState::Neutral,
53            read_only: false,
54            marked_range: None,
55            on_submit: None,
56        }
57    }
58
59    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
60        self.placeholder = placeholder.into();
61        self
62    }
63
64    pub fn multiline(mut self, multiline: bool) -> Self {
65        self.multiline = multiline;
66        self
67    }
68
69    /// When `true`, plain Enter fires [`Self::on_submit`] instead of
70    /// inserting a newline; Shift/Ctrl/Cmd+Enter still inserts a newline (in
71    /// `multiline` mode). Defaults to `false`, which preserves the previous
72    /// behavior of always inserting a newline on Enter in `multiline` mode
73    /// (e.g. `CodeEditor`'s free-form multiline input).
74    pub fn submit_on_enter(mut self, submit_on_enter: bool) -> Self {
75        self.submit_on_enter = submit_on_enter;
76        self
77    }
78
79    /// Registers a callback fired when the user presses plain Enter while
80    /// [`Self::submit_on_enter`] is `true`. Has no effect otherwise.
81    pub fn on_submit(
82        mut self,
83        handler: impl Fn(&mut Window, &mut Context<Self>) + 'static,
84    ) -> Self {
85        self.on_submit = Some(Rc::new(handler));
86        self
87    }
88
89    /// When `true`, the input no longer accepts keyboard edits (used for
90    /// read-only code previews). Focus/selection styling is unaffected.
91    pub fn read_only(mut self, read_only: bool) -> Self {
92        self.read_only = read_only;
93        self
94    }
95
96    /// Sets the error validation state (red border/ring) when `invalid` is
97    /// true, otherwise clears back to [`InputValidationState::Neutral`].
98    pub fn invalid(mut self, invalid: bool) -> Self {
99        self.validation = if invalid {
100            InputValidationState::Error
101        } else {
102            InputValidationState::Neutral
103        };
104        self
105    }
106
107    /// Sets the success validation state (green border/ring) when `success`
108    /// is true, otherwise clears back to [`InputValidationState::Neutral`].
109    pub fn success(mut self, success: bool) -> Self {
110        self.validation = if success {
111            InputValidationState::Success
112        } else {
113            InputValidationState::Neutral
114        };
115        self
116    }
117
118    /// Sets the warning validation state (amber border/ring) when `warning`
119    /// is true, otherwise clears back to [`InputValidationState::Neutral`].
120    pub fn warning(mut self, warning: bool) -> Self {
121        self.validation = if warning {
122            InputValidationState::Warning
123        } else {
124            InputValidationState::Neutral
125        };
126        self
127    }
128
129    /// The current text content.
130    pub fn text(&self) -> &str {
131        &self.content
132    }
133
134    /// Programmatically sets the text content (e.g. `SearchInput`/`Combobox`
135    /// setting the display text after a selection). Notifies for re-render.
136    pub fn set_text(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {
137        self.content = text.into();
138        cx.notify();
139    }
140
141    /// Clears the text content (e.g. `SearchInput`'s clear button). Notifies
142    /// for re-render.
143    pub fn clear(&mut self, cx: &mut Context<Self>) {
144        self.content.clear();
145        cx.notify();
146    }
147
148    /// Dynamically toggles read-only mode after construction (e.g.
149    /// `CodeEditor` switching an already-created input between editable and
150    /// preview modes). Notifies for re-render.
151    pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context<Self>) {
152        self.read_only = read_only;
153        cx.notify();
154    }
155
156    fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
157        if self.read_only {
158            return;
159        }
160        let keystroke = &event.keystroke;
161
162        if self.submit_on_enter && keystroke.key == "enter" {
163            let wants_newline = self.multiline
164                && (keystroke.modifiers.shift
165                    || keystroke.modifiers.control
166                    || keystroke.modifiers.platform);
167            if wants_newline {
168                self.content.push('\n');
169            } else if let Some(on_submit) = self.on_submit.clone() {
170                on_submit(window, cx);
171            }
172            cx.notify();
173            return;
174        }
175
176        // Ignore keyboard shortcuts (cmd/ctrl chords) — only capture text input.
177        if keystroke.modifiers.control || keystroke.modifiers.platform {
178            return;
179        }
180        match keystroke.key.as_str() {
181            "backspace" => {
182                self.content.pop();
183            }
184            "enter" if self.multiline => self.content.push('\n'),
185            "space" => self.content.push(' '),
186            _ => {
187                if let Some(text) = &keystroke.key_char {
188                    self.content.push_str(text);
189                }
190            }
191        }
192        cx.notify();
193    }
194}
195
196impl Render for TextInput {
197    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
198        let focused = self.focus_handle.is_focused(window);
199        let is_empty = self.content.is_empty();
200        let text_color = if is_empty {
201            semantic::text_placeholder(cx)
202        } else {
203            semantic::text(cx)
204        };
205        let border_color = match self.validation {
206            InputValidationState::Error => palette::danger(500),
207            InputValidationState::Success => palette::success(500),
208            InputValidationState::Warning => palette::warning(500),
209            InputValidationState::Neutral => semantic::border(cx),
210        };
211        let ring_color = match self.validation {
212            InputValidationState::Error => palette::danger(500),
213            InputValidationState::Success => palette::success(500),
214            InputValidationState::Warning => palette::warning(500),
215            InputValidationState::Neutral => palette::primary(500),
216        };
217        let show_cursor = focused && !is_empty && !self.read_only;
218        let cursor = || div().w(px(1.)).h(px(16.)).bg(palette::primary(500));
219
220        // Multiline content is split and rendered one row per line (rather
221        // than a single text child carrying embedded `\n`s) so each typed
222        // newline reliably produces a new visual row, with the blinking
223        // caret appended to the last row.
224        let content: AnyElement = if self.multiline {
225            let text: SharedString = if is_empty {
226                self.placeholder.clone()
227            } else {
228                self.content.clone().into()
229            };
230            let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
231            let last_ix = lines.len().saturating_sub(1);
232            v_flex()
233                .w_full()
234                .children(lines.into_iter().enumerate().map(|(ix, line)| {
235                    h_flex()
236                        .min_h(px(20.))
237                        .items_center()
238                        .gap(DynamicSpacing::Base02.rems(cx))
239                        .child(SharedString::from(line))
240                        .when(ix == last_ix && show_cursor, |this| this.child(cursor()))
241                }))
242                .into_any_element()
243        } else {
244            let display: SharedString = if is_empty {
245                self.placeholder.clone()
246            } else {
247                self.content.clone().into()
248            };
249            h_flex()
250                .flex_wrap()
251                .items_center()
252                .gap(DynamicSpacing::Base02.rems(cx))
253                .child(display)
254                .when(show_cursor, |this| this.child(cursor()))
255                .into_any_element()
256        };
257
258        let field = div()
259            .track_focus(&self.focus_handle)
260            .on_key_down(cx.listener(Self::on_key_down))
261            .on_mouse_down(
262                MouseButton::Left,
263                cx.listener(|this, _event, window, cx| {
264                    window.focus(&this.focus_handle, cx);
265                    cx.notify();
266                }),
267            )
268            .w_full()
269            .when(self.multiline, |this| this.min_h(px(96.)))
270            .px(DynamicSpacing::Base12.px(cx))
271            .py(DynamicSpacing::Base08.px(cx))
272            .rounded_md()
273            .bg(semantic::surface(cx))
274            .border_1()
275            .border_color(border_color)
276            .text_color(text_color)
277            .child(content)
278            .child({
279                // Register an IME input handler for this field so platform
280                // input methods (Vietnamese/CJK IME, dead-key composition)
281                // commit text through `EntityInputHandler` instead of being
282                // dropped. `handle_input` only activates while focused.
283                let focus_handle = self.focus_handle.clone();
284                let entity = cx.entity();
285                canvas(
286                    move |_bounds, _window, _cx| {},
287                    move |bounds, _state, window, cx| {
288                        window.handle_input(
289                            &focus_handle,
290                            ElementInputHandler::new(bounds, entity.clone()),
291                            cx,
292                        );
293                    },
294                )
295                .absolute()
296                .size_full()
297            });
298
299        focus_ring(field, focused, ring_color)
300    }
301}
302
303impl Focusable for TextInput {
304    fn focus_handle(&self, _cx: &App) -> FocusHandle {
305        self.focus_handle.clone()
306    }
307}
308
309impl EntityInputHandler for TextInput {
310    fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
311        !self.read_only
312    }
313
314    /// No cursor/selection tracking — this is an append-only field. Returning
315    /// `None` tells the platform there is no active selection (IME commits at
316    /// the end).
317    fn selected_text_range(
318        &mut self,
319        _ignore_disabled_input: bool,
320        _window: &mut Window,
321        _cx: &mut Context<Self>,
322    ) -> Option<UTF16Selection> {
323        None
324    }
325
326    /// The byte range of in-progress IME marked (composition) text.
327    fn marked_text_range(
328        &self,
329        _window: &mut Window,
330        _cx: &mut Context<Self>,
331    ) -> Option<Range<usize>> {
332        self.marked_range.clone()
333    }
334
335    /// Returns the text in the given UTF-16 range (used by the platform to
336    /// read back what's around the composition).
337    fn text_for_range(
338        &mut self,
339        range_utf16: Range<usize>,
340        _adjusted_range: &mut Option<Range<usize>>,
341        _window: &mut Window,
342        _cx: &mut Context<Self>,
343    ) -> Option<String> {
344        let bytes = utf16_range_to_byte_range(&self.content, range_utf16)?;
345        Some(self.content[bytes].to_string())
346    }
347
348    /// IME committed text (or a plain paste/insert). Replaces any in-progress
349    /// marked range, otherwise appends at the end.
350    fn replace_text_in_range(
351        &mut self,
352        range: Option<Range<usize>>,
353        text: &str,
354        _window: &mut Window,
355        cx: &mut Context<Self>,
356    ) {
357        if self.read_only {
358            return;
359        }
360        if let Some(marked) = self.marked_range.take() {
361            self.content.replace_range(marked, text);
362        } else if let Some(range) = range {
363            let bytes = utf16_range_to_byte_range(&self.content, range);
364            if let Some(bytes) = bytes {
365                self.content.replace_range(bytes, text);
366            } else {
367                self.content.push_str(text);
368            }
369        } else {
370            self.content.push_str(text);
371        }
372        cx.notify();
373    }
374
375    /// IME composition in progress — replace the given range (or append) with
376    /// `new_text` and mark it as the active composition range.
377    fn replace_and_mark_text_in_range(
378        &mut self,
379        range: Option<Range<usize>>,
380        new_text: &str,
381        _new_selected_range: Option<Range<usize>>,
382        _window: &mut Window,
383        cx: &mut Context<Self>,
384    ) {
385        if self.read_only {
386            return;
387        }
388        let start_byte = if let Some(marked) = self.marked_range.clone() {
389            self.content.replace_range(marked.clone(), new_text);
390            marked.start
391        } else if let Some(range) = range {
392            let bytes = utf16_range_to_byte_range(&self.content, range);
393            if let Some(bytes) = bytes {
394                self.content.replace_range(bytes.clone(), new_text);
395                bytes.start
396            } else {
397                self.content.push_str(new_text);
398                self.content.len().saturating_sub(new_text.len())
399            }
400        } else {
401            let start = self.content.len();
402            self.content.push_str(new_text);
403            start
404        };
405        let end_byte = start_byte + new_text.len();
406        self.marked_range = Some(start_byte..end_byte);
407        cx.notify();
408    }
409
410    /// Composition finalized/abandoned — drop the mark without changing text.
411    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
412        if self.marked_range.take().is_some() {
413            cx.notify();
414        }
415    }
416
417    /// Bounds for a UTF-16 range within the field, for IME candidate placement.
418    /// Best-effort: returns the element bounds (candidates appear near the
419    /// field, not pixel-perfect per-character).
420    fn bounds_for_range(
421        &mut self,
422        _range_utf16: Range<usize>,
423        element_bounds: Bounds<Pixels>,
424        _window: &mut Window,
425        _cx: &mut Context<Self>,
426    ) -> Option<Bounds<Pixels>> {
427        Some(element_bounds)
428    }
429
430    fn character_index_for_point(
431        &mut self,
432        _point: gpui::Point<Pixels>,
433        _window: &mut Window,
434        _cx: &mut Context<Self>,
435    ) -> Option<usize> {
436        None
437    }
438}
439
440/// Maps a UTF-16 code-unit range to a byte range within `text` (Rust strings
441/// are UTF-8). Returns `None` if the range is out of bounds.
442fn utf16_range_to_byte_range(text: &str, range_utf16: Range<usize>) -> Option<Range<usize>> {
443    let mut start_byte = None;
444    let mut end_byte = None;
445    let mut utf16_index = 0usize;
446    for (byte_idx, ch) in text.char_indices() {
447        if start_byte.is_none() && utf16_index >= range_utf16.start {
448            start_byte = Some(byte_idx);
449        }
450        utf16_index += ch.len_utf16();
451        if end_byte.is_none() && utf16_index >= range_utf16.end {
452            end_byte = Some(byte_idx + ch.len_utf8());
453            break;
454        }
455    }
456    let start = start_byte.unwrap_or(text.len());
457    let end = end_byte.unwrap_or(text.len());
458    if start <= end && start <= text.len() && end <= text.len() {
459        Some(start..end)
460    } else {
461        None
462    }
463}
464
465/// A multi-line text field. Construct with
466/// `cx.new(|cx| Textarea::new(cx).multiline(true))`.
467pub type Textarea = TextInput;