Skip to main content

xrack_runtime/
text_input.rs

1use crate::{
2    ControlAction, InputRoute, Node, SpinDecimal, Value, combo_editable, decimal_separator,
3    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            _ => InputType::Text,
172        }
173    }
174
175    /// Check a proposed user edit, allowing incomplete numeric drafts.
176    pub fn allows_text_edit(&self, text: &str) -> bool {
177        self.allows_text_edit_with(
178            text,
179            self.input_type(),
180            || decimal_separator(self),
181            || self.int("maximum-length"),
182        )
183    }
184
185    /// Check live text constraints against the draft displayed by the input scene.
186    #[doc(hidden)]
187    pub fn try_allows_text_edit_with<E>(
188        &self,
189        text: &str,
190        mode: InputType,
191        separator: impl FnOnce() -> Result<char, E>,
192        maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
193    ) -> Result<bool, E> {
194        if !text_syntax_allows(text, mode, separator)? {
195            return Ok(false);
196        }
197        let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
198        Ok(limit.is_none_or(|limit| {
199            let length = text.graphemes(true).count();
200            // An external update can leave the value over its limit. Let edits repair it.
201            length <= limit || length < text_input_value(self).graphemes(true).count()
202        }))
203    }
204
205    #[doc(hidden)]
206    pub fn allows_text_edit_with(
207        &self,
208        text: &str,
209        mode: InputType,
210        separator: impl FnOnce() -> char,
211        maximum_length: impl FnOnce() -> Option<i64>,
212    ) -> bool {
213        self.try_allows_text_edit_with(
214            text,
215            mode,
216            || Ok::<_, std::convert::Infallible>(separator()),
217            || Ok(maximum_length()),
218        )
219        .unwrap_or_else(|error| match error {})
220    }
221
222    #[doc(hidden)]
223    pub fn accepts_editor_update(&self, text: &str) -> bool {
224        (is_text_input(self.kind) || combo_editable(self))
225            && !self.boolean("read-only", false)
226            && text_input_value(self) != text
227            && self.allows_text_edit(text)
228    }
229
230    /// Reject an edit based on text replaced since the scene was prepared.
231    #[doc(hidden)]
232    pub fn try_prepare_text_edit<E>(
233        &self,
234        input: InputRoute<'_>,
235        editable: impl FnOnce() -> Result<bool, E>,
236        current: impl FnOnce() -> Result<String, E>,
237        validate: impl FnOnce() -> Result<bool, E>,
238    ) -> Result<bool, E> {
239        if !input.try_available(editable)? {
240            return Ok(false);
241        }
242        // Keep the draft read in the route's watch, outside its availability
243        // watch. A linked table write checks its own field after reading history.
244        if current()? != text_input_value(self) {
245            return Ok(false);
246        }
247        input.try_available(validate)
248    }
249
250    #[doc(hidden)]
251    pub fn prepare_text_edit(
252        &self,
253        input: InputRoute<'_>,
254        editable: impl FnOnce() -> bool,
255        current: impl FnOnce() -> String,
256        validate: impl FnOnce() -> bool,
257    ) -> bool {
258        self.try_prepare_text_edit(
259            input,
260            || Ok::<_, std::convert::Infallible>(editable()),
261            || Ok(current()),
262            || Ok(validate()),
263        )
264        .unwrap_or_else(|error| match error {})
265    }
266
267    /// Check whether the current value can be submitted by an editor.
268    pub fn accepts_text_submission(&self) -> bool {
269        text_submission_is_valid(
270            text_input_value(self),
271            self.input_type(),
272            || decimal_separator(self),
273            || self.int("maximum-length"),
274        )
275    }
276}
277
278/// Validate a submitted value against the current editor bindings.
279#[doc(hidden)]
280pub fn try_text_submission_is_valid<E>(
281    text: &str,
282    mode: InputType,
283    separator: impl FnOnce() -> Result<char, E>,
284    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
285) -> Result<bool, E> {
286    if !text_syntax_allows(text, mode, separator)? {
287        return Ok(false);
288    }
289    let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
290    Ok(
291        limit.is_none_or(|limit| text.graphemes(true).nth(limit).is_none())
292            && (!matches!(mode, InputType::Number | InputType::Decimal)
293                || text.bytes().any(|byte| byte.is_ascii_digit())),
294    )
295}
296
297#[doc(hidden)]
298pub fn text_submission_is_valid(
299    text: &str,
300    mode: InputType,
301    separator: impl FnOnce() -> char,
302    maximum_length: impl FnOnce() -> Option<i64>,
303) -> bool {
304    try_text_submission_is_valid(
305        text,
306        mode,
307        || Ok::<_, std::convert::Infallible>(separator()),
308        || Ok(maximum_length()),
309    )
310    .unwrap_or_else(|error| match error {})
311}
312
313/// Optional numeric limits for a single-line editor's submitted value.
314#[doc(hidden)]
315#[derive(Default)]
316pub struct NumericTextLimits {
317    pub minimum: Option<f64>,
318    pub maximum: Option<f64>,
319    pub decimals: Option<i64>,
320}
321
322impl NumericTextLimits {
323    fn allows(self, text: &str, mode: InputType, separator: char) -> bool {
324        if let Some(places) = self
325            .decimals
326            .and_then(|places| usize::try_from(places).ok())
327            && text
328                .split_once(separator)
329                .is_some_and(|(_, fraction)| fraction.len() > places)
330        {
331            return false;
332        }
333        if self.minimum.is_none() && self.maximum.is_none() {
334            return true;
335        }
336        if mode == InputType::Number {
337            // Compare the digits to the integral bounds before any float
338            // conversion, so adjacent large integers remain distinct.
339            let digits = text.trim_start_matches('0');
340            let digits = if digits.is_empty() { "0" } else { digits };
341            let compare = |bound: f64| {
342                let bound = format!("{:.0}", bound.abs());
343                digits
344                    .len()
345                    .cmp(&bound.len())
346                    .then_with(|| digits.cmp(&bound))
347            };
348            return self.minimum.is_none_or(|minimum| {
349                minimum.is_finite() && (minimum <= 0.0 || compare(minimum.ceil()) != Ordering::Less)
350            }) && self.maximum.is_none_or(|maximum| {
351                maximum.is_finite()
352                    && maximum >= 0.0
353                    && compare(maximum.floor()) != Ordering::Greater
354            });
355        }
356        let Some(number) = SpinDecimal::parse(text, separator).map(SpinDecimal::get) else {
357            return false;
358        };
359        self.minimum
360            .is_none_or(|minimum| minimum.is_finite() && number >= minimum)
361            && self
362                .maximum
363                .is_none_or(|maximum| maximum.is_finite() && number <= maximum)
364    }
365}
366
367/// Evaluate final submission conditions in order, keeping later bindings lazy.
368#[doc(hidden)]
369pub fn try_text_submission_with<E>(
370    text: &str,
371    mode: InputType,
372    separator: impl FnOnce() -> Result<char, E>,
373    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
374    minimum_length: impl FnOnce() -> Result<i64, E>,
375    numeric_limits: impl FnOnce(InputType) -> Result<NumericTextLimits, E>,
376    submit_when: impl FnOnce() -> Result<bool, E>,
377) -> Result<bool, E> {
378    let separator = if mode == InputType::Decimal {
379        separator()?
380    } else {
381        '.'
382    };
383    if !try_text_submission_is_valid(text, mode, || Ok(separator), maximum_length)? {
384        return Ok(false);
385    }
386    let Ok(minimum) = usize::try_from(minimum_length()?.max(0)) else {
387        return Ok(false);
388    };
389    if minimum > text.len() || text.graphemes(true).take(minimum).count() != minimum {
390        return Ok(false);
391    }
392    if matches!(mode, InputType::Number | InputType::Decimal)
393        && !numeric_limits(mode)?.allows(text, mode, separator)
394    {
395        return Ok(false);
396    }
397    submit_when()
398}
399
400#[doc(hidden)]
401pub fn text_submission_with(
402    text: &str,
403    mode: InputType,
404    separator: impl FnOnce() -> char,
405    maximum_length: impl FnOnce() -> Option<i64>,
406    minimum_length: impl FnOnce() -> i64,
407    numeric_limits: impl FnOnce(InputType) -> NumericTextLimits,
408    submit_when: impl FnOnce() -> bool,
409) -> bool {
410    try_text_submission_with(
411        text,
412        mode,
413        || Ok::<_, std::convert::Infallible>(separator()),
414        || Ok(maximum_length()),
415        || Ok(minimum_length()),
416        |mode| Ok(numeric_limits(mode)),
417        || Ok(submit_when()),
418    )
419    .unwrap_or_else(|error| match error {})
420}
421
422fn text_syntax_allows<E>(
423    text: &str,
424    mode: InputType,
425    separator: impl FnOnce() -> Result<char, E>,
426) -> Result<bool, E> {
427    Ok(match mode {
428        InputType::Number => text.bytes().all(|byte| byte.is_ascii_digit()),
429        InputType::Decimal => spin_text_is_valid(text, Some(separator()?)),
430        InputType::Text | InputType::Password | InputType::Search => true,
431    })
432}