1use crate::{
2 ControlAction, InputRoute, 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 #[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 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 #[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 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 #[doc(hidden)]
231 pub fn try_prepare_text_edit<E>(
232 &self,
233 input: InputRoute<'_>,
234 editable: impl FnOnce() -> Result<bool, E>,
235 current: impl FnOnce() -> Result<String, E>,
236 validate: impl FnOnce() -> Result<bool, E>,
237 ) -> Result<bool, E> {
238 if !input.try_available(editable)? {
239 return Ok(false);
240 }
241 if current()? != text_input_value(self) {
244 return Ok(false);
245 }
246 input.try_available(validate)
247 }
248
249 #[doc(hidden)]
250 pub fn prepare_text_edit(
251 &self,
252 input: InputRoute<'_>,
253 editable: impl FnOnce() -> bool,
254 current: impl FnOnce() -> String,
255 validate: impl FnOnce() -> bool,
256 ) -> bool {
257 self.try_prepare_text_edit(
258 input,
259 || Ok::<_, std::convert::Infallible>(editable()),
260 || Ok(current()),
261 || Ok(validate()),
262 )
263 .unwrap_or_else(|error| match error {})
264 }
265
266 pub fn accepts_text_submission(&self) -> bool {
268 text_submission_is_valid(
269 text_input_value(self),
270 self.input_type(),
271 || decimal_separator(self),
272 || self.int("maximum-length"),
273 )
274 }
275}
276
277#[doc(hidden)]
279pub fn try_text_submission_is_valid<E>(
280 text: &str,
281 mode: InputType,
282 separator: impl FnOnce() -> Result<char, E>,
283 maximum_length: impl FnOnce() -> Result<Option<i64>, E>,
284) -> Result<bool, E> {
285 if !text_syntax_allows(text, mode, separator)? {
286 return Ok(false);
287 }
288 let limit = maximum_length()?.and_then(|limit| usize::try_from(limit).ok());
289 Ok(
290 limit.is_none_or(|limit| text.graphemes(true).nth(limit).is_none())
291 && (!matches!(mode, InputType::Number | InputType::Decimal)
292 || text.bytes().any(|byte| byte.is_ascii_digit())),
293 )
294}
295
296#[doc(hidden)]
297pub fn text_submission_is_valid(
298 text: &str,
299 mode: InputType,
300 separator: impl FnOnce() -> char,
301 maximum_length: impl FnOnce() -> Option<i64>,
302) -> bool {
303 try_text_submission_is_valid(
304 text,
305 mode,
306 || Ok::<_, std::convert::Infallible>(separator()),
307 || Ok(maximum_length()),
308 )
309 .unwrap_or_else(|error| match error {})
310}
311
312fn text_syntax_allows<E>(
313 text: &str,
314 mode: InputType,
315 separator: impl FnOnce() -> Result<char, E>,
316) -> Result<bool, E> {
317 Ok(match mode {
318 InputType::Number => text.bytes().all(|byte| byte.is_ascii_digit()),
319 InputType::Decimal => spin_text_is_valid(text, Some(separator()?)),
320 InputType::Text | InputType::Password | InputType::Search => true,
321 })
322}