Skip to main content

fc_ui/capabilities/controls/
input_state.rs

1use crate::capabilities::foundation::theme::use_theme;
2/// Interactive text input state management with validation and accessibility
3///
4/// Industry-standard input component with:
5/// - Multiple input types with built-in validation
6/// - Character filtering and input masking
7/// - Proper cursor management and accessibility
8/// - Real-time validation with error messages
9/// - Min/max length enforcement
10/// - Pattern matching support
11/// - Auto-formatting for phone, date, credit card
12/// - ARIA support for screen readers
13use gpui::{prelude::*, *};
14use std::ops::Range;
15use std::sync::LazyLock;
16
17use crate::capabilities::controls::input_format::DisplayMapping;
18use crate::capabilities::controls::text_util;
19use crate::capabilities::controls::validation;
20
21// The canonical definitions live in `controls::validation` so that
22// `TextareaState` shares the exact same machinery; they are re-exported here
23// to preserve the long-standing `input_state::ValidationRules` public path.
24pub use crate::capabilities::controls::validation::{ValidationError, ValidationRules};
25
26static EMAIL_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
27    regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
28        .expect("Invalid email regex pattern")
29});
30
31actions!(
32    input_state,
33    [
34        Backspace,
35        Delete,
36        Left,
37        Right,
38        SelectLeft,
39        SelectRight,
40        SelectAll,
41        Home,
42        End,
43        Copy,
44        Cut,
45        Paste,
46        Enter,
47        Tab,
48        ShiftTab,
49        Escape,
50        WordLeft,
51        WordRight,
52        SelectWordLeft,
53        SelectWordRight,
54    ]
55);
56
57/// Input types with built-in validation and filtering
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum InputType {
60    /// Plain text input (default)
61    Text,
62    /// Email input with @ and domain validation
63    Email,
64    /// Numeric input (integers and decimals)
65    Number,
66    /// Phone number with formatting
67    Tel,
68    /// URL input with protocol validation
69    Url,
70    /// Password input with strength indicators
71    Password,
72    /// Search input with debounced events
73    Search,
74    /// Date input (YYYY-MM-DD format)
75    Date,
76    /// Time input (HH:MM format)
77    Time,
78    /// Credit card number with masking
79    CreditCard,
80}
81
82/// Input masking for formatting
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum InputMask {
85    /// No masking
86    None,
87    /// Phone: (999) 999-9999
88    Phone,
89    /// Credit card: 9999 9999 9999 9999
90    CreditCard,
91    /// Date: MM/DD/YYYY
92    Date,
93    /// Time: HH:MM
94    Time,
95    /// Custom mask pattern
96    Custom(&'static str),
97}
98
99/// Events emitted by the InputState
100#[derive(Clone, Debug)]
101pub enum InputEvent {
102    Change,
103    Enter,
104    Focus,
105    Blur,
106    Validate(Result<(), ValidationError>),
107    Tab,
108    ShiftTab,
109}
110
111#[derive(Clone, Copy)]
112enum DeletionDirection {
113    Backward,
114    Forward,
115}
116
117/// Core input state entity that handles text editing with validation
118pub struct InputState {
119    focus_handle: FocusHandle,
120    /// Canonical value before custom display formatting.
121    raw_content: String,
122    /// Last display string written by `InputState` itself. Since `content` is
123    /// public for compatibility, this lets us distinguish an external write
124    /// from a formatter change without reverse-running the formatter.
125    last_synced_display: String,
126    pub content: SharedString,
127    pub placeholder: SharedString,
128    pub disabled: bool,
129    pub masked: bool,
130    selected_range: Range<usize>,
131    selection_reversed: bool,
132    marked_range: Option<Range<usize>>,
133    last_layout: Option<gpui::ShapedLine>,
134    last_bounds: Option<Bounds<Pixels>>,
135    is_selecting: bool,
136    was_focused: bool,
137    last_click_time: Option<std::time::Instant>,
138    last_click_position: Option<Point<Pixels>>,
139
140    // Cursor blink state
141    cursor_visible: bool,
142    _blink_task: Option<Task<()>>,
143
144    // Enhanced features
145    pub input_type: InputType,
146    pub validation_rules: ValidationRules,
147    pub validation_error: Option<ValidationError>,
148    pub input_mask: InputMask,
149    pub aria_label: Option<SharedString>,
150    pub aria_description: Option<SharedString>,
151    pub autocomplete: Option<SharedString>,
152    pub helper_text: Option<SharedString>,
153    pub success_message: Option<SharedString>,
154    pub tab_index: Option<i32>,
155    pub select_on_focus: bool,
156    pub validate_on_blur: bool,
157    pub validate_on_change: bool,
158    pub trim_on_blur: bool,
159    pub shake_triggered: bool,
160    pub(crate) shake_count: u32,
161    cursor_position_override: Option<usize>,
162
163    // Tracks whether the Input builder's `initial_value` has already been
164    // applied to this state. Without this, `Input::render` would re-apply
165    // the initial value every frame, overwriting user edits and emitting
166    // a spurious `Change` event on each render.
167    initial_value_applied: bool,
168    // Tracks formatter ownership so removing a builder formatter does not
169    // leave the previous display transformation installed on the state.
170    builder_formatter_active: bool,
171    event_subscription: Option<Subscription>,
172}
173
174impl EventEmitter<InputEvent> for InputState {}
175
176impl InputState {
177    pub fn new(cx: &mut Context<Self>) -> Self {
178        Self {
179            focus_handle: cx.focus_handle(),
180            raw_content: String::new(),
181            last_synced_display: String::new(),
182            content: "".into(),
183            placeholder: "Type here...".into(),
184            disabled: false,
185            masked: false,
186            selected_range: 0..0,
187            selection_reversed: false,
188            marked_range: None,
189            last_layout: None,
190            last_bounds: None,
191            is_selecting: false,
192            was_focused: false,
193            last_click_time: None,
194            last_click_position: None,
195            cursor_visible: true,
196            _blink_task: None,
197
198            input_type: InputType::Text,
199            validation_rules: ValidationRules::default(),
200            validation_error: None,
201            input_mask: InputMask::None,
202            aria_label: None,
203            aria_description: None,
204            autocomplete: None,
205            helper_text: None,
206            success_message: None,
207            tab_index: None,
208            select_on_focus: false,
209            validate_on_blur: true,
210            validate_on_change: false,
211            trim_on_blur: true,
212            shake_triggered: false,
213            shake_count: 0,
214            cursor_position_override: None,
215            initial_value_applied: false,
216            builder_formatter_active: false,
217            event_subscription: None,
218        }
219    }
220
221    pub(super) fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
222        self.event_subscription = subscription;
223    }
224
225    /// Set the input type
226    pub fn input_type(mut self, input_type: InputType) -> Self {
227        self.input_type = input_type;
228        match input_type {
229            InputType::Email => {
230                self.placeholder = "email@example.com".into();
231                self.autocomplete = Some("email".into());
232            }
233            InputType::Tel => {
234                self.placeholder = "(555) 555-5555".into();
235                self.input_mask = InputMask::Phone;
236                self.autocomplete = Some("tel".into());
237            }
238            InputType::Url => {
239                self.placeholder = "https://example.com".into();
240                self.autocomplete = Some("url".into());
241            }
242            InputType::Password => {
243                self.masked = true;
244                self.autocomplete = Some("current-password".into());
245            }
246            InputType::CreditCard => {
247                self.input_mask = InputMask::CreditCard;
248                self.placeholder = "1234 5678 9012 3456".into();
249                self.autocomplete = Some("cc-number".into());
250            }
251            InputType::Date => {
252                self.input_mask = InputMask::Date;
253                self.placeholder = "MM/DD/YYYY".into();
254            }
255            InputType::Time => {
256                self.input_mask = InputMask::Time;
257                self.placeholder = "HH:MM".into();
258            }
259            _ => {}
260        }
261        self
262    }
263
264    /// Set validation rules
265    pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
266        self.validation_rules = rules;
267        self
268    }
269
270    /// Set minimum length
271    pub fn min_length(mut self, min: usize) -> Self {
272        self.validation_rules.min_length = Some(min);
273        self
274    }
275
276    /// Set maximum length
277    pub fn max_length(mut self, max: usize) -> Self {
278        self.validation_rules.max_length = Some(max);
279        self
280    }
281
282    /// Mark field as required
283    pub fn required(mut self, required: bool) -> Self {
284        self.validation_rules.required = required;
285        self
286    }
287
288    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
289        self.placeholder = placeholder.into();
290        self
291    }
292
293    /// Set the initial value.
294    ///
295    /// Equivalent to assigning `content` directly, but leaves the caret at
296    /// the end of the text. This is raw initialization: it bypasses
297    /// validation rules, filtering, and `max_length` truncation. To replace
298    /// the value later with filtering, truncation, validation, and a
299    /// `Change` event, use [`InputState::set_value`].
300    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
301        self.content = value.into();
302        let len = self.content.len();
303        self.selected_range = len..len;
304        self
305    }
306
307    /// Set whether user interaction is disabled.
308    pub fn disabled(mut self, disabled: bool) -> Self {
309        self.disabled = disabled;
310        self
311    }
312
313    /// Set whether the whole value is selected when the input gains focus.
314    pub fn select_on_focus(mut self, select_on_focus: bool) -> Self {
315        self.select_on_focus = select_on_focus;
316        self
317    }
318
319    /// Set whether surrounding whitespace is trimmed on blur (default `true`).
320    pub fn trim_on_blur(mut self, trim_on_blur: bool) -> Self {
321        self.trim_on_blur = trim_on_blur;
322        self
323    }
324
325    /// Set the placeholder text
326    pub fn set_placeholder(
327        &mut self,
328        placeholder: impl Into<SharedString>,
329        _window: &mut Window,
330        cx: &mut Context<Self>,
331    ) {
332        self.placeholder = placeholder.into();
333        self.invalidate_layout_cache();
334        cx.notify();
335    }
336
337    pub fn content(&self) -> &str {
338        &self.content
339    }
340
341    /// Whether an IME composition is currently in progress.
342    ///
343    /// While composing, the in-flight text is displayed but not committed:
344    /// validation and `max_length` truncation only apply on commit.
345    pub fn is_composing(&self) -> bool {
346        self.marked_range.is_some()
347    }
348
349    /// Number of characters in the in-flight IME composition (0 when not
350    /// composing). `content()` includes these characters, so the committed
351    /// length is `content().chars().count() - composition_char_count()`.
352    pub fn composition_char_count(&self) -> usize {
353        // `content` is a public field: a direct external write can leave
354        // `marked_range` stale, so slice defensively instead of panicking.
355        self.marked_range
356            .as_ref()
357            .and_then(|range| self.content.get(range.clone()))
358            .map(|marked| marked.chars().count())
359            .unwrap_or(0)
360    }
361
362    /// Return the canonical value before display formatting.
363    pub(crate) fn raw_value(&self) -> &str {
364        &self.raw_content
365    }
366
367    /// Set the text content with validation
368    pub fn set_value(
369        &mut self,
370        value: impl Into<SharedString>,
371        window: &mut Window,
372        cx: &mut Context<Self>,
373    ) {
374        let value = value.into();
375        self.sync_raw_content();
376
377        // A formatter is allowed to omit all of the raw value from its
378        // display (for example a visibility formatter that renders an empty
379        // string).  In that case the display range is empty even though the
380        // raw value is not.  Replacing through the display range would append
381        // to the old raw value instead of replacing it.  Clear the raw value
382        // first so the normal insertion path still applies filtering,
383        // masking, length limits, validation, and event emission exactly
384        // once.
385        if self.content.is_empty() && !self.raw_content.is_empty() && self.marked_range.is_none() {
386            self.raw_content.clear();
387            self.selected_range = 0..0;
388            self.set_display_content(String::new());
389        }
390        let full_range_utf16 = 0..self.offset_to_utf16(self.content.len());
391        self.replace_text_in_range(Some(full_range_utf16), &value, window, cx);
392    }
393
394    pub(crate) fn value_matches(&self, value: &str) -> bool {
395        // Do not replace text while an IME composition is active. The parent
396        // value intentionally lags the composing value until `unmark_text`.
397        if self.marked_range.is_some() {
398            return true;
399        }
400        self.raw_content == value && self.content.as_ref() == self.format_content(value)
401    }
402
403    fn sync_raw_content(&mut self) {
404        if self.content.as_ref() != self.last_synced_display {
405            // `content` remains public for compatibility. An external write
406            // becomes the next raw value; a formatter update leaves content
407            // untouched and therefore preserves the existing raw value.
408            self.raw_content.clear();
409            self.raw_content.push_str(self.content.as_ref());
410            self.last_synced_display = self.content.to_string();
411        }
412    }
413
414    fn set_display_content(&mut self, display: String) {
415        self.content = display.into();
416        self.last_synced_display = self.content.to_string();
417    }
418
419    /// Re-apply a changed formatter while preserving the raw value and caret.
420    /// Composition text is deliberately left unformatted until `unmark_text`.
421    pub(crate) fn refresh_formatted_content(&mut self) {
422        self.sync_raw_content();
423        if self.marked_range.is_some() {
424            return;
425        }
426        let old_display = self.content.to_string();
427        if self.validation_rules.custom_formatter.is_none() {
428            if old_display == self.raw_content {
429                return;
430            }
431            let raw_range = Self::display_to_raw_index(
432                &self.raw_content,
433                &old_display,
434                self.selected_range.start,
435            )
436                ..Self::display_to_raw_index(
437                    &self.raw_content,
438                    &old_display,
439                    self.selected_range.end,
440                );
441            let raw = self.raw_content.clone();
442            self.set_display_content(raw);
443            self.selected_range = raw_range.start..raw_range.end;
444            self.invalidate_layout_cache();
445            return;
446        }
447        let new_display = self.format_content(&self.raw_content);
448        if old_display == new_display {
449            return;
450        }
451        let raw_range =
452            Self::display_to_raw_index(&self.raw_content, &old_display, self.selected_range.start)
453                ..Self::display_to_raw_index(
454                    &self.raw_content,
455                    &old_display,
456                    self.selected_range.end,
457                );
458        self.set_display_content(new_display.clone());
459        self.selected_range =
460            Self::raw_to_display_index(&self.raw_content, &new_display, raw_range.start)
461                ..Self::raw_to_display_index(&self.raw_content, &new_display, raw_range.end);
462        self.invalidate_layout_cache();
463    }
464
465    pub(crate) fn sync_builder_formatter(&mut self, active: bool) {
466        if !active && self.builder_formatter_active {
467            self.validation_rules.custom_formatter = None;
468        }
469        self.builder_formatter_active = active;
470    }
471
472    /// Apply the builder-supplied initial value exactly once.
473    ///
474    /// `Input::render` runs every frame; calling `set_value` there would
475    /// overwrite user edits and emit a `Change` event on every render.
476    /// This helper applies the value only on the first call, so subsequent
477    /// renders leave the state untouched. To forcefully replace the value
478    /// later (e.g., resetting a form), call `set_value` directly.
479    pub fn apply_initial_value(
480        &mut self,
481        value: impl Into<SharedString>,
482        window: &mut Window,
483        cx: &mut Context<Self>,
484    ) {
485        if self.initial_value_applied {
486            return;
487        }
488        self.initial_value_applied = true;
489        self.set_value(value, window, cx);
490    }
491
492    /// Validate the current input value
493    pub fn validate(&mut self, cx: &mut Context<Self>) -> Result<(), ValidationError> {
494        self.sync_raw_content();
495        let value = self.committed_raw_value();
496        let field_name = self.aria_label.clone();
497
498        if let Some(result) = validation::check_required_empty(
499            self.validation_rules.required,
500            &value,
501            field_name.clone(),
502        ) {
503            if result.is_ok() {
504                // Optional empty value: clear any stale messages without
505                // reporting success.
506                self.validation_error = None;
507                self.success_message = None;
508                cx.emit(InputEvent::Validate(Ok(())));
509                cx.notify();
510                return Ok(());
511            }
512            return self.finish_validation(result, cx);
513        }
514
515        if let Err(error) = self.validate_input_type(&value) {
516            return self.finish_validation(Err(error), cx);
517        }
518
519        let result = validation::check_constraints(&self.validation_rules, &value, field_name);
520        self.finish_validation(result, cx)
521    }
522
523    fn validate_input_type(&self, value: &str) -> Result<(), ValidationError> {
524        match self.input_type {
525            InputType::Email => self.validate_email(value),
526            InputType::Number => self.validate_number(value),
527            InputType::Url => self.validate_url(value),
528            InputType::Tel => self.validate_phone(value),
529            InputType::Date => self.validate_date(value),
530            InputType::Time => self.validate_time(value),
531            InputType::CreditCard => self.validate_credit_card(value),
532            _ => Ok(()),
533        }
534    }
535
536    fn committed_raw_value(&self) -> String {
537        let Some(range) = self.marked_range.as_ref() else {
538            return self.raw_content.clone();
539        };
540        let Some(_) = self.raw_content.get(range.clone()) else {
541            return self.raw_content.clone();
542        };
543        let mut committed = self.raw_content.clone();
544        committed.replace_range(range.clone(), "");
545        committed
546    }
547
548    fn finish_validation(
549        &mut self,
550        result: Result<(), ValidationError>,
551        cx: &mut Context<Self>,
552    ) -> Result<(), ValidationError> {
553        match &result {
554            Ok(()) => {
555                self.validation_error = None;
556                self.success_message = Some("Valid input".into());
557            }
558            Err(error) => {
559                self.validation_error = Some(error.clone());
560            }
561        }
562        cx.emit(InputEvent::Validate(result.clone()));
563        cx.notify();
564        result
565    }
566
567    pub fn trigger_shake(&mut self) {
568        self.shake_triggered = true;
569    }
570
571    fn filter_input(&self, input: &str) -> String {
572        if let Some(ref custom_filter) = self.validation_rules.custom_filter {
573            return custom_filter(input);
574        }
575
576        match self.input_type {
577            InputType::Number => input
578                .chars()
579                .filter(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
580                .collect(),
581            InputType::Tel => input
582                .chars()
583                .filter(|c| {
584                    c.is_ascii_digit()
585                        || *c == '+'
586                        || *c == '-'
587                        || *c == '('
588                        || *c == ')'
589                        || *c == ' '
590                })
591                .collect(),
592            InputType::Date => input
593                .chars()
594                .filter(|c| c.is_ascii_digit() || *c == '/' || *c == '-')
595                .collect(),
596            InputType::Time => input
597                .chars()
598                .filter(|c| c.is_ascii_digit() || *c == ':')
599                .collect(),
600            InputType::CreditCard => input
601                .chars()
602                .filter(|c| c.is_ascii_digit() || *c == ' ')
603                .collect(),
604            _ => input.to_string(),
605        }
606    }
607
608    fn format_content(&self, content: &str) -> String {
609        if content.is_empty() {
610            return String::new();
611        }
612
613        self.validation_rules
614            .custom_formatter
615            .as_ref()
616            .map(|formatter| formatter(content))
617            .unwrap_or_else(|| content.to_owned())
618    }
619
620    fn raw_to_display_index(raw: &str, display: &str, raw_index: usize) -> usize {
621        DisplayMapping::raw_to_display_index(raw, display, raw_index)
622    }
623
624    fn display_to_raw_index(raw: &str, display: &str, display_index: usize) -> usize {
625        DisplayMapping::display_to_raw_index(raw, display, display_index)
626    }
627
628    fn apply_mask(&mut self, input: &str) -> String {
629        match self.input_mask {
630            InputMask::Phone => {
631                let digits: String = input.chars().filter(|c| c.is_ascii_digit()).collect();
632                if digits.len() <= 3 {
633                    digits
634                } else if digits.len() <= 6 {
635                    format!("({}) {}", &digits[0..3], &digits[3..])
636                } else if digits.len() <= 10 {
637                    format!("({}) {}-{}", &digits[0..3], &digits[3..6], &digits[6..])
638                } else {
639                    format!("({}) {}-{}", &digits[0..3], &digits[3..6], &digits[6..10])
640                }
641            }
642            InputMask::CreditCard => {
643                let digits: String = input.chars().filter(|c| c.is_ascii_digit()).collect();
644                digits
645                    .chars()
646                    .enumerate()
647                    .map(|(i, c)| {
648                        if i > 0 && i % 4 == 0 {
649                            format!(" {}", c)
650                        } else {
651                            c.to_string()
652                        }
653                    })
654                    .collect::<String>()
655            }
656            InputMask::Date => {
657                let digits: String = input.chars().filter(|c| c.is_ascii_digit()).collect();
658                if digits.len() <= 2 {
659                    digits
660                } else if digits.len() <= 4 {
661                    format!("{}/{}", &digits[0..2], &digits[2..])
662                } else if digits.len() <= 8 {
663                    format!("{}/{}/{}", &digits[0..2], &digits[2..4], &digits[4..])
664                } else {
665                    format!("{}/{}/{}", &digits[0..2], &digits[2..4], &digits[4..8])
666                }
667            }
668            InputMask::Time => {
669                let digits: String = input.chars().filter(|c| c.is_ascii_digit()).collect();
670                if digits.len() <= 2 {
671                    digits
672                } else if digits.len() <= 4 {
673                    format!("{}:{}", &digits[0..2], &digits[2..])
674                } else {
675                    format!("{}:{}", &digits[0..2], &digits[2..4])
676                }
677            }
678            _ => input.to_string(),
679        }
680    }
681
682    fn validate_email(&self, email: &str) -> Result<(), ValidationError> {
683        if !EMAIL_REGEX.is_match(email) {
684            return Err(ValidationError {
685                message: "Please enter a valid email address".into(),
686                field_name: self.aria_label.clone(),
687            });
688        }
689        Ok(())
690    }
691
692    fn validate_url(&self, url: &str) -> Result<(), ValidationError> {
693        if !url.starts_with("http://") && !url.starts_with("https://") {
694            return Err(ValidationError {
695                message: "URL must start with http:// or https://".into(),
696                field_name: self.aria_label.clone(),
697            });
698        }
699        Ok(())
700    }
701
702    fn validate_number(&self, number: &str) -> Result<(), ValidationError> {
703        let parsed = number.parse::<f64>();
704        if parsed.is_err() {
705            return Err(ValidationError {
706                message: "Please enter a valid number".into(),
707                field_name: self.aria_label.clone(),
708            });
709        }
710
711        if let Ok(value) = parsed {
712            if let Some(min) = self.validation_rules.min_value {
713                if value < min {
714                    return Err(ValidationError {
715                        message: format!("Must be at least {}", min).into(),
716                        field_name: self.aria_label.clone(),
717                    });
718                }
719            }
720            if let Some(max) = self.validation_rules.max_value {
721                if value > max {
722                    return Err(ValidationError {
723                        message: format!("Must be no more than {}", max).into(),
724                        field_name: self.aria_label.clone(),
725                    });
726                }
727            }
728        }
729        Ok(())
730    }
731
732    fn validate_phone(&self, phone: &str) -> Result<(), ValidationError> {
733        let digits: String = phone.chars().filter(|c| c.is_ascii_digit()).collect();
734        if digits.len() < 10 {
735            return Err(ValidationError {
736                message: "Phone number must be at least 10 digits".into(),
737                field_name: self.aria_label.clone(),
738            });
739        }
740        Ok(())
741    }
742
743    fn validate_date(&self, date: &str) -> Result<(), ValidationError> {
744        let parts: Vec<&str> = date.split('/').collect();
745        if parts.len() != 3 {
746            return Err(ValidationError {
747                message: "Date must be in MM/DD/YYYY format".into(),
748                field_name: self.aria_label.clone(),
749            });
750        }
751
752        let month = parts[0].parse::<u32>().unwrap_or(0);
753        let day = parts[1].parse::<u32>().unwrap_or(0);
754        let year = parts[2].parse::<u32>().unwrap_or(0);
755
756        if !(1..=12).contains(&month) {
757            return Err(ValidationError {
758                message: "Invalid month".into(),
759                field_name: self.aria_label.clone(),
760            });
761        }
762        if !(1..=31).contains(&day) {
763            return Err(ValidationError {
764                message: "Invalid day".into(),
765                field_name: self.aria_label.clone(),
766            });
767        }
768        if !(1900..=2100).contains(&year) {
769            return Err(ValidationError {
770                message: "Invalid year".into(),
771                field_name: self.aria_label.clone(),
772            });
773        }
774        Ok(())
775    }
776
777    fn validate_time(&self, time: &str) -> Result<(), ValidationError> {
778        let parts: Vec<&str> = time.split(':').collect();
779        if parts.len() != 2 {
780            return Err(ValidationError {
781                message: "Time must be in HH:MM format".into(),
782                field_name: self.aria_label.clone(),
783            });
784        }
785
786        let hours = parts[0].parse::<u32>().unwrap_or(25);
787        let minutes = parts[1].parse::<u32>().unwrap_or(61);
788
789        if hours > 23 {
790            return Err(ValidationError {
791                message: "Invalid hours (0-23)".into(),
792                field_name: self.aria_label.clone(),
793            });
794        }
795        if minutes > 59 {
796            return Err(ValidationError {
797                message: "Invalid minutes (0-59)".into(),
798                field_name: self.aria_label.clone(),
799            });
800        }
801        Ok(())
802    }
803
804    fn validate_credit_card(&self, card: &str) -> Result<(), ValidationError> {
805        let digits: String = card.chars().filter(|c| c.is_ascii_digit()).collect();
806        if digits.len() < 13 || digits.len() > 19 {
807            return Err(ValidationError {
808                message: "Invalid credit card number".into(),
809                field_name: self.aria_label.clone(),
810            });
811        }
812
813        let mut sum = 0;
814        let mut alternate = false;
815        for c in digits.chars().rev() {
816            let Some(mut digit) = c.to_digit(10) else {
817                continue;
818            };
819            if alternate {
820                digit *= 2;
821                if digit > 9 {
822                    digit -= 9;
823                }
824            }
825            sum += digit;
826            alternate = !alternate;
827        }
828
829        if sum % 10 != 0 {
830            return Err(ValidationError {
831                message: "Invalid credit card number".into(),
832                field_name: self.aria_label.clone(),
833            });
834        }
835        Ok(())
836    }
837
838    pub fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
839        if self.selected_range.is_empty() {
840            self.move_to(self.previous_boundary(self.cursor_offset()), cx);
841        } else {
842            self.move_to(self.selected_range.start, cx)
843        }
844    }
845
846    pub fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
847        if self.selected_range.is_empty() {
848            self.move_to(self.next_boundary(self.selected_range.end), cx);
849        } else {
850            self.move_to(self.selected_range.end, cx)
851        }
852    }
853
854    pub fn word_left(&mut self, _: &WordLeft, _: &mut Window, cx: &mut Context<Self>) {
855        let offset = self.previous_word_boundary(self.cursor_offset());
856        if self.selected_range.is_empty() {
857            self.move_to(offset, cx);
858        } else {
859            self.move_to(self.selected_range.start.min(offset), cx);
860        }
861    }
862
863    pub fn word_right(&mut self, _: &WordRight, _: &mut Window, cx: &mut Context<Self>) {
864        let offset = self.next_word_boundary(self.cursor_offset());
865        if self.selected_range.is_empty() {
866            self.move_to(offset, cx);
867        } else {
868            self.move_to(self.selected_range.end.max(offset), cx);
869        }
870    }
871
872    pub fn select_word_left(&mut self, _: &SelectWordLeft, _: &mut Window, cx: &mut Context<Self>) {
873        self.select_to(self.previous_word_boundary(self.cursor_offset()), cx);
874    }
875
876    pub fn select_word_right(
877        &mut self,
878        _: &SelectWordRight,
879        _: &mut Window,
880        cx: &mut Context<Self>,
881    ) {
882        self.select_to(self.next_word_boundary(self.cursor_offset()), cx);
883    }
884
885    pub fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
886        self.select_to(self.previous_boundary(self.cursor_offset()), cx);
887    }
888
889    pub fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
890        self.select_to(self.next_boundary(self.cursor_offset()), cx);
891    }
892
893    pub fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
894        self.selected_range = 0..self.content.len();
895        self.selection_reversed = false;
896        self.reset_blink(cx);
897        cx.notify()
898    }
899
900    pub fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
901        self.move_to(0, cx);
902    }
903
904    pub fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
905        self.move_to(self.content.len(), cx);
906    }
907
908    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
909        if self.selected_range.is_empty() {
910            let cursor = self.cursor_offset();
911            let previous = self.previous_boundary(cursor);
912            if previous == cursor {
913                return;
914            }
915            self.select_to(previous, cx)
916        }
917        self.replace_text_in_range_with_direction(
918            Some(DeletionDirection::Backward),
919            None,
920            "",
921            window,
922            cx,
923        )
924    }
925
926    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
927        if self.selected_range.is_empty() {
928            let cursor = self.cursor_offset();
929            let next = self.next_boundary(cursor);
930            if next == cursor {
931                return;
932            }
933            self.select_to(next, cx)
934        }
935        self.replace_text_in_range_with_direction(
936            Some(DeletionDirection::Forward),
937            None,
938            "",
939            window,
940            cx,
941        )
942    }
943
944    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
945        window.focus_next();
946        cx.emit(InputEvent::Tab);
947    }
948
949    pub fn shift_tab(&mut self, _: &ShiftTab, window: &mut Window, cx: &mut Context<Self>) {
950        window.focus_prev();
951        cx.emit(InputEvent::ShiftTab);
952    }
953
954    fn on_mouse_down(
955        &mut self,
956        event: &MouseDownEvent,
957        _window: &mut Window,
958        cx: &mut Context<Self>,
959    ) {
960        self.is_selecting = true;
961
962        let now = std::time::Instant::now();
963        let is_double_click = if let (Some(last_time), Some(last_pos)) =
964            (self.last_click_time, self.last_click_position)
965        {
966            let time_diff = now.duration_since(last_time);
967            let dx = event.position.x - last_pos.x;
968            let dy = event.position.y - last_pos.y;
969            let close_enough = dx < px(5.0) && dx > px(-5.0) && dy < px(5.0) && dy > px(-5.0);
970            time_diff.as_millis() < 500 && close_enough
971        } else {
972            false
973        };
974
975        self.last_click_time = Some(now);
976        self.last_click_position = Some(event.position);
977
978        if is_double_click && !self.content.is_empty() {
979            self.selected_range = 0..self.content.len();
980            self.selection_reversed = false;
981            self.reset_blink(cx);
982            cx.notify();
983            return;
984        }
985
986        let click_index = self.index_for_mouse_position(event.position);
987        self.cursor_position_override = Some(click_index);
988
989        if event.modifiers.shift {
990            self.select_to(click_index, cx);
991        } else {
992            self.move_to(click_index, cx)
993        }
994    }
995
996    fn on_mouse_up(&mut self, _: &MouseUpEvent, _window: &mut Window, _cx: &mut Context<Self>) {
997        self.is_selecting = false;
998    }
999
1000    fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
1001        if self.is_selecting {
1002            let position = self.index_for_mouse_position(event.position);
1003            self.select_to(position, cx);
1004        }
1005    }
1006
1007    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
1008        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
1009            let filtered_text = self.filter_input(&text.replace("\n", " "));
1010            self.replace_text_in_range(None, &filtered_text, window, cx);
1011        }
1012    }
1013
1014    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
1015        if !self.selected_range.is_empty() {
1016            cx.write_to_clipboard(ClipboardItem::new_string(
1017                self.content[self.selected_range.clone()].to_string(),
1018            ));
1019        }
1020    }
1021
1022    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
1023        if !self.selected_range.is_empty() {
1024            cx.write_to_clipboard(ClipboardItem::new_string(
1025                self.content[self.selected_range.clone()].to_string(),
1026            ));
1027            self.replace_text_in_range(None, "", window, cx)
1028        }
1029    }
1030
1031    pub fn enter(&mut self, _: &Enter, _: &mut Window, cx: &mut Context<Self>) {
1032        cx.emit(InputEvent::Enter);
1033        // Enter is a semantic action for a single-line input. Stop the action
1034        // here so GPUI does not fall through to character input and insert a
1035        // newline into a field that cannot represent one. Forms subscribe to
1036        // InputEvent::Enter instead of relying on action bubbling.
1037        cx.stop_propagation();
1038    }
1039
1040    pub fn escape(&mut self, _: &Escape, _window: &mut Window, cx: &mut Context<Self>) {
1041        self.selected_range = self.content.len()..self.content.len();
1042        cx.emit(InputEvent::Blur);
1043        cx.notify();
1044    }
1045
1046    /// Called when the input gains focus
1047    pub fn on_focus(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1048        self.start_blink(cx);
1049        if self.select_on_focus && !self.content.is_empty() {
1050            self.selected_range = 0..self.content.len();
1051        } else if let Some(position) = self.cursor_position_override.take() {
1052            let position = self.clamp_offset(position);
1053            self.selected_range = position..position;
1054        } else if !self.content.is_empty() {
1055            let len = self.content.len();
1056            self.selected_range = len..len;
1057        }
1058
1059        cx.emit(InputEvent::Focus);
1060        cx.notify();
1061    }
1062
1063    /// Called when the input loses focus
1064    pub fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1065        self.stop_blink();
1066        self.cursor_position_override.take();
1067        if self.trim_on_blur {
1068            self.sync_raw_content();
1069            let trimmed = self.raw_content.trim().to_string();
1070            if trimmed != self.raw_content {
1071                self.set_value(trimmed, window, cx);
1072            }
1073        }
1074
1075        if self.validate_on_blur {
1076            self.validate(cx).ok();
1077        }
1078
1079        cx.emit(InputEvent::Blur);
1080        cx.notify();
1081    }
1082
1083    // Syncs focus transitions observed during paint with focus/blur side
1084    // effects, mirroring TextareaState::sync_focus_state.
1085    fn sync_focus_state(&mut self, is_focused: bool, window: &mut Window, cx: &mut Context<Self>) {
1086        if self.was_focused == is_focused {
1087            return;
1088        }
1089
1090        self.was_focused = is_focused;
1091        if is_focused {
1092            self.on_focus(window, cx);
1093        } else {
1094            self.is_selecting = false;
1095            self.on_blur(window, cx);
1096        }
1097    }
1098
1099    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
1100        let offset = self.clamp_offset(offset);
1101        self.selected_range = offset..offset;
1102        self.selection_reversed = false;
1103        self.reset_blink(cx);
1104        cx.notify()
1105    }
1106
1107    fn cursor_offset(&self) -> usize {
1108        text_util::cursor_offset(&self.selected_range, self.selection_reversed)
1109    }
1110
1111    fn index_for_mouse_position(&mut self, position: Point<Pixels>) -> usize {
1112        if self.content.is_empty() {
1113            return 0;
1114        }
1115
1116        let (Some(bounds), Some(line)) = (self.last_bounds.as_ref(), self.last_layout.as_ref())
1117        else {
1118            return 0;
1119        };
1120        if !self.layout_matches_current_display(line) {
1121            self.invalidate_layout_cache();
1122            return self.cursor_offset();
1123        }
1124        if position.y < bounds.top() {
1125            return 0;
1126        }
1127        if position.y > bounds.bottom() {
1128            return self.content.len();
1129        }
1130
1131        let display_index = line.closest_index_for_x(position.x - bounds.left());
1132        self.display_to_source_index(display_index)
1133            .unwrap_or(self.content.len())
1134    }
1135
1136    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
1137        let offset = self.clamp_offset(offset);
1138        (self.selected_range, self.selection_reversed) = text_util::extend_selection(
1139            self.selected_range.clone(),
1140            self.selection_reversed,
1141            offset,
1142        );
1143        self.reset_blink(cx);
1144        cx.notify()
1145    }
1146
1147    fn offset_to_utf16(&self, offset: usize) -> usize {
1148        crate::capabilities::controls::text_util::offset_to_utf16(&self.content, offset)
1149    }
1150
1151    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
1152        crate::capabilities::controls::text_util::range_to_utf16(&self.content, range)
1153    }
1154
1155    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
1156        crate::capabilities::controls::text_util::range_from_utf16(&self.content, range_utf16)
1157    }
1158
1159    pub(crate) fn invalidate_layout_cache(&mut self) {
1160        self.last_layout = None;
1161        self.last_bounds = None;
1162    }
1163
1164    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
1165        if self.masked == masked {
1166            return;
1167        }
1168
1169        self.masked = masked;
1170        self.invalidate_layout_cache();
1171        cx.notify();
1172    }
1173
1174    fn current_display_text(&self) -> SharedString {
1175        if self.content.is_empty() {
1176            self.placeholder.clone()
1177        } else if self.masked {
1178            "•".repeat(self.content.chars().count()).into()
1179        } else {
1180            self.content.clone()
1181        }
1182    }
1183
1184    fn layout_matches_current_display(&self, layout: &gpui::ShapedLine) -> bool {
1185        layout.text == self.current_display_text()
1186    }
1187
1188    fn source_to_display_index(&self, source_index: usize) -> Option<usize> {
1189        if self.content.is_empty() {
1190            return None;
1191        }
1192
1193        if self.masked {
1194            let char_count = self.content.get(..source_index)?.chars().count();
1195            Some(char_count * "•".len())
1196        } else {
1197            Some(source_index.min(self.content.len()))
1198        }
1199    }
1200
1201    fn display_to_source_index(&self, display_index: usize) -> Option<usize> {
1202        if self.content.is_empty() {
1203            return None;
1204        }
1205
1206        if self.masked {
1207            let bullet_len = "•".len();
1208            let char_index = display_index / bullet_len;
1209            Some(
1210                self.content
1211                    .char_indices()
1212                    .nth(char_index)
1213                    .map(|(byte_idx, _)| byte_idx)
1214                    .unwrap_or(self.content.len()),
1215            )
1216        } else {
1217            Some(display_index.min(self.content.len()))
1218        }
1219    }
1220
1221    fn clamp_offset(&self, offset: usize) -> usize {
1222        text_util::clamp_offset(&self.content, offset)
1223    }
1224
1225    fn previous_boundary(&self, offset: usize) -> usize {
1226        text_util::previous_grapheme_boundary(&self.content, offset)
1227    }
1228
1229    fn next_boundary(&self, offset: usize) -> usize {
1230        text_util::next_grapheme_boundary(&self.content, offset)
1231    }
1232
1233    fn previous_word_boundary(&self, offset: usize) -> usize {
1234        text_util::previous_word_boundary(&self.content, offset)
1235    }
1236
1237    fn next_word_boundary(&self, offset: usize) -> usize {
1238        text_util::next_word_boundary(&self.content, offset)
1239    }
1240
1241    fn start_blink(&mut self, cx: &mut Context<Self>) {
1242        self._blink_task = None;
1243        self.cursor_visible = true;
1244        self._blink_task = Some(cx.spawn(async |this, cx| loop {
1245            cx.background_executor()
1246                .timer(std::time::Duration::from_millis(500))
1247                .await;
1248            let ok = this.update(cx, |this: &mut Self, cx: &mut Context<Self>| {
1249                this.cursor_visible = !this.cursor_visible;
1250                cx.notify();
1251            });
1252            if ok.is_err() {
1253                break;
1254            }
1255        }));
1256    }
1257
1258    fn stop_blink(&mut self) {
1259        self._blink_task = None;
1260        self.cursor_visible = true;
1261    }
1262
1263    fn reset_blink(&mut self, cx: &mut Context<Self>) {
1264        self.stop_blink();
1265        self.start_blink(cx);
1266    }
1267
1268    fn replace_text_in_range_with_direction(
1269        &mut self,
1270        deletion_direction: Option<DeletionDirection>,
1271        range_utf16: Option<Range<usize>>,
1272        new_text: &str,
1273        window: &mut Window,
1274        cx: &mut Context<Self>,
1275    ) {
1276        self.sync_raw_content();
1277        let had_marked_text = self.marked_range.is_some();
1278        let display_range = range_utf16
1279            .as_ref()
1280            .map(|range_utf16| self.range_from_utf16(range_utf16))
1281            .or(self.marked_range.clone())
1282            .unwrap_or(self.selected_range.clone());
1283        let mut range =
1284            Self::display_to_raw_index(&self.raw_content, &self.content, display_range.start)
1285                ..Self::display_to_raw_index(&self.raw_content, &self.content, display_range.end);
1286        if new_text.is_empty() && !display_range.is_empty() && range.is_empty() {
1287            if let Some(direction) = deletion_direction {
1288                let fallback = match direction {
1289                    DeletionDirection::Backward if range.start > 0 => Some(
1290                        text_util::previous_grapheme_boundary(&self.raw_content, range.start)
1291                            ..range.start,
1292                    ),
1293                    DeletionDirection::Forward if range.end < self.raw_content.len() => Some(
1294                        range.end..text_util::next_grapheme_boundary(&self.raw_content, range.end),
1295                    ),
1296                    _ => None,
1297                };
1298                let Some(fallback) = fallback else {
1299                    // The selected display text contains formatting
1300                    // characters only (for example a currency prefix). There
1301                    // is no raw value to remove in this direction.
1302                    return;
1303                };
1304                range = fallback;
1305            }
1306        }
1307
1308        let filtered_text = self.filter_input(new_text);
1309        let formatted_text = if self.input_mask != InputMask::None {
1310            self.apply_mask(&filtered_text)
1311        } else {
1312            filtered_text
1313        };
1314
1315        let formatted_text = if let Some(max_length) = self.validation_rules.max_length {
1316            let retained_chars =
1317                self.raw_content.chars().count() - self.raw_content[range.clone()].chars().count();
1318            let allowed_chars = max_length.saturating_sub(retained_chars);
1319            formatted_text
1320                .chars()
1321                .take(allowed_chars)
1322                .collect::<String>()
1323        } else {
1324            formatted_text
1325        };
1326
1327        let next_raw = self.raw_content[0..range.start].to_owned()
1328            + &formatted_text
1329            + &self.raw_content[range.end..];
1330        let content_changed = next_raw != self.raw_content;
1331        let next_display = self.format_content(&next_raw);
1332        let raw_cursor = range.start + formatted_text.len();
1333        let cursor = Self::raw_to_display_index(&next_raw, &next_display, raw_cursor);
1334
1335        self.raw_content = next_raw;
1336        self.set_display_content(next_display);
1337        self.selected_range = cursor..cursor;
1338
1339        self.marked_range.take();
1340        self.selection_reversed = false;
1341        if self.focus_handle.is_focused(window) {
1342            self.reset_blink(cx);
1343        }
1344        self.invalidate_layout_cache();
1345
1346        if (content_changed || had_marked_text) && self.validate_on_change {
1347            self.validate(cx).ok();
1348        }
1349
1350        if content_changed || had_marked_text {
1351            cx.emit(InputEvent::Change);
1352        }
1353        cx.notify();
1354    }
1355
1356    pub fn focus_handle(&self, _: &App) -> FocusHandle {
1357        self.focus_handle.clone()
1358    }
1359}
1360
1361impl EntityInputHandler for InputState {
1362    fn text_for_range(
1363        &mut self,
1364        range_utf16: Range<usize>,
1365        actual_range: &mut Option<Range<usize>>,
1366        _window: &mut Window,
1367        _cx: &mut Context<Self>,
1368    ) -> Option<String> {
1369        let range = self.range_from_utf16(&range_utf16);
1370        actual_range.replace(self.range_to_utf16(&range));
1371        Some(self.content[range].to_string())
1372    }
1373
1374    fn selected_text_range(
1375        &mut self,
1376        _ignore_disabled_input: bool,
1377        _window: &mut Window,
1378        _cx: &mut Context<Self>,
1379    ) -> Option<UTF16Selection> {
1380        Some(UTF16Selection {
1381            range: self.range_to_utf16(&self.selected_range),
1382            reversed: self.selection_reversed,
1383        })
1384    }
1385
1386    fn marked_text_range(
1387        &self,
1388        _window: &mut Window,
1389        _cx: &mut Context<Self>,
1390    ) -> Option<Range<usize>> {
1391        self.marked_range
1392            .as_ref()
1393            .map(|range| self.range_to_utf16(range))
1394    }
1395
1396    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1397        let had_marked_text = self.marked_range.is_some();
1398        self.sync_raw_content();
1399        if self.validation_rules.custom_formatter.is_some() {
1400            let raw_selected_range = self.selected_range.clone();
1401            let formatted = self.format_content(&self.raw_content);
1402            self.set_display_content(formatted);
1403            self.selected_range = Self::raw_to_display_index(
1404                &self.raw_content,
1405                &self.content,
1406                raw_selected_range.start,
1407            )
1408                ..Self::raw_to_display_index(
1409                    &self.raw_content,
1410                    &self.content,
1411                    raw_selected_range.end,
1412                );
1413        }
1414        self.marked_range = None;
1415        self.invalidate_layout_cache();
1416        if had_marked_text {
1417            if self.validate_on_change {
1418                self.validate(cx).ok();
1419            }
1420            cx.emit(InputEvent::Change);
1421        }
1422        cx.notify();
1423    }
1424
1425    fn replace_text_in_range(
1426        &mut self,
1427        range_utf16: Option<Range<usize>>,
1428        new_text: &str,
1429        window: &mut Window,
1430        cx: &mut Context<Self>,
1431    ) {
1432        self.replace_text_in_range_with_direction(None, range_utf16, new_text, window, cx);
1433    }
1434    fn replace_and_mark_text_in_range(
1435        &mut self,
1436        range_utf16: Option<Range<usize>>,
1437        new_text: &str,
1438        new_selected_range_utf16: Option<Range<usize>>,
1439        window: &mut Window,
1440        cx: &mut Context<Self>,
1441    ) {
1442        self.sync_raw_content();
1443        let display_range = range_utf16
1444            .as_ref()
1445            .map(|range_utf16| self.range_from_utf16(range_utf16))
1446            .or(self.marked_range.clone())
1447            .unwrap_or(self.selected_range.clone());
1448        let range =
1449            Self::display_to_raw_index(&self.raw_content, &self.content, display_range.start)
1450                ..Self::display_to_raw_index(&self.raw_content, &self.content, display_range.end);
1451
1452        let filtered_text = self.filter_input(new_text);
1453        let next_raw = self.raw_content[0..range.start].to_owned()
1454            + &filtered_text
1455            + &self.raw_content[range.end..];
1456        self.raw_content = next_raw;
1457
1458        // Keep the composition text editable until the IME commits it. The
1459        // formatter is applied once by `unmark_text`.
1460        self.set_display_content(self.raw_content.clone());
1461        if !filtered_text.is_empty() {
1462            self.marked_range = Some(range.start..range.start + filtered_text.len());
1463        } else {
1464            self.marked_range = None;
1465        }
1466        self.selected_range = new_selected_range_utf16
1467            .as_ref()
1468            .map(|range_utf16| text_util::range_from_utf16(&filtered_text, range_utf16))
1469            .map(|new_range| new_range.start + range.start..new_range.end + range.start)
1470            .unwrap_or_else(|| {
1471                range.start + filtered_text.len()..range.start + filtered_text.len()
1472            });
1473
1474        self.selection_reversed = false;
1475        if self.focus_handle.is_focused(window) {
1476            self.reset_blink(cx);
1477        }
1478        self.invalidate_layout_cache();
1479        cx.notify();
1480    }
1481
1482    fn bounds_for_range(
1483        &mut self,
1484        range_utf16: Range<usize>,
1485        bounds: Bounds<Pixels>,
1486        _window: &mut Window,
1487        _cx: &mut Context<Self>,
1488    ) -> Option<Bounds<Pixels>> {
1489        let layout_matches = {
1490            let last_layout = self.last_layout.as_ref()?;
1491            self.layout_matches_current_display(last_layout)
1492        };
1493        if !layout_matches {
1494            self.invalidate_layout_cache();
1495            return None;
1496        }
1497
1498        let last_layout = self.last_layout.as_ref()?;
1499        let range = self.range_from_utf16(&range_utf16);
1500        let display_start = self.source_to_display_index(range.start)?;
1501        let display_end = self.source_to_display_index(range.end)?;
1502        Some(Bounds::from_corners(
1503            point(
1504                bounds.left() + last_layout.x_for_index(display_start),
1505                bounds.top(),
1506            ),
1507            point(
1508                bounds.left() + last_layout.x_for_index(display_end),
1509                bounds.bottom(),
1510            ),
1511        ))
1512    }
1513
1514    fn character_index_for_point(
1515        &mut self,
1516        point: Point<Pixels>,
1517        _window: &mut Window,
1518        _cx: &mut Context<Self>,
1519    ) -> Option<usize> {
1520        let line_point = self.last_bounds?.localize(&point)?;
1521        let layout_matches = {
1522            let last_layout = self.last_layout.as_ref()?;
1523            self.layout_matches_current_display(last_layout)
1524        };
1525        if !layout_matches {
1526            self.invalidate_layout_cache();
1527            return None;
1528        }
1529
1530        let last_layout = self.last_layout.as_ref()?;
1531        let display_index = last_layout.index_for_x(point.x - line_point.x)?;
1532        let utf8_index = self.display_to_source_index(display_index)?;
1533        Some(self.offset_to_utf16(utf8_index))
1534    }
1535}
1536
1537/// Custom element for rendering the input text with cursor and selection.
1538/// This is THE KEY to text input - it calls window.handle_input() in the paint method
1539struct InputTextElement {
1540    input: Entity<InputState>,
1541}
1542
1543struct PrepaintState {
1544    line: Option<gpui::ShapedLine>,
1545    cursor: Option<PaintQuad>,
1546    selection: Option<PaintQuad>,
1547}
1548
1549impl IntoElement for InputTextElement {
1550    type Element = Self;
1551
1552    fn into_element(self) -> Self::Element {
1553        self
1554    }
1555}
1556
1557impl gpui::Element for InputTextElement {
1558    type RequestLayoutState = ();
1559    type PrepaintState = PrepaintState;
1560
1561    fn id(&self) -> Option<ElementId> {
1562        None
1563    }
1564
1565    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1566        None
1567    }
1568
1569    fn request_layout(
1570        &mut self,
1571        _id: Option<&GlobalElementId>,
1572        _inspector_id: Option<&gpui::InspectorElementId>,
1573        window: &mut Window,
1574        cx: &mut App,
1575    ) -> (LayoutId, Self::RequestLayoutState) {
1576        let mut style = Style::default();
1577        style.size.width = relative(1.).into();
1578        style.size.height = window.line_height().into();
1579        (window.request_layout(style, [], cx), ())
1580    }
1581
1582    fn prepaint(
1583        &mut self,
1584        _id: Option<&GlobalElementId>,
1585        _inspector_id: Option<&gpui::InspectorElementId>,
1586        bounds: Bounds<Pixels>,
1587        _request_layout: &mut Self::RequestLayoutState,
1588        window: &mut Window,
1589        cx: &mut App,
1590    ) -> Self::PrepaintState {
1591        let input = self.input.read(cx);
1592        let (content, selected_range, cursor) = if input.masked {
1593            let char_count = input.content.chars().count();
1594            let masked_text = "•".repeat(char_count).into();
1595
1596            let start_chars = input.content[..input.selected_range.start].chars().count();
1597            let end_chars = input.content[..input.selected_range.end].chars().count();
1598            let masked_selected_range = (start_chars * "•".len())..(end_chars * "•".len());
1599
1600            let cursor_chars = if input.selection_reversed {
1601                start_chars
1602            } else {
1603                end_chars
1604            };
1605            let masked_cursor = cursor_chars * "•".len();
1606
1607            (masked_text, masked_selected_range, masked_cursor)
1608        } else {
1609            (
1610                input.content.clone(),
1611                input.selected_range.clone(),
1612                input.cursor_offset(),
1613            )
1614        };
1615        let style = window.text_style();
1616        let theme = use_theme(cx);
1617
1618        let (display_text, text_color) = if content.is_empty() {
1619            (input.placeholder.clone(), theme.tokens.muted_foreground)
1620        } else {
1621            (content, style.color)
1622        };
1623
1624        let run = TextRun {
1625            len: display_text.len(),
1626            font: style.font(),
1627            color: text_color,
1628            background_color: None,
1629            underline: None,
1630            strikethrough: None,
1631        };
1632
1633        let runs = if let Some(marked_range) = input.marked_range.as_ref() {
1634            let (marked_start, marked_end) = if input.masked {
1635                let start_chars = input.content[..marked_range.start].chars().count();
1636                let end_chars = input.content[..marked_range.end].chars().count();
1637                (start_chars * "•".len(), end_chars * "•".len())
1638            } else {
1639                (marked_range.start, marked_range.end)
1640            };
1641
1642            vec![
1643                TextRun {
1644                    len: marked_start,
1645                    ..run.clone()
1646                },
1647                TextRun {
1648                    len: marked_end - marked_start,
1649                    underline: Some(UnderlineStyle {
1650                        color: Some(run.color),
1651                        thickness: px(1.0),
1652                        wavy: false,
1653                    }),
1654                    ..run.clone()
1655                },
1656                TextRun {
1657                    len: display_text.len() - marked_end,
1658                    ..run
1659                },
1660            ]
1661            .into_iter()
1662            .filter(|run| run.len > 0)
1663            .collect()
1664        } else {
1665            vec![run]
1666        };
1667
1668        let font_size = style.font_size.to_pixels(window.rem_size());
1669        let line = window
1670            .text_system()
1671            .shape_line(display_text, font_size, &runs, None);
1672
1673        let cursor_pos = line.x_for_index(cursor);
1674        let (selection, cursor) = if selected_range.is_empty() {
1675            (
1676                None,
1677                Some(fill(
1678                    Bounds::new(
1679                        point(bounds.left() + cursor_pos, bounds.top()),
1680                        size(px(2.), bounds.bottom() - bounds.top()),
1681                    ),
1682                    theme.tokens.primary,
1683                )),
1684            )
1685        } else {
1686            (
1687                Some(fill(
1688                    Bounds::from_corners(
1689                        point(
1690                            bounds.left() + line.x_for_index(selected_range.start),
1691                            bounds.top(),
1692                        ),
1693                        point(
1694                            bounds.left() + line.x_for_index(selected_range.end),
1695                            bounds.bottom(),
1696                        ),
1697                    ),
1698                    theme.tokens.primary.opacity(0.25),
1699                )),
1700                None,
1701            )
1702        };
1703        PrepaintState {
1704            line: Some(line),
1705            cursor,
1706            selection,
1707        }
1708    }
1709
1710    fn paint(
1711        &mut self,
1712        _id: Option<&GlobalElementId>,
1713        _inspector_id: Option<&gpui::InspectorElementId>,
1714        bounds: Bounds<Pixels>,
1715        _request_layout: &mut Self::RequestLayoutState,
1716        prepaint: &mut Self::PrepaintState,
1717        window: &mut Window,
1718        cx: &mut App,
1719    ) {
1720        let focus_handle = self.input.read(cx).focus_handle.clone();
1721        let disabled = self.input.read(cx).disabled;
1722
1723        if !disabled {
1724            window.handle_input(
1725                &focus_handle,
1726                ElementInputHandler::new(bounds, self.input.clone()),
1727                cx,
1728            );
1729        }
1730
1731        if let Some(selection) = prepaint.selection.take() {
1732            window.paint_quad(selection)
1733        }
1734        let Some(line) = prepaint.line.take() else {
1735            return;
1736        };
1737        if line
1738            .paint(bounds.origin, window.line_height(), window, cx)
1739            .is_err()
1740        {
1741            return;
1742        }
1743
1744        let is_focused = focus_handle.is_focused(window);
1745        if is_focused {
1746            let cursor_visible = self.input.read(cx).cursor_visible;
1747            if cursor_visible {
1748                if let Some(cursor) = prepaint.cursor.take() {
1749                    window.paint_quad(cursor);
1750                }
1751            }
1752        }
1753
1754        self.input.update(cx, |input, cx| {
1755            input.last_layout = Some(line);
1756            input.last_bounds = Some(bounds);
1757            input.sync_focus_state(is_focused, window, cx);
1758        });
1759    }
1760}
1761
1762impl Render for InputState {
1763    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1764        let input = cx.entity();
1765
1766        div()
1767            .w_full()
1768            .h_full()
1769            .on_mouse_down(MouseButton::Left, {
1770                let input = input.clone();
1771                move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
1772                    input.update(cx, |input, cx| {
1773                        input.on_mouse_down(event, window, cx);
1774                    });
1775                }
1776            })
1777            .on_mouse_up(MouseButton::Left, {
1778                let input = input.clone();
1779                move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
1780                    input.update(cx, |input, cx| {
1781                        input.on_mouse_up(event, window, cx);
1782                    });
1783                }
1784            })
1785            .on_mouse_up_out(MouseButton::Left, {
1786                let input = input.clone();
1787                move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
1788                    input.update(cx, |input, cx| {
1789                        input.on_mouse_up(event, window, cx);
1790                    });
1791                }
1792            })
1793            .on_mouse_move({
1794                let input = input.clone();
1795                move |event: &MouseMoveEvent, window: &mut Window, cx: &mut App| {
1796                    input.update(cx, |input, cx| {
1797                        input.on_mouse_move(event, window, cx);
1798                    });
1799                }
1800            })
1801            .child(InputTextElement { input })
1802    }
1803}
1804
1805impl Focusable for InputState {
1806    fn focus_handle(&self, _: &App) -> FocusHandle {
1807        self.focus_handle.clone()
1808    }
1809}
1810
1811use regex;
1812
1813/// Wire a bare [`InputState`] into a custom container with full keyboard
1814/// editing, using the same wiring the `Input` component applies to its shell.
1815///
1816/// `InputState` renders only the text body (text, caret, selection, IME
1817/// underline). The editing keys are key bindings scoped to the `"Input"`
1818/// context and are attached by the `Input` component's container — a
1819/// container an application renders itself must reproduce that wiring, or
1820/// every editing key except plain text insertion silently does nothing.
1821/// This helper attaches:
1822///
1823/// - the `"Input"` key context the key bindings are filtered on,
1824/// - focus tracking for the state's focus handle (click-to-focus, tab order),
1825/// - all 20 keyboard actions, including word navigation, unless the state
1826///   is [`InputState::disabled`].
1827///
1828/// The returned div is an unstyled container; style it and add the state as
1829/// its child:
1830///
1831/// ```rust,ignore
1832/// use fc_ui::components::input_state::wire_actions;
1833///
1834/// fn render(state: &Entity<InputState>, window: &mut Window, cx: &App) -> impl IntoElement {
1835///     wire_actions(state, window, cx)
1836///         .h(px(36.0))
1837///         .px(px(12.0))
1838///         .rounded(px(8.0))
1839///         .child(state.clone())
1840/// }
1841/// ```
1842///
1843/// The key bindings are registered by `components::input::init`, which
1844/// `fc_ui::init` calls at startup; applications that skip crate init
1845/// must call it themselves or no keystroke will match an action.
1846pub fn wire_actions(state: &Entity<InputState>, window: &mut Window, cx: &App) -> Stateful<Div> {
1847    let disabled = state.read(cx).disabled;
1848    let focus_handle = state.read(cx).focus_handle(cx);
1849
1850    div()
1851        .id(("input", state.entity_id()))
1852        .key_context("Input")
1853        .track_focus(&focus_handle.tab_index(0).tab_stop(true))
1854        .when(!disabled, |this| {
1855            this.on_action(window.listener_for(state, InputState::backspace))
1856                .on_action(window.listener_for(state, InputState::delete))
1857                .on_action(window.listener_for(state, InputState::left))
1858                .on_action(window.listener_for(state, InputState::right))
1859                .on_action(window.listener_for(state, InputState::select_left))
1860                .on_action(window.listener_for(state, InputState::select_right))
1861                .on_action(window.listener_for(state, InputState::select_all))
1862                .on_action(window.listener_for(state, InputState::home))
1863                .on_action(window.listener_for(state, InputState::end))
1864                .on_action(window.listener_for(state, InputState::copy))
1865                .on_action(window.listener_for(state, InputState::cut))
1866                .on_action(window.listener_for(state, InputState::paste))
1867                .on_action(window.listener_for(state, InputState::enter))
1868                .on_action(window.listener_for(state, InputState::tab))
1869                .on_action(window.listener_for(state, InputState::shift_tab))
1870                .on_action(window.listener_for(state, InputState::escape))
1871                .on_action(window.listener_for(state, InputState::word_left))
1872                .on_action(window.listener_for(state, InputState::word_right))
1873                .on_action(window.listener_for(state, InputState::select_word_left))
1874                .on_action(window.listener_for(state, InputState::select_word_right))
1875        })
1876}
1877
1878#[cfg(test)]
1879mod tests {
1880    use super::*;
1881    use crate::capabilities::foundation::theme::{install_theme, Theme};
1882    use std::sync::Arc;
1883
1884    struct TestView {
1885        state: Entity<InputState>,
1886    }
1887
1888    impl Render for TestView {
1889        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1890            div()
1891        }
1892    }
1893
1894    #[gpui::test]
1895    fn builders_configure_common_state_options() {
1896        let mut app = TestApp::new();
1897        app.update(|cx| install_theme(cx, Theme::light()));
1898        let state = app.update(|cx| {
1899            cx.new(|cx| {
1900                InputState::new(cx)
1901                    .value("  hello  ")
1902                    .placeholder("p")
1903                    .disabled(true)
1904                    .select_on_focus(true)
1905                    .trim_on_blur(false)
1906            })
1907        });
1908
1909        app.update(|cx| {
1910            let state = state.read(cx);
1911            assert_eq!(state.content(), "  hello  ");
1912            assert_eq!(state.placeholder, "p");
1913            assert!(state.disabled);
1914            assert!(state.select_on_focus);
1915            assert!(!state.trim_on_blur);
1916        });
1917    }
1918
1919    #[gpui::test]
1920    fn word_left_moves_cursor_to_previous_word_boundary() {
1921        let mut app = TestApp::new();
1922        app.update(|cx| install_theme(cx, Theme::light()));
1923        let state = app.update(|cx| cx.new(InputState::new));
1924        let mut window = app.open_window(|_, _| TestView {
1925            state: state.clone(),
1926        });
1927
1928        let text = "foo bar baz";
1929        window.update(|view, window, cx| {
1930            view.state.update(cx, |state, cx| {
1931                state.set_value(text, window, cx);
1932                state.selected_range = text.len()..text.len();
1933                state.word_left(&WordLeft, window, cx);
1934                assert_eq!(state.selected_range, 8..8, "should stop before baz");
1935                state.word_left(&WordLeft, window, cx);
1936                assert_eq!(state.selected_range, 4..4, "should stop before bar");
1937                state.word_left(&WordLeft, window, cx);
1938                assert_eq!(state.selected_range, 0..0, "should reach start");
1939            });
1940        });
1941    }
1942
1943    #[gpui::test]
1944    fn word_right_moves_cursor_to_next_word_boundary() {
1945        let mut app = TestApp::new();
1946        app.update(|cx| install_theme(cx, Theme::light()));
1947        let state = app.update(|cx| cx.new(InputState::new));
1948        let mut window = app.open_window(|_, _| TestView {
1949            state: state.clone(),
1950        });
1951
1952        window.update(|view, window, cx| {
1953            view.state.update(cx, |state, cx| {
1954                state.set_value("foo bar baz", window, cx);
1955                state.selected_range = 0..0;
1956                state.word_right(&WordRight, window, cx);
1957                assert_eq!(state.selected_range, 4..4, "should stop at bar start");
1958                state.word_right(&WordRight, window, cx);
1959                assert_eq!(state.selected_range, 8..8, "should stop at baz start");
1960                state.word_right(&WordRight, window, cx);
1961                assert_eq!(state.selected_range, 11..11, "should reach end");
1962            });
1963        });
1964    }
1965
1966    #[gpui::test]
1967    fn word_movement_handles_unicode() {
1968        let mut app = TestApp::new();
1969        app.update(|cx| install_theme(cx, Theme::light()));
1970        let state = app.update(|cx| cx.new(InputState::new));
1971        let mut window = app.open_window(|_, _| TestView {
1972            state: state.clone(),
1973        });
1974
1975        let text = "中文 test";
1976        window.update(|view, window, cx| {
1977            view.state.update(cx, |state, cx| {
1978                state.set_value(text, window, cx);
1979                state.selected_range = text.len()..text.len();
1980                state.word_left(&WordLeft, window, cx);
1981                assert_eq!(state.selected_range, 7..7, "should stop before test");
1982                state.word_left(&WordLeft, window, cx);
1983                assert_eq!(state.selected_range, 0..0, "should reach start");
1984            });
1985        });
1986    }
1987
1988    #[gpui::test]
1989    fn ime_marked_replacement_maps_selection_into_inserted_text() {
1990        let mut app = TestApp::new();
1991        app.update(|cx| install_theme(cx, Theme::light()));
1992        let state = app.update(|cx| cx.new(InputState::new));
1993        let mut window = app.open_window(|_, _| TestView {
1994            state: state.clone(),
1995        });
1996
1997        window.update(|view, window, cx| {
1998            view.state.update(cx, |state, cx| {
1999                state.set_value("ab中文cd", window, cx);
2000                state.selected_range = 2..8; // "中文"
2001
2002                // IME 组字提交:替换非空选区;new_selected_range 是相对新插入文本的
2003                // UTF-16 区间,修复后的语义是 new_range + range.start
2004                state.replace_and_mark_text_in_range(None, "xy测试", Some(2..4), window, cx);
2005
2006                assert_eq!(state.content(), "abxy测试cd");
2007                // "xy测试" 的 UTF-16 2..4 == 其字节 2..8("测试"),再整体偏移到插入点 2
2008                let range = state.selected_range.clone();
2009                assert_eq!(range, 4..10);
2010                assert_eq!(&state.content()[range.clone()], "测试");
2011                assert!(state.content().is_char_boundary(range.start));
2012                assert!(state.content().is_char_boundary(range.end));
2013                assert_eq!(state.marked_range, Some(2..10));
2014                assert_eq!(
2015                    &state.content()[state.marked_range.clone().unwrap()],
2016                    "xy测试"
2017                );
2018            });
2019        });
2020    }
2021
2022    #[gpui::test]
2023    fn ime_commit_replacing_nonempty_selection_places_cursor_after_insert() {
2024        let mut app = TestApp::new();
2025        app.update(|cx| install_theme(cx, Theme::light()));
2026        let state = app.update(|cx| cx.new(InputState::new));
2027        let mut window = app.open_window(|_, _| TestView {
2028            state: state.clone(),
2029        });
2030
2031        window.update(|view, window, cx| {
2032            view.state.update(cx, |state, cx| {
2033                state.set_value("ab中文cd", window, cx);
2034                state.selected_range = 2..8; // "中文"
2035
2036                state.replace_text_in_range(None, "新字", window, cx);
2037
2038                assert_eq!(state.content(), "ab新字cd");
2039                assert_eq!(state.selected_range, 8..8);
2040                assert!(state.content().is_char_boundary(state.selected_range.start));
2041            });
2042        });
2043    }
2044
2045    #[gpui::test]
2046    fn validation_pattern_is_enforced() {
2047        let mut app = TestApp::new();
2048        app.update(|cx| install_theme(cx, Theme::light()));
2049        let state = app.update(|cx| cx.new(InputState::new));
2050        let mut window = app.open_window(|_, _| TestView {
2051            state: state.clone(),
2052        });
2053
2054        window.update(|view, window, cx| {
2055            view.state.update(cx, |state, cx| {
2056                state.validation_rules.pattern = Some(r"^[A-Z]{3}-\d{4}$".into());
2057                state.set_value("ABC-1234", window, cx);
2058                assert!(state.validate(cx).is_ok());
2059
2060                state.set_value("abc-1234", window, cx);
2061                assert!(state.validate(cx).is_err());
2062            });
2063        });
2064    }
2065
2066    #[gpui::test]
2067    fn custom_formatter_supports_editing_and_clear() {
2068        let mut app = TestApp::new();
2069        app.update(|cx| install_theme(cx, Theme::light()));
2070        let state = app.update(|cx| cx.new(InputState::new));
2071        let mut window = app.open_window(|_, _| TestView {
2072            state: state.clone(),
2073        });
2074
2075        window.update(|view, window, cx| {
2076            view.state.update(cx, |state, cx| {
2077                state.validation_rules.custom_formatter = Some(Arc::new(|value| {
2078                    format!("${:.2}", value.parse::<f64>().unwrap_or(0.0))
2079                }));
2080                state.set_value("12", window, cx);
2081                assert_eq!(state.content(), "$12.00");
2082
2083                state.replace_text_in_range(None, "3", window, cx);
2084                assert_eq!(state.content(), "$123.00");
2085
2086                state.set_value("", window, cx);
2087                assert!(state.content().is_empty());
2088            });
2089        });
2090    }
2091
2092    #[gpui::test]
2093    fn formatter_preserves_middle_cursor_position() {
2094        let mut app = TestApp::new();
2095        app.update(|cx| install_theme(cx, Theme::light()));
2096        let state = app.update(|cx| cx.new(InputState::new));
2097        let mut window = app.open_window(|_, _| TestView {
2098            state: state.clone(),
2099        });
2100
2101        window.update(|view, window, cx| {
2102            view.state.update(cx, |state, cx| {
2103                state.validation_rules.custom_formatter = Some(Arc::new(|value| value.to_owned()));
2104                state.set_value("abcd", window, cx);
2105                state.selected_range = 1..1;
2106
2107                state.replace_text_in_range(None, "X", window, cx);
2108
2109                assert_eq!(state.content(), "aXbcd");
2110                assert_eq!(state.selected_range, 2..2);
2111            });
2112        });
2113    }
2114
2115    #[gpui::test]
2116    fn formatter_cursor_mapping_handles_inserted_separators_and_affixes() {
2117        assert_eq!(
2118            InputState::raw_to_display_index("1234", "1,234", 2),
2119            3,
2120            "the cursor after raw `12` should move past the grouping separator"
2121        );
2122        assert_eq!(InputState::display_to_raw_index("1234", "1,234", 3), 2);
2123        assert_eq!(InputState::raw_to_display_index("12", "$12.00", 0), 1);
2124        assert_eq!(InputState::raw_to_display_index("12", "$12.00", 2), 6);
2125        assert_eq!(InputState::display_to_raw_index("12", "$12.00", 6), 2);
2126    }
2127
2128    #[gpui::test]
2129    fn formatter_cursor_mapping_uses_character_boundaries_for_unicode_expansion() {
2130        // `İ`.to_lowercase() expands to two display characters (`i` plus a
2131        // combining dot), whose UTF-8 length is three bytes.  Both ends of
2132        // the raw value must map to display character boundaries.
2133        let raw = "İ";
2134        let display = "i\u{307}";
2135        assert_eq!(InputState::raw_to_display_index(raw, display, 0), 0);
2136        assert_eq!(
2137            InputState::raw_to_display_index(raw, display, raw.len()),
2138            display.len()
2139        );
2140        assert_eq!(InputState::display_to_raw_index(raw, display, 0), 0);
2141        assert_eq!(
2142            InputState::display_to_raw_index(raw, display, display.len()),
2143            raw.len()
2144        );
2145        assert!(display.is_char_boundary(InputState::raw_to_display_index(
2146            raw,
2147            display,
2148            raw.len()
2149        )));
2150    }
2151
2152    #[gpui::test]
2153    fn formatter_cursor_mapping_falls_back_for_reordered_text() {
2154        // A reverse formatter has no monotonic raw/display inverse.  The
2155        // mapping remains monotonic and usable for editing instead of using
2156        // the first accidental character match as an anchor.
2157        let raw = "abcd";
2158        let display = "dcba";
2159        assert_eq!(InputState::raw_to_display_index(raw, display, 0), 0);
2160        assert_eq!(
2161            InputState::raw_to_display_index(raw, display, raw.len()),
2162            display.len()
2163        );
2164        assert_eq!(InputState::display_to_raw_index(raw, display, 0), 0);
2165        assert_eq!(
2166            InputState::display_to_raw_index(raw, display, display.len()),
2167            raw.len()
2168        );
2169    }
2170
2171    #[gpui::test]
2172    fn set_value_replaces_raw_text_when_formatter_hides_display() {
2173        let mut app = TestApp::new();
2174        app.update(|cx| install_theme(cx, Theme::light()));
2175        let state = app.update(|cx| cx.new(InputState::new));
2176        let mut window = app.open_window(|_, _| TestView {
2177            state: state.clone(),
2178        });
2179
2180        window.update(|view, window, cx| {
2181            view.state.update(cx, |state, cx| {
2182                state.validation_rules.custom_formatter = Some(Arc::new(|_| String::new()));
2183                state.set_value("first", window, cx);
2184                assert_eq!(state.raw_value(), "first");
2185                assert!(state.content().is_empty());
2186
2187                state.set_value("second", window, cx);
2188                assert_eq!(state.raw_value(), "second");
2189                assert!(state.content().is_empty());
2190            });
2191        });
2192    }
2193
2194    #[gpui::test]
2195    fn removing_a_formatter_restores_the_raw_display_value() {
2196        let mut app = TestApp::new();
2197        app.update(|cx| install_theme(cx, Theme::light()));
2198        let state = app.update(|cx| cx.new(InputState::new));
2199        let mut window = app.open_window(|_, _| TestView {
2200            state: state.clone(),
2201        });
2202
2203        window.update(|view, window, cx| {
2204            view.state.update(cx, |state, cx| {
2205                state.validation_rules.custom_formatter =
2206                    Some(Arc::new(|value| format!("${value}")));
2207                state.set_value("12", window, cx);
2208                state.validation_rules.custom_formatter = None;
2209                state.refresh_formatted_content();
2210
2211                assert_eq!(state.content(), "12");
2212            });
2213        });
2214    }
2215
2216    #[gpui::test]
2217    fn formatter_is_applied_when_ime_composition_ends() {
2218        let mut app = TestApp::new();
2219        app.update(|cx| install_theme(cx, Theme::light()));
2220        let state = app.update(|cx| cx.new(InputState::new));
2221        let mut window = app.open_window(|_, _| TestView {
2222            state: state.clone(),
2223        });
2224
2225        window.update(|view, window, cx| {
2226            view.state.update(cx, |state, cx| {
2227                state.validation_rules.custom_formatter =
2228                    Some(Arc::new(|value| value.to_uppercase()));
2229                state.replace_and_mark_text_in_range(None, "ab", None, window, cx);
2230                assert_eq!(state.content(), "ab");
2231
2232                state.unmark_text(window, cx);
2233
2234                assert_eq!(state.content(), "AB");
2235                assert!(state.marked_range.is_none());
2236            });
2237        });
2238    }
2239
2240    #[gpui::test]
2241    fn ime_commit_emits_change_when_composition_ends() {
2242        let mut app = TestApp::new();
2243        app.update(|cx| install_theme(cx, Theme::light()));
2244        let state = app.update(|cx| cx.new(InputState::new));
2245        let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2246        let changes_for_subscription = changes.clone();
2247        app.update(|cx| {
2248            cx.subscribe(&state, move |_emitter, event: &InputEvent, _cx| {
2249                if matches!(event, InputEvent::Change) {
2250                    changes_for_subscription.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2251                }
2252            })
2253            .detach();
2254        });
2255        let mut window = app.open_window(|_, _| TestView {
2256            state: state.clone(),
2257        });
2258
2259        window.update(|view, window, cx| {
2260            view.state.update(cx, |state, cx| {
2261                state.replace_and_mark_text_in_range(None, "ab", None, window, cx);
2262                assert_eq!(
2263                    changes.load(std::sync::atomic::Ordering::SeqCst),
2264                    0,
2265                    "composition updates should not emit a committed change"
2266                );
2267                state.unmark_text(window, cx);
2268            });
2269        });
2270
2271        assert_eq!(
2272            changes.load(std::sync::atomic::Ordering::SeqCst),
2273            1,
2274            "ending composition should emit one committed change"
2275        );
2276    }
2277
2278    #[gpui::test]
2279    fn externally_changed_public_content_is_used_as_the_next_raw_value() {
2280        let mut app = TestApp::new();
2281        app.update(|cx| install_theme(cx, Theme::light()));
2282        let state = app.update(|cx| cx.new(InputState::new));
2283        let mut window = app.open_window(|_, _| TestView {
2284            state: state.clone(),
2285        });
2286
2287        window.update(|view, window, cx| {
2288            view.state.update(cx, |state, cx| {
2289                state.validation_rules.custom_formatter =
2290                    Some(Arc::new(|value| format!("<{value}>")));
2291                state.set_value("12", window, cx);
2292                state.content = "34".into();
2293                state.selected_range = 2..2;
2294
2295                state.replace_text_in_range(None, "5", window, cx);
2296
2297                assert_eq!(state.content(), "<345>");
2298            });
2299        });
2300    }
2301
2302    #[gpui::test]
2303    fn invalid_validation_pattern_is_rejected() {
2304        let mut app = TestApp::new();
2305        app.update(|cx| install_theme(cx, Theme::light()));
2306        let state = app.update(|cx| cx.new(InputState::new));
2307        let mut window = app.open_window(|_, _| TestView {
2308            state: state.clone(),
2309        });
2310
2311        window.update(|view, window, cx| {
2312            view.state.update(cx, |state, cx| {
2313                state.validation_rules.pattern = Some("[".into());
2314                state.set_value("abc", window, cx);
2315
2316                let error = state.validate(cx).expect_err("invalid regex should fail");
2317                assert_eq!(error.message.as_ref(), "Invalid validation pattern");
2318            });
2319        });
2320    }
2321
2322    #[gpui::test]
2323    fn grapheme_deletion_removes_whole_unicode_clusters() {
2324        let mut app = TestApp::new();
2325        app.update(|cx| install_theme(cx, Theme::light()));
2326        let state = app.update(|cx| cx.new(InputState::new));
2327        let mut window = app.open_window(|_, _| TestView {
2328            state: state.clone(),
2329        });
2330
2331        window.update(|view, window, cx| {
2332            view.state.update(cx, |state, cx| {
2333                state.set_value("a👩‍💻e\u{301}b", window, cx);
2334                state.backspace(&Backspace, window, cx);
2335                assert_eq!(state.content(), "a👩‍💻e\u{301}");
2336                assert_eq!(
2337                    state.selected_range,
2338                    state.content().len()..state.content().len()
2339                );
2340
2341                state.backspace(&Backspace, window, cx);
2342                assert_eq!(state.content(), "a👩‍💻");
2343                assert_eq!(
2344                    state.selected_range,
2345                    state.content().len()..state.content().len()
2346                );
2347
2348                state.selected_range = "a".len().."a".len();
2349                state.selection_reversed = false;
2350                state.delete(&Delete, window, cx);
2351                assert_eq!(state.content(), "a");
2352                assert_eq!(state.selected_range, "a".len().."a".len());
2353            });
2354        });
2355    }
2356
2357    #[gpui::test]
2358    fn selection_direction_flips_when_crossing_the_anchor() {
2359        let mut app = TestApp::new();
2360        app.update(|cx| install_theme(cx, Theme::light()));
2361        let state = app.update(|cx| cx.new(InputState::new));
2362        let mut window = app.open_window(|_, _| TestView {
2363            state: state.clone(),
2364        });
2365
2366        window.update(|view, window, cx| {
2367            view.state.update(cx, |state, cx| {
2368                let text = "a😀b";
2369                let emoji_start = "a".len();
2370                let emoji_end = "a😀".len();
2371
2372                state.set_value(text, window, cx);
2373                state.selected_range = emoji_start..emoji_start;
2374                state.selection_reversed = false;
2375                state.select_right(&SelectRight, window, cx);
2376                assert_eq!(state.selected_range, emoji_start..emoji_end);
2377                assert!(!state.selection_reversed);
2378
2379                state.select_left(&SelectLeft, window, cx);
2380                assert_eq!(state.selected_range, emoji_start..emoji_start);
2381                assert!(!state.selection_reversed);
2382                state.select_left(&SelectLeft, window, cx);
2383                assert_eq!(state.selected_range, 0..emoji_start);
2384                assert!(state.selection_reversed);
2385
2386                state.selected_range = emoji_end..emoji_end;
2387                state.selection_reversed = false;
2388                state.select_left(&SelectLeft, window, cx);
2389                assert_eq!(state.selected_range, emoji_start..emoji_end);
2390                assert!(state.selection_reversed);
2391                state.select_right(&SelectRight, window, cx);
2392                assert_eq!(state.selected_range, emoji_end..emoji_end);
2393                assert!(state.selection_reversed);
2394                state.select_right(&SelectRight, window, cx);
2395                assert_eq!(state.selected_range, emoji_end..text.len());
2396                assert!(!state.selection_reversed);
2397            });
2398        });
2399    }
2400
2401    #[gpui::test]
2402    fn utf16_ranges_preserve_astral_character_boundaries() {
2403        let mut app = TestApp::new();
2404        app.update(|cx| install_theme(cx, Theme::light()));
2405        let state = app.update(|cx| cx.new(InputState::new));
2406        let mut window = app.open_window(|_, _| TestView {
2407            state: state.clone(),
2408        });
2409
2410        window.update(|view, window, cx| {
2411            view.state.update(cx, |state, cx| {
2412                state.set_value("a😀b", window, cx);
2413                let mut actual_range = None;
2414                assert_eq!(
2415                    state.text_for_range(1..3, &mut actual_range, window, cx),
2416                    Some("😀".to_string())
2417                );
2418                assert_eq!(actual_range, Some(1..3));
2419
2420                state.selected_range = "a".len().."a😀".len();
2421                let selected = state
2422                    .selected_text_range(false, window, cx)
2423                    .expect("selection should be available");
2424                assert_eq!(selected.range, 1..3);
2425                assert!(!selected.reversed);
2426
2427                state.replace_text_in_range(Some(1..3), "", window, cx);
2428                assert_eq!(state.content(), "ab");
2429                assert_eq!(state.selected_range, 1..1);
2430            });
2431        });
2432    }
2433    #[gpui::test]
2434    fn ime_composition_state_is_queryable() {
2435        let mut app = TestApp::new();
2436        app.update(|cx| install_theme(cx, Theme::light()));
2437        let state = app.update(|cx| cx.new(InputState::new));
2438        let mut window = app.open_window(|_, _| TestView {
2439            state: state.clone(),
2440        });
2441
2442        window.update(|view, window, cx| {
2443            view.state.update(cx, |state, cx| {
2444                state.set_value("hello", window, cx);
2445                assert!(!state.is_composing());
2446                assert_eq!(state.composition_char_count(), 0);
2447
2448                // IME starts composing "nihao" at the caret.
2449                state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
2450                assert!(state.is_composing());
2451                assert_eq!(state.composition_char_count(), 5);
2452                // Committed length excludes the in-flight composition.
2453                assert_eq!(
2454                    state.content().chars().count() - state.composition_char_count(),
2455                    5
2456                );
2457            });
2458        });
2459
2460        window.update(|view, window, cx| {
2461            view.state.update(cx, |state, cx| {
2462                // Committing the composed text ends the composition.
2463                state.replace_text_in_range(None, "你好", window, cx);
2464                assert!(!state.is_composing());
2465                assert_eq!(state.composition_char_count(), 0);
2466                assert_eq!(state.content(), "hello你好");
2467            });
2468        });
2469    }
2470}