Skip to main content

xrack_runtime/
text_input.rs

1use crate::{
2    ControlAction, InputMask, InputRoute, InputValidity, Node, SpinDecimal, Value, combo_editable,
3    decimal_separator, is_text_input, search_suggestion, spin_text_is_valid, text_input_value,
4};
5use std::cmp::Ordering;
6use unicode_segmentation::UnicodeSegmentation;
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub enum InputType {
10    #[default]
11    Text,
12    Password,
13    Number,
14    Decimal,
15    Search,
16    Email,
17    Url,
18    Tel,
19}
20
21/// Native autofill hint for a single-line text editor.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum InputPurpose {
24    #[default]
25    Auto,
26    Username,
27    CurrentPassword,
28    NewPassword,
29    OneTimeCode,
30}
31
32/// Native keyboard capitalization requested by a text editor.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum KeyboardCapitalization {
35    #[default]
36    Auto,
37    None,
38    Words,
39    Sentences,
40    Characters,
41}
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub enum ReturnKey {
45    #[default]
46    Auto,
47    Next,
48    Done,
49}
50
51#[doc(hidden)]
52pub enum SearchInput {
53    Edit(String),
54    Submit(String),
55    Select { text: String, changed: bool },
56}
57
58#[doc(hidden)]
59pub enum SearchUpdate<'a> {
60    SetText(&'a str),
61    Edited(&'a str),
62    Accepted(&'a str),
63    Selected(&'a str),
64    Triggered(&'a str),
65}
66
67impl SearchInput {
68    /// Check the live field and preserve the query or suggestion from the input scene.
69    #[doc(hidden)]
70    pub fn try_from_control<E>(
71        node: &Node,
72        action: ControlAction,
73        available: impl FnOnce() -> Result<bool, E>,
74        editable: impl FnOnce() -> Result<bool, E>,
75        current: impl FnOnce() -> Result<String, E>,
76        result_query: impl FnOnce() -> Result<Option<String>, E>,
77        suggestion: impl FnOnce(usize) -> Result<Option<String>, E>,
78    ) -> Result<Option<Self>, E> {
79        if !matches!(
80            action,
81            ControlAction::SubmitSearch | ControlAction::Select(_) | ControlAction::ClearSearch
82        ) {
83            return Ok(None);
84        }
85        crate::property::watch_reads(|reads| {
86            if !available()? || reads.changed() {
87                return Ok(None);
88            }
89            let shown = text_input_value(node);
90            if action == ControlAction::SubmitSearch {
91                let query = current()?;
92                return Ok((query == shown && !reads.changed()).then_some(Self::Submit(query)));
93            }
94            if shown.is_empty()
95                || node.boolean("read-only", false)
96                || !editable()?
97                || reads.changed()
98                || current()? != shown
99                || reads.changed()
100            {
101                return Ok(None);
102            }
103            if action == ControlAction::ClearSearch {
104                return Ok(Some(Self::Edit(String::new())));
105            }
106            let ControlAction::Select(index) = action else {
107                return Ok(None);
108            };
109            let Some(candidate) = search_suggestion(node, index) else {
110                return Ok(None);
111            };
112            if result_query()?.is_some_and(|query| query != shown) || reads.changed() {
113                return Ok(None);
114            }
115            let Some(text) = suggestion(index)? else {
116                return Ok(None);
117            };
118            Ok(
119                (text == candidate && !reads.changed()).then(|| Self::Select {
120                    changed: text != shown,
121                    text,
122                }),
123            )
124        })
125    }
126
127    #[doc(hidden)]
128    pub fn from_control(
129        node: &Node,
130        action: ControlAction,
131        available: impl FnOnce() -> bool,
132        editable: impl FnOnce() -> bool,
133        current: impl FnOnce() -> String,
134        result_query: impl FnOnce() -> Option<String>,
135        suggestion: impl FnOnce(usize) -> Option<String>,
136    ) -> Option<Self> {
137        Self::try_from_control(
138            node,
139            action,
140            || Ok::<_, std::convert::Infallible>(available()),
141            || Ok(editable()),
142            || Ok(current()),
143            || Ok(result_query()),
144            |index| Ok(suggestion(index)),
145        )
146        .unwrap_or_else(|error| match error {})
147    }
148
149    #[doc(hidden)]
150    pub fn try_apply<E>(
151        self,
152        live: impl FnOnce() -> Result<bool, E>,
153        mut apply: impl FnMut(SearchUpdate<'_>) -> Result<bool, E>,
154    ) -> Result<bool, E> {
155        match self {
156            Self::Edit(text) => {
157                if !apply(SearchUpdate::SetText(&text))? {
158                    return Ok(false);
159                }
160                apply(SearchUpdate::Edited(&text))?;
161                if live()? {
162                    apply(SearchUpdate::Triggered(&text))?;
163                }
164            }
165            Self::Submit(text) => {
166                apply(SearchUpdate::Accepted(&text))?;
167                apply(SearchUpdate::Triggered(&text))?;
168            }
169            Self::Select { text, changed } => {
170                if changed {
171                    if !apply(SearchUpdate::SetText(&text))? {
172                        return Ok(false);
173                    }
174                    apply(SearchUpdate::Edited(&text))?;
175                }
176                apply(SearchUpdate::Selected(&text))?;
177                apply(SearchUpdate::Triggered(&text))?;
178            }
179        }
180        Ok(true)
181    }
182
183    #[doc(hidden)]
184    pub fn apply(
185        self,
186        live: impl FnOnce() -> bool,
187        mut apply: impl FnMut(SearchUpdate<'_>),
188    ) -> bool {
189        self.try_apply(
190            || Ok::<_, std::convert::Infallible>(live()),
191            |update| {
192                apply(update);
193                Ok(true)
194            },
195        )
196        .unwrap_or_else(|error| match error {})
197    }
198}
199
200impl Node {
201    pub fn input_type(&self) -> InputType {
202        match (self.kind, self.properties.get("input-type")) {
203            ("TextInput" | "LineEdit", Some(Value::InputType(mode))) => *mode,
204            ("ComboBox", Some(Value::InputType(mode))) if combo_editable(self) => *mode,
205            _ => InputType::Text,
206        }
207    }
208
209    pub fn input_purpose(&self) -> InputPurpose {
210        match (self.kind, self.properties.get("input-purpose")) {
211            ("TextInput" | "LineEdit", Some(Value::InputPurpose(purpose))) => *purpose,
212            ("ComboBox", Some(Value::InputPurpose(purpose))) if combo_editable(self) => *purpose,
213            _ => InputPurpose::Auto,
214        }
215    }
216
217    pub fn keyboard_capitalization(&self) -> KeyboardCapitalization {
218        match self.properties.get("keyboard-capitalization") {
219            Some(Value::KeyboardCapitalization(mode)) => *mode,
220            _ => KeyboardCapitalization::Auto,
221        }
222    }
223
224    pub fn return_key(&self) -> ReturnKey {
225        match (self.kind, self.properties.get("return-key")) {
226            ("TextInput" | "LineEdit", Some(Value::ReturnKey(key))) => *key,
227            ("ComboBox", Some(Value::ReturnKey(key))) if combo_editable(self) => *key,
228            _ => ReturnKey::Auto,
229        }
230    }
231
232    /// Whether to show the keyboard's previous and next field controls.
233    pub fn keyboard_navigation(&self) -> bool {
234        self.boolean("keyboard-navigation", self.return_key() != ReturnKey::Auto)
235    }
236
237    /// Check a proposed user edit, allowing incomplete numeric drafts.
238    pub fn allows_text_edit(&self, text: &str) -> bool {
239        self.allows_text_edit_with(
240            text,
241            self.input_type(),
242            || decimal_separator(self),
243            || self.int("maximum-length"),
244        )
245    }
246
247    /// Check live text constraints against the draft displayed by the input scene.
248    #[doc(hidden)]
249    pub fn try_allows_text_edit_with<E>(
250        &self,
251        text: &str,
252        mode: InputType,
253        separator: impl FnOnce() -> Result<char, E>,
254        maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
255    ) -> Result<bool, E> {
256        if !self
257            .text("input-mask")
258            .filter(|mask| !mask.is_empty())
259            .is_none_or(|mask| InputMask::parse(mask).is_some_and(|mask| mask.allows(text)))
260            || !text_syntax_allows(text, mode, separator)?
261        {
262            return Ok(false);
263        }
264        let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
265        let length_allowed = limit.is_none_or(|limit| {
266            let length = text.graphemes(true).count();
267            // An external update can leave the value over its limit. Let edits repair it.
268            length <= limit || length < text_input_value(self).graphemes(true).count()
269        });
270        Ok(length_allowed
271            && self
272                .text("input-pattern")
273                .is_none_or(|pattern| crate::input_pattern::input_pattern_allows(pattern, text)))
274    }
275
276    #[doc(hidden)]
277    pub fn allows_text_edit_with(
278        &self,
279        text: &str,
280        mode: InputType,
281        separator: impl FnOnce() -> char,
282        maximum_length: impl FnOnce() -> Option<i64>,
283    ) -> bool {
284        self.try_allows_text_edit_with(
285            text,
286            mode,
287            || Ok::<_, std::convert::Infallible>(separator()),
288            || Ok(maximum_length()),
289        )
290        .unwrap_or_else(|error| match error {})
291    }
292
293    #[doc(hidden)]
294    pub fn accepts_editor_update(&self, text: &str) -> bool {
295        (is_text_input(self.kind) || combo_editable(self))
296            && !self.boolean("read-only", false)
297            && text_input_value(self) != text
298            && self.allows_text_edit(text)
299    }
300
301    /// Reject an edit based on text replaced since the scene was prepared.
302    #[doc(hidden)]
303    pub fn try_prepare_text_edit<E>(
304        &self,
305        input: InputRoute<'_>,
306        editable: impl FnOnce() -> Result<bool, E>,
307        current: impl FnOnce() -> Result<String, E>,
308        validate: impl FnOnce() -> Result<bool, E>,
309    ) -> Result<bool, E> {
310        if !input.try_available(editable)? {
311            return Ok(false);
312        }
313        // Keep the draft read in the route's watch, outside its availability
314        // watch. A linked table write checks its own field after reading history.
315        if current()? != text_input_value(self) {
316            return Ok(false);
317        }
318        input.try_available(validate)
319    }
320
321    #[doc(hidden)]
322    pub fn prepare_text_edit(
323        &self,
324        input: InputRoute<'_>,
325        editable: impl FnOnce() -> bool,
326        current: impl FnOnce() -> String,
327        validate: impl FnOnce() -> bool,
328    ) -> bool {
329        self.try_prepare_text_edit(
330            input,
331            || Ok::<_, std::convert::Infallible>(editable()),
332            || Ok(current()),
333            || Ok(validate()),
334        )
335        .unwrap_or_else(|error| match error {})
336    }
337
338    /// Check whether the current value can be submitted by an editor.
339    pub fn accepts_text_submission(&self) -> bool {
340        let text = text_input_value(self);
341        self.text("input-mask")
342            .filter(|mask| !mask.is_empty())
343            .is_none_or(|mask| InputMask::parse(mask).is_some_and(|mask| mask.accepts(text)))
344            && text_submission_is_valid(
345                text,
346                self.input_type(),
347                || decimal_separator(self),
348                || self.int("maximum-length"),
349            )
350            && self
351                .text("input-pattern")
352                .is_none_or(|pattern| crate::input_pattern_accepts(pattern, text))
353    }
354}
355
356/// Validate a submitted value against the current editor bindings.
357#[doc(hidden)]
358pub fn try_text_submission_is_valid<E>(
359    text: &str,
360    mode: InputType,
361    separator: impl FnOnce() -> Result<char, E>,
362    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
363) -> Result<bool, E> {
364    if !text_syntax_allows(text, mode, separator)? {
365        return Ok(false);
366    }
367    let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
368    Ok(
369        limit.is_none_or(|limit| text.graphemes(true).nth(limit).is_none())
370            && submission_has_value(text, mode),
371    )
372}
373
374#[doc(hidden)]
375pub fn text_submission_is_valid(
376    text: &str,
377    mode: InputType,
378    separator: impl FnOnce() -> char,
379    maximum_length: impl FnOnce() -> Option<i64>,
380) -> bool {
381    try_text_submission_is_valid(
382        text,
383        mode,
384        || Ok::<_, std::convert::Infallible>(separator()),
385        || Ok(maximum_length()),
386    )
387    .unwrap_or_else(|error| match error {})
388}
389
390/// Optional numeric limits for a single-line editor's submitted value.
391#[doc(hidden)]
392#[derive(Default)]
393pub struct NumericTextLimits {
394    pub minimum: Option<f64>,
395    pub maximum: Option<f64>,
396    pub decimals: Option<i64>,
397}
398
399impl NumericTextLimits {
400    fn allows(self, text: &str, mode: InputType, separator: char) -> bool {
401        if let Some(places) = self
402            .decimals
403            .and_then(|places| usize::try_from(places).ok())
404            && text
405                .split_once(separator)
406                .is_some_and(|(_, fraction)| fraction.len() > places)
407        {
408            return false;
409        }
410        if self.minimum.is_none() && self.maximum.is_none() {
411            return true;
412        }
413        if mode == InputType::Number {
414            // Compare the digits to the integral bounds before any float
415            // conversion, so adjacent large integers remain distinct.
416            let digits = text.trim_start_matches('0');
417            let digits = if digits.is_empty() { "0" } else { digits };
418            let compare = |bound: f64| {
419                let bound = format!("{:.0}", bound.abs());
420                digits
421                    .len()
422                    .cmp(&bound.len())
423                    .then_with(|| digits.cmp(&bound))
424            };
425            return self.minimum.is_none_or(|minimum| {
426                minimum.is_finite() && (minimum <= 0.0 || compare(minimum.ceil()) != Ordering::Less)
427            }) && self.maximum.is_none_or(|maximum| {
428                maximum.is_finite()
429                    && maximum >= 0.0
430                    && compare(maximum.floor()) != Ordering::Greater
431            });
432        }
433        let Some(number) = SpinDecimal::parse(text, separator).map(SpinDecimal::get) else {
434            return false;
435        };
436        self.minimum
437            .is_none_or(|minimum| minimum.is_finite() && number >= minimum)
438            && self
439                .maximum
440                .is_none_or(|maximum| maximum.is_finite() && number <= maximum)
441    }
442}
443
444/// Evaluate final submission conditions in order, keeping later bindings lazy.
445#[doc(hidden)]
446pub fn try_text_submission_with<E>(
447    text: &str,
448    mode: InputType,
449    separator: impl FnOnce() -> Result<char, E>,
450    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
451    minimum_length: impl FnOnce() -> Result<i64, E>,
452    numeric_limits: impl FnOnce(InputType) -> Result<NumericTextLimits, E>,
453    submit_when: impl FnOnce() -> Result<bool, E>,
454) -> Result<bool, E> {
455    try_text_submission_with_mask(
456        text,
457        mode,
458        separator,
459        maximum_length,
460        minimum_length,
461        numeric_limits,
462        || Ok(String::new()),
463        submit_when,
464    )
465}
466
467#[doc(hidden)]
468pub fn text_submission_with(
469    text: &str,
470    mode: InputType,
471    separator: impl FnOnce() -> char,
472    maximum_length: impl FnOnce() -> Option<i64>,
473    minimum_length: impl FnOnce() -> i64,
474    numeric_limits: impl FnOnce(InputType) -> NumericTextLimits,
475    submit_when: impl FnOnce() -> bool,
476) -> bool {
477    try_text_submission_with(
478        text,
479        mode,
480        || Ok::<_, std::convert::Infallible>(separator()),
481        || Ok(maximum_length()),
482        || Ok(minimum_length()),
483        |mode| Ok(numeric_limits(mode)),
484        || Ok(submit_when()),
485    )
486    .unwrap_or_else(|error| match error {})
487}
488
489pub fn try_text_submission_with_mask<E>(
490    text: &str,
491    mode: InputType,
492    separator: impl FnOnce() -> Result<char, E>,
493    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
494    minimum_length: impl FnOnce() -> Result<i64, E>,
495    numeric_limits: impl FnOnce(InputType) -> Result<NumericTextLimits, E>,
496    mask: impl FnOnce() -> Result<String, E>,
497    submit_when: impl FnOnce() -> Result<bool, E>,
498) -> Result<bool, E> {
499    let separator = if mode == InputType::Decimal {
500        separator()?
501    } else {
502        '.'
503    };
504    if !try_text_submission_is_valid(text, mode, || Ok(separator), maximum_length)? {
505        return Ok(false);
506    }
507    if !try_text_submission_limits(text, mode, separator, minimum_length, numeric_limits)? {
508        return Ok(false);
509    }
510    let mask = mask()?;
511    if !mask.is_empty() && !InputMask::parse(&mask).is_some_and(|pattern| pattern.accepts(text)) {
512        return Ok(false);
513    }
514    submit_when()
515}
516
517fn submission_has_value(text: &str, mode: InputType) -> bool {
518    !matches!(mode, InputType::Number | InputType::Decimal)
519        || text.bytes().any(|byte| byte.is_ascii_digit())
520}
521
522fn try_text_submission_limits<E>(
523    text: &str,
524    mode: InputType,
525    separator: char,
526    minimum_length: impl FnOnce() -> Result<i64, E>,
527    numeric_limits: impl FnOnce(InputType) -> Result<NumericTextLimits, E>,
528) -> Result<bool, E> {
529    let Ok(minimum) = usize::try_from(minimum_length()?.max(0)) else {
530        return Ok(false);
531    };
532    if minimum > text.len() || text.graphemes(true).take(minimum).count() != minimum {
533        return Ok(false);
534    }
535    if matches!(mode, InputType::Number | InputType::Decimal)
536        && !numeric_limits(mode)?.allows(text, mode, separator)
537    {
538        return Ok(false);
539    }
540    Ok(true)
541}
542
543#[doc(hidden)]
544pub fn text_submission_with_mask(
545    text: &str,
546    mode: InputType,
547    separator: impl FnOnce() -> char,
548    maximum_length: impl FnOnce() -> Option<i64>,
549    minimum_length: impl FnOnce() -> i64,
550    numeric_limits: impl FnOnce(InputType) -> NumericTextLimits,
551    mask: impl FnOnce() -> String,
552    submit_when: impl FnOnce() -> bool,
553) -> bool {
554    try_text_submission_with_mask(
555        text,
556        mode,
557        || Ok::<_, std::convert::Infallible>(separator()),
558        || Ok(maximum_length()),
559        || Ok(minimum_length()),
560        |mode| Ok(numeric_limits(mode)),
561        || Ok(mask()),
562        || Ok(submit_when()),
563    )
564    .unwrap_or_else(|error| match error {})
565}
566
567#[doc(hidden)]
568pub fn try_text_input_validity<E>(
569    text: &str,
570    mode: InputType,
571    separator: impl FnOnce() -> Result<char, E>,
572    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
573    minimum_length: impl FnOnce() -> Result<i64, E>,
574    numeric_limits: impl FnOnce(InputType) -> Result<NumericTextLimits, E>,
575    mask: impl FnOnce() -> Result<String, E>,
576    pattern: impl FnOnce() -> Result<String, E>,
577    submit_when: impl FnOnce() -> Result<bool, E>,
578) -> Result<InputValidity, E> {
579    let separator = if mode == InputType::Decimal {
580        separator()?
581    } else {
582        '.'
583    };
584    if !text_syntax_allows(text, mode, || Ok(separator))?
585        || maximum_length()?
586            .and_then(|limit| usize::try_from(limit).ok())
587            .is_some_and(|limit| text.graphemes(true).nth(limit).is_some())
588    {
589        return Ok(InputValidity::Invalid);
590    }
591    let mask = mask()?;
592    let masked = if mask.is_empty() {
593        InputValidity::Acceptable
594    } else {
595        InputMask::parse(&mask).map_or(InputValidity::Invalid, |mask| mask.validity(text))
596    };
597    if masked == InputValidity::Invalid {
598        return Ok(InputValidity::Invalid);
599    }
600    let matched = crate::input_pattern::pattern_validity(&pattern()?, text);
601    if matched == InputValidity::Invalid {
602        return Ok(InputValidity::Invalid);
603    }
604    if masked == InputValidity::Acceptable
605        && matched == InputValidity::Acceptable
606        && submission_has_value(text, mode)
607        && try_text_submission_limits(text, mode, separator, minimum_length, numeric_limits)?
608        && submit_when()?
609    {
610        Ok(InputValidity::Acceptable)
611    } else {
612        Ok(InputValidity::Intermediate)
613    }
614}
615
616#[doc(hidden)]
617pub fn text_input_validity(
618    text: &str,
619    mode: InputType,
620    separator: impl FnOnce() -> char,
621    maximum_length: impl FnOnce() -> Option<i64>,
622    minimum_length: impl FnOnce() -> i64,
623    numeric_limits: impl FnOnce(InputType) -> NumericTextLimits,
624    mask: impl FnOnce() -> String,
625    pattern: impl FnOnce() -> String,
626    submit_when: impl FnOnce() -> bool,
627) -> InputValidity {
628    try_text_input_validity(
629        text,
630        mode,
631        || Ok::<_, std::convert::Infallible>(separator()),
632        || Ok(maximum_length()),
633        || Ok(minimum_length()),
634        |mode| Ok(numeric_limits(mode)),
635        || Ok(mask()),
636        || Ok(pattern()),
637        || Ok(submit_when()),
638    )
639    .unwrap_or_else(|error| match error {})
640}
641
642fn text_syntax_allows<E>(
643    text: &str,
644    mode: InputType,
645    separator: impl FnOnce() -> Result<char, E>,
646) -> Result<bool, E> {
647    Ok(match mode {
648        InputType::Number => text.bytes().all(|byte| byte.is_ascii_digit()),
649        InputType::Decimal => spin_text_is_valid(text, Some(separator()?)),
650        InputType::Text
651        | InputType::Password
652        | InputType::Search
653        | InputType::Email
654        | InputType::Url
655        | InputType::Tel => true,
656    })
657}