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