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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum InputValidationState {
15 #[default]
16 Neutral,
17 Error,
18 Success,
19 Warning,
20}
21
22pub 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 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 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 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 pub fn read_only(mut self, read_only: bool) -> Self {
92 self.read_only = read_only;
93 self
94 }
95
96 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 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 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 pub fn text(&self) -> &str {
131 &self.content
132 }
133
134 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 pub fn clear(&mut self, cx: &mut Context<Self>) {
144 self.content.clear();
145 cx.notify();
146 }
147
148 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 if keystroke.modifiers.control || keystroke.modifiers.platform {
178 return;
179 }
180 match keystroke.key.as_str() {
186 "backspace" => {
187 if let Some(range) = self.marked_range.take() {
188 self.content.replace_range(range, "");
189 } else {
190 self.content.pop();
191 }
192 }
193 "enter" if self.multiline => self.content.push('\n'),
194 _ => {}
195 }
196 cx.notify();
197 }
198}
199
200impl Render for TextInput {
201 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
202 let focused = self.focus_handle.is_focused(window);
203 let is_empty = self.content.is_empty();
204 let text_color = if is_empty {
205 semantic::text_placeholder(cx)
206 } else {
207 semantic::text(cx)
208 };
209 let border_color = match self.validation {
210 InputValidationState::Error => palette::danger(500),
211 InputValidationState::Success => palette::success(500),
212 InputValidationState::Warning => palette::warning(500),
213 InputValidationState::Neutral => semantic::border(cx),
214 };
215 let ring_color = match self.validation {
216 InputValidationState::Error => palette::danger(500),
217 InputValidationState::Success => palette::success(500),
218 InputValidationState::Warning => palette::warning(500),
219 InputValidationState::Neutral => palette::primary(500),
220 };
221 let show_cursor = focused && !is_empty && !self.read_only;
222 let cursor = || div().w(px(1.)).h(px(16.)).bg(palette::primary(500));
223
224 let content: AnyElement = if self.multiline {
229 let text: SharedString = if is_empty {
230 self.placeholder.clone()
231 } else {
232 self.content.clone().into()
233 };
234 let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
235 let last_ix = lines.len().saturating_sub(1);
236 v_flex()
237 .w_full()
238 .children(lines.into_iter().enumerate().map(|(ix, line)| {
239 h_flex()
240 .min_h(px(20.))
241 .items_center()
242 .gap(DynamicSpacing::Base02.rems(cx))
243 .child(SharedString::from(line))
244 .when(ix == last_ix && show_cursor, |this| this.child(cursor()))
245 }))
246 .into_any_element()
247 } else {
248 let display: SharedString = if is_empty {
249 self.placeholder.clone()
250 } else {
251 self.content.clone().into()
252 };
253 h_flex()
254 .flex_wrap()
255 .items_center()
256 .gap(DynamicSpacing::Base02.rems(cx))
257 .child(display)
258 .when(show_cursor, |this| this.child(cursor()))
259 .into_any_element()
260 };
261
262 let field = div()
263 .track_focus(&self.focus_handle)
264 .on_key_down(cx.listener(Self::on_key_down))
265 .on_mouse_down(
266 MouseButton::Left,
267 cx.listener(|this, _event, window, cx| {
268 window.focus(&this.focus_handle, cx);
269 cx.notify();
270 }),
271 )
272 .w_full()
273 .when(self.multiline, |this| this.min_h(px(96.)))
274 .px(DynamicSpacing::Base12.px(cx))
275 .py(DynamicSpacing::Base08.px(cx))
276 .rounded_md()
277 .bg(semantic::surface(cx))
278 .border_1()
279 .border_color(border_color)
280 .text_color(text_color)
281 .child(content)
282 .child({
283 let focus_handle = self.focus_handle.clone();
288 let entity = cx.entity();
289 canvas(
290 move |_bounds, _window, _cx| {},
291 move |bounds, _state, window, cx| {
292 window.handle_input(
293 &focus_handle,
294 ElementInputHandler::new(bounds, entity.clone()),
295 cx,
296 );
297 },
298 )
299 .absolute()
300 .size_full()
301 });
302
303 focus_ring(field, focused, ring_color)
304 }
305}
306
307impl Focusable for TextInput {
308 fn focus_handle(&self, _cx: &App) -> FocusHandle {
309 self.focus_handle.clone()
310 }
311}
312
313impl EntityInputHandler for TextInput {
314 fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
315 !self.read_only
316 }
317
318 fn selected_text_range(
322 &mut self,
323 _ignore_disabled_input: bool,
324 _window: &mut Window,
325 _cx: &mut Context<Self>,
326 ) -> Option<UTF16Selection> {
327 None
328 }
329
330 fn marked_text_range(
332 &self,
333 _window: &mut Window,
334 _cx: &mut Context<Self>,
335 ) -> Option<Range<usize>> {
336 self.marked_range.clone()
337 }
338
339 fn text_for_range(
342 &mut self,
343 range_utf16: Range<usize>,
344 _adjusted_range: &mut Option<Range<usize>>,
345 _window: &mut Window,
346 _cx: &mut Context<Self>,
347 ) -> Option<String> {
348 let bytes = utf16_range_to_byte_range(&self.content, range_utf16)?;
349 Some(self.content[bytes].to_string())
350 }
351
352 fn replace_text_in_range(
355 &mut self,
356 range: Option<Range<usize>>,
357 text: &str,
358 _window: &mut Window,
359 cx: &mut Context<Self>,
360 ) {
361 if self.read_only {
362 return;
363 }
364 if let Some(marked) = self.marked_range.take() {
365 self.content.replace_range(marked, text);
366 } else if let Some(range) = range {
367 let bytes = utf16_range_to_byte_range(&self.content, range);
368 if let Some(bytes) = bytes {
369 self.content.replace_range(bytes, text);
370 } else {
371 self.content.push_str(text);
372 }
373 } else {
374 self.content.push_str(text);
375 }
376 cx.notify();
377 }
378
379 fn replace_and_mark_text_in_range(
382 &mut self,
383 range: Option<Range<usize>>,
384 new_text: &str,
385 _new_selected_range: Option<Range<usize>>,
386 _window: &mut Window,
387 cx: &mut Context<Self>,
388 ) {
389 if self.read_only {
390 return;
391 }
392 let start_byte = if let Some(marked) = self.marked_range.clone() {
393 self.content.replace_range(marked.clone(), new_text);
394 marked.start
395 } else if let Some(range) = range {
396 let bytes = utf16_range_to_byte_range(&self.content, range);
397 if let Some(bytes) = bytes {
398 self.content.replace_range(bytes.clone(), new_text);
399 bytes.start
400 } else {
401 self.content.push_str(new_text);
402 self.content.len().saturating_sub(new_text.len())
403 }
404 } else {
405 let start = self.content.len();
406 self.content.push_str(new_text);
407 start
408 };
409 let end_byte = start_byte + new_text.len();
410 self.marked_range = Some(start_byte..end_byte);
411 cx.notify();
412 }
413
414 fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
416 if self.marked_range.take().is_some() {
417 cx.notify();
418 }
419 }
420
421 fn bounds_for_range(
425 &mut self,
426 _range_utf16: Range<usize>,
427 element_bounds: Bounds<Pixels>,
428 _window: &mut Window,
429 _cx: &mut Context<Self>,
430 ) -> Option<Bounds<Pixels>> {
431 Some(element_bounds)
432 }
433
434 fn character_index_for_point(
435 &mut self,
436 _point: gpui::Point<Pixels>,
437 _window: &mut Window,
438 _cx: &mut Context<Self>,
439 ) -> Option<usize> {
440 None
441 }
442}
443
444fn utf16_range_to_byte_range(text: &str, range_utf16: Range<usize>) -> Option<Range<usize>> {
447 let mut start_byte = None;
448 let mut end_byte = None;
449 let mut utf16_index = 0usize;
450 for (byte_idx, ch) in text.char_indices() {
451 if start_byte.is_none() && utf16_index >= range_utf16.start {
452 start_byte = Some(byte_idx);
453 }
454 utf16_index += ch.len_utf16();
455 if end_byte.is_none() && utf16_index >= range_utf16.end {
456 end_byte = Some(byte_idx + ch.len_utf8());
457 break;
458 }
459 }
460 let start = start_byte.unwrap_or(text.len());
461 let end = end_byte.unwrap_or(text.len());
462 if start <= end && start <= text.len() && end <= text.len() {
463 Some(start..end)
464 } else {
465 None
466 }
467}
468
469pub type Textarea = TextInput;