Skip to main content

xrack_runtime/
text_input.rs

1use crate::{
2    ControlAction, Node, Value, combo_editable, decimal_separator, is_text_input,
3    search_suggestion, spin_text_is_valid, text_input_value,
4};
5use unicode_segmentation::UnicodeSegmentation;
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8pub enum InputType {
9    #[default]
10    Text,
11    Password,
12    Number,
13    Decimal,
14    Search,
15}
16
17#[doc(hidden)]
18pub enum SearchInput {
19    Edit(String),
20    Submit(String),
21    Select { text: String, changed: bool },
22}
23
24#[doc(hidden)]
25pub enum SearchUpdate<'a> {
26    SetText(&'a str),
27    Edited(&'a str),
28    Accepted(&'a str),
29    Selected(&'a str),
30    Triggered(&'a str),
31}
32
33impl SearchInput {
34    /// Check the live field and preserve the query or suggestion from the input scene.
35    #[doc(hidden)]
36    pub fn try_from_control<E>(
37        node: &Node,
38        action: ControlAction,
39        available: impl FnOnce() -> Result<bool, E>,
40        editable: impl FnOnce() -> Result<bool, E>,
41        current: impl FnOnce() -> Result<String, E>,
42        result_query: impl FnOnce() -> Result<Option<String>, E>,
43        suggestion: impl FnOnce(usize) -> Result<Option<String>, E>,
44    ) -> Result<Option<Self>, E> {
45        if !matches!(
46            action,
47            ControlAction::SubmitSearch | ControlAction::Select(_) | ControlAction::ClearSearch
48        ) {
49            return Ok(None);
50        }
51        crate::property::watch_reads(|reads| {
52            if !available()? || reads.changed() {
53                return Ok(None);
54            }
55            let shown = text_input_value(node);
56            if action == ControlAction::SubmitSearch {
57                let query = current()?;
58                return Ok((query == shown && !reads.changed()).then_some(Self::Submit(query)));
59            }
60            if shown.is_empty()
61                || node.boolean("read-only", false)
62                || !editable()?
63                || reads.changed()
64                || current()? != shown
65                || reads.changed()
66            {
67                return Ok(None);
68            }
69            if action == ControlAction::ClearSearch {
70                return Ok(Some(Self::Edit(String::new())));
71            }
72            let ControlAction::Select(index) = action else {
73                return Ok(None);
74            };
75            let Some(candidate) = search_suggestion(node, index) else {
76                return Ok(None);
77            };
78            if result_query()?.is_some_and(|query| query != shown) || reads.changed() {
79                return Ok(None);
80            }
81            let Some(text) = suggestion(index)? else {
82                return Ok(None);
83            };
84            Ok(
85                (text == candidate && !reads.changed()).then(|| Self::Select {
86                    changed: text != shown,
87                    text,
88                }),
89            )
90        })
91    }
92
93    #[doc(hidden)]
94    pub fn from_control(
95        node: &Node,
96        action: ControlAction,
97        available: impl FnOnce() -> bool,
98        editable: impl FnOnce() -> bool,
99        current: impl FnOnce() -> String,
100        result_query: impl FnOnce() -> Option<String>,
101        suggestion: impl FnOnce(usize) -> Option<String>,
102    ) -> Option<Self> {
103        Self::try_from_control(
104            node,
105            action,
106            || Ok::<_, std::convert::Infallible>(available()),
107            || Ok(editable()),
108            || Ok(current()),
109            || Ok(result_query()),
110            |index| Ok(suggestion(index)),
111        )
112        .unwrap_or_else(|error| match error {})
113    }
114
115    #[doc(hidden)]
116    pub fn try_apply<E>(
117        self,
118        live: impl FnOnce() -> Result<bool, E>,
119        mut apply: impl FnMut(SearchUpdate<'_>) -> Result<bool, E>,
120    ) -> Result<bool, E> {
121        match self {
122            Self::Edit(text) => {
123                if !apply(SearchUpdate::SetText(&text))? {
124                    return Ok(false);
125                }
126                apply(SearchUpdate::Edited(&text))?;
127                if live()? {
128                    apply(SearchUpdate::Triggered(&text))?;
129                }
130            }
131            Self::Submit(text) => {
132                apply(SearchUpdate::Accepted(&text))?;
133                apply(SearchUpdate::Triggered(&text))?;
134            }
135            Self::Select { text, changed } => {
136                if changed {
137                    if !apply(SearchUpdate::SetText(&text))? {
138                        return Ok(false);
139                    }
140                    apply(SearchUpdate::Edited(&text))?;
141                }
142                apply(SearchUpdate::Selected(&text))?;
143                apply(SearchUpdate::Triggered(&text))?;
144            }
145        }
146        Ok(true)
147    }
148
149    #[doc(hidden)]
150    pub fn apply(
151        self,
152        live: impl FnOnce() -> bool,
153        mut apply: impl FnMut(SearchUpdate<'_>),
154    ) -> bool {
155        self.try_apply(
156            || Ok::<_, std::convert::Infallible>(live()),
157            |update| {
158                apply(update);
159                Ok(true)
160            },
161        )
162        .unwrap_or_else(|error| match error {})
163    }
164}
165
166impl Node {
167    pub fn input_type(&self) -> InputType {
168        match (self.kind, self.properties.get("input-type")) {
169            ("TextInput" | "LineEdit", Some(Value::InputType(mode))) => *mode,
170            _ => InputType::Text,
171        }
172    }
173
174    /// Check a proposed user edit, allowing incomplete numeric drafts.
175    pub fn allows_text_edit(&self, text: &str) -> bool {
176        self.allows_text_edit_with(
177            text,
178            self.input_type(),
179            || decimal_separator(self),
180            || self.int("maximum-length"),
181        )
182    }
183
184    /// Check live text constraints against the draft displayed by the input scene.
185    #[doc(hidden)]
186    pub fn try_allows_text_edit_with<E>(
187        &self,
188        text: &str,
189        mode: InputType,
190        separator: impl FnOnce() -> Result<char, E>,
191        maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
192    ) -> Result<bool, E> {
193        if !text_syntax_allows(text, mode, separator)? {
194            return Ok(false);
195        }
196        let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
197        Ok(limit.is_none_or(|limit| {
198            let length = text.graphemes(true).count();
199            // An external update can leave the value over its limit. Let edits repair it.
200            length <= limit || length < text_input_value(self).graphemes(true).count()
201        }))
202    }
203
204    #[doc(hidden)]
205    pub fn allows_text_edit_with(
206        &self,
207        text: &str,
208        mode: InputType,
209        separator: impl FnOnce() -> char,
210        maximum_length: impl FnOnce() -> Option<i64>,
211    ) -> bool {
212        self.try_allows_text_edit_with(
213            text,
214            mode,
215            || Ok::<_, std::convert::Infallible>(separator()),
216            || Ok(maximum_length()),
217        )
218        .unwrap_or_else(|error| match error {})
219    }
220
221    #[doc(hidden)]
222    pub fn accepts_editor_update(&self, text: &str) -> bool {
223        (is_text_input(self.kind) || combo_editable(self))
224            && !self.boolean("read-only", false)
225            && text_input_value(self) != text
226            && self.allows_text_edit(text)
227    }
228
229    /// Check whether the current value can be submitted by an editor.
230    pub fn accepts_text_submission(&self) -> bool {
231        text_submission_is_valid(
232            text_input_value(self),
233            self.input_type(),
234            || decimal_separator(self),
235            || self.int("maximum-length"),
236        )
237    }
238}
239
240/// Validate a submitted value against the current editor bindings.
241#[doc(hidden)]
242pub fn try_text_submission_is_valid<E>(
243    text: &str,
244    mode: InputType,
245    separator: impl FnOnce() -> Result<char, E>,
246    maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
247) -> Result<bool, E> {
248    if !text_syntax_allows(text, mode, separator)? {
249        return Ok(false);
250    }
251    let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
252    Ok(
253        limit.is_none_or(|limit| text.graphemes(true).nth(limit).is_none())
254            && (!matches!(mode, InputType::Number | InputType::Decimal)
255                || text.bytes().any(|byte| byte.is_ascii_digit())),
256    )
257}
258
259#[doc(hidden)]
260pub fn text_submission_is_valid(
261    text: &str,
262    mode: InputType,
263    separator: impl FnOnce() -> char,
264    maximum_length: impl FnOnce() -> Option<i64>,
265) -> bool {
266    try_text_submission_is_valid(
267        text,
268        mode,
269        || Ok::<_, std::convert::Infallible>(separator()),
270        || Ok(maximum_length()),
271    )
272    .unwrap_or_else(|error| match error {})
273}
274
275fn text_syntax_allows<E>(
276    text: &str,
277    mode: InputType,
278    separator: impl FnOnce() -> Result<char, E>,
279) -> Result<bool, E> {
280    Ok(match mode {
281        InputType::Number => text.bytes().all(|byte| byte.is_ascii_digit()),
282        InputType::Decimal => spin_text_is_valid(text, Some(separator()?)),
283        InputType::Text | InputType::Password | InputType::Search => true,
284    })
285}