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