Skip to main content

fc_ui/capabilities/controls/
input_state.rs

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