xrack_runtime/
text_input.rs1use crate::{Node, Value, decimal_separator, spin_text_is_valid, text_input_value};
2use unicode_segmentation::UnicodeSegmentation;
3
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum InputType {
6 #[default]
7 Text,
8 Password,
9 Number,
10 Decimal,
11 Search,
12}
13
14impl Node {
15 pub fn input_type(&self) -> InputType {
16 match (self.kind, self.properties.get("input-type")) {
17 ("TextInput" | "LineEdit", Some(Value::InputType(mode))) => *mode,
18 _ => InputType::Text,
19 }
20 }
21
22 fn text_syntax_allows(&self, text: &str) -> bool {
23 match self.input_type() {
24 InputType::Number => text.bytes().all(|byte| byte.is_ascii_digit()),
25 InputType::Decimal => spin_text_is_valid(text, Some(decimal_separator(self))),
26 InputType::Text | InputType::Password | InputType::Search => true,
27 }
28 }
29
30 fn maximum_text_length(&self) -> Option<usize> {
31 usize::try_from(self.int("maximum-length")?).ok()
32 }
33
34 pub fn allows_text_edit(&self, text: &str) -> bool {
36 self.text_syntax_allows(text)
37 && self.maximum_text_length().is_none_or(|limit| {
38 let length = text.graphemes(true).count();
39 length <= limit || length < text_input_value(self).graphemes(true).count()
41 })
42 }
43
44 pub fn accepts_text_submission(&self) -> bool {
46 let text = text_input_value(self);
47 self.text_syntax_allows(text)
48 && self
49 .maximum_text_length()
50 .is_none_or(|limit| text.graphemes(true).nth(limit).is_none())
51 && (!matches!(self.input_type(), InputType::Number | InputType::Decimal)
52 || text.bytes().any(|byte| byte.is_ascii_digit()))
53 }
54}