Skip to main content

raui_core/widget/component/interactive/
input_field.rs

1use crate::{
2    Integer, MessageData, PropsData, Scalar, UnsignedInteger, pre_hooks, unpack_named_slots,
3    view_model::ViewModelValue,
4    widget::{
5        WidgetId, WidgetIdOrRef,
6        component::interactive::{
7            button::{ButtonProps, use_button},
8            navigation::{NavSignal, NavTextChange, use_nav_item, use_nav_text_input},
9        },
10        context::{WidgetContext, WidgetMountOrChangeContext},
11        node::WidgetNode,
12        unit::area::AreaBoxNode,
13    },
14};
15use intuicio_data::managed::ManagedLazy;
16use serde::{Deserialize, Serialize};
17use std::str::FromStr;
18
19fn is_false(v: &bool) -> bool {
20    !*v
21}
22
23fn is_zero(v: &usize) -> bool {
24    *v == 0
25}
26
27pub trait TextInputProxy: Send + Sync {
28    fn get(&self) -> String;
29    fn set(&mut self, value: String);
30}
31
32impl<T> TextInputProxy for T
33where
34    T: ToString + FromStr + Send + Sync,
35{
36    fn get(&self) -> String {
37        self.to_string()
38    }
39
40    fn set(&mut self, value: String) {
41        if let Ok(value) = value.parse() {
42            *self = value;
43        }
44    }
45}
46
47impl<T> TextInputProxy for ViewModelValue<T>
48where
49    T: ToString + FromStr + Send + Sync,
50{
51    fn get(&self) -> String {
52        self.to_string()
53    }
54
55    fn set(&mut self, value: String) {
56        if let Ok(value) = value.parse() {
57            **self = value;
58        }
59    }
60}
61
62#[derive(Clone)]
63pub struct TextInput(ManagedLazy<dyn TextInputProxy>);
64
65impl TextInput {
66    pub fn new(data: ManagedLazy<impl TextInputProxy + 'static>) -> Self {
67        let (lifetime, data) = data.into_inner();
68        let data = data as *mut dyn TextInputProxy;
69        unsafe { Self(ManagedLazy::<dyn TextInputProxy>::new_raw(data, lifetime).unwrap()) }
70    }
71
72    pub fn into_inner(self) -> ManagedLazy<dyn TextInputProxy> {
73        self.0
74    }
75
76    pub fn get(&self) -> String {
77        self.0.read().map(|data| data.get()).unwrap_or_default()
78    }
79
80    pub fn set(&mut self, value: impl ToString) {
81        if let Some(mut data) = self.0.write() {
82            data.set(value.to_string());
83        }
84    }
85}
86
87impl std::fmt::Debug for TextInput {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_tuple("TextInput")
90            .field(&self.0.read().map(|data| data.get()).unwrap_or_default())
91            .finish()
92    }
93}
94
95impl<T: TextInputProxy + 'static> From<ManagedLazy<T>> for TextInput {
96    fn from(value: ManagedLazy<T>) -> Self {
97        Self::new(value)
98    }
99}
100
101#[derive(PropsData, Debug, Default, Clone, Copy, Serialize, Deserialize)]
102#[props_data(crate::props::PropsData)]
103#[prefab(crate::Prefab)]
104pub enum TextInputMode {
105    #[default]
106    Text,
107    Number,
108    Integer,
109    UnsignedInteger,
110    #[serde(skip)]
111    Filter(fn(usize, char) -> bool),
112}
113
114impl TextInputMode {
115    pub fn is_text(&self) -> bool {
116        matches!(self, Self::Text)
117    }
118
119    pub fn is_number(&self) -> bool {
120        matches!(self, Self::Number)
121    }
122
123    pub fn is_integer(&self) -> bool {
124        matches!(self, Self::Integer)
125    }
126
127    pub fn is_unsigned_integer(&self) -> bool {
128        matches!(self, Self::UnsignedInteger)
129    }
130
131    pub fn is_filter(&self) -> bool {
132        matches!(self, Self::Filter(_))
133    }
134
135    pub fn process(&self, text: &str) -> Option<String> {
136        match self {
137            Self::Text => Some(text.to_owned()),
138            Self::Number => text.parse::<Scalar>().ok().map(|v| v.to_string()),
139            Self::Integer => text.parse::<Integer>().ok().map(|v| v.to_string()),
140            Self::UnsignedInteger => text.parse::<UnsignedInteger>().ok().map(|v| v.to_string()),
141            Self::Filter(f) => {
142                if text.char_indices().any(|(i, c)| !f(i, c)) {
143                    None
144                } else {
145                    Some(text.to_owned())
146                }
147            }
148        }
149    }
150
151    pub fn is_valid(&self, text: &str) -> bool {
152        match self {
153            Self::Text => true,
154            Self::Number => text.parse::<Scalar>().is_ok() || text == "-",
155            Self::Integer => text.parse::<Integer>().is_ok() || text == "-",
156            Self::UnsignedInteger => text.parse::<UnsignedInteger>().is_ok(),
157            Self::Filter(f) => text.char_indices().all(|(i, c)| f(i, c)),
158        }
159    }
160}
161
162#[derive(PropsData, Debug, Default, Clone, Copy, Serialize, Deserialize)]
163#[props_data(crate::props::PropsData)]
164#[prefab(crate::Prefab)]
165pub struct TextInputState {
166    #[serde(default)]
167    #[serde(skip_serializing_if = "is_false")]
168    pub focused: bool,
169    #[serde(default)]
170    #[serde(skip_serializing_if = "is_zero")]
171    pub cursor_position: usize,
172}
173
174#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
175#[props_data(crate::props::PropsData)]
176#[prefab(crate::Prefab)]
177pub struct TextInputProps {
178    #[serde(default)]
179    #[serde(skip_serializing_if = "is_false")]
180    pub allow_new_line: bool,
181    #[serde(default)]
182    #[serde(skip)]
183    pub text: Option<TextInput>,
184}
185
186#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
187#[props_data(crate::props::PropsData)]
188#[prefab(crate::Prefab)]
189pub struct TextInputNotifyProps(
190    #[serde(default)]
191    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
192    pub WidgetIdOrRef,
193);
194
195#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
196#[props_data(crate::props::PropsData)]
197#[prefab(crate::Prefab)]
198pub struct TextInputControlNotifyProps(
199    #[serde(default)]
200    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
201    pub WidgetIdOrRef,
202);
203
204#[derive(MessageData, Debug, Clone)]
205#[message_data(crate::messenger::MessageData)]
206pub struct TextInputNotifyMessage {
207    pub sender: WidgetId,
208    pub state: TextInputState,
209    pub submitted: bool,
210}
211
212#[derive(MessageData, Debug, Clone)]
213#[message_data(crate::messenger::MessageData)]
214pub struct TextInputControlNotifyMessage {
215    pub sender: WidgetId,
216    pub character: char,
217}
218
219pub fn use_text_input_notified_state(context: &mut WidgetContext) {
220    context.life_cycle.change(|context| {
221        for msg in context.messenger.messages {
222            if let Some(msg) = msg.as_any().downcast_ref::<TextInputNotifyMessage>() {
223                let _ = context.state.write_with(msg.state.to_owned());
224            }
225        }
226    });
227}
228
229#[pre_hooks(use_nav_text_input)]
230pub fn use_text_input(context: &mut WidgetContext) {
231    fn notify(context: &WidgetMountOrChangeContext, data: TextInputNotifyMessage) {
232        if let Ok(notify) = context.props.read::<TextInputNotifyProps>()
233            && let Some(to) = notify.0.read()
234        {
235            context.messenger.write(to, data);
236        }
237    }
238
239    context.life_cycle.mount(|context| {
240        notify(
241            &context,
242            TextInputNotifyMessage {
243                sender: context.id.to_owned(),
244                state: Default::default(),
245                submitted: false,
246            },
247        );
248        let _ = context.state.write_with(TextInputState::default());
249    });
250
251    context.life_cycle.change(|context| {
252        let mode = context.props.read_cloned_or_default::<TextInputMode>();
253        let mut props = context.props.read_cloned_or_default::<TextInputProps>();
254        let mut state = context.state.read_cloned_or_default::<TextInputState>();
255        let mut text = props
256            .text
257            .as_ref()
258            .map(|text| text.get())
259            .unwrap_or_default();
260        let mut dirty_text = false;
261        let mut dirty_state = false;
262        let mut submitted = false;
263        for msg in context.messenger.messages {
264            if let Some(msg) = msg.as_any().downcast_ref() {
265                match msg {
266                    NavSignal::FocusTextInput(idref) => {
267                        state.focused = idref.is_some();
268                        dirty_state = true;
269                    }
270                    NavSignal::TextChange(change) if state.focused => match change {
271                        NavTextChange::InsertCharacter(c) => {
272                            if c.is_control() {
273                                if let Ok(notify) =
274                                    context.props.read::<TextInputControlNotifyProps>()
275                                    && let Some(to) = notify.0.read()
276                                {
277                                    context.messenger.write(
278                                        to,
279                                        TextInputControlNotifyMessage {
280                                            sender: context.id.to_owned(),
281                                            character: *c,
282                                        },
283                                    );
284                                }
285                            } else {
286                                state.cursor_position =
287                                    state.cursor_position.min(text.chars().count());
288                                let mut iter = text.chars();
289                                let mut new_text = iter
290                                    .by_ref()
291                                    .take(state.cursor_position)
292                                    .collect::<String>();
293                                new_text.push(*c);
294                                new_text.extend(iter);
295                                if mode.is_valid(&new_text) {
296                                    state.cursor_position += 1;
297                                    text = new_text;
298                                    dirty_text = true;
299                                    dirty_state = true;
300                                }
301                            }
302                        }
303                        NavTextChange::MoveCursorLeft => {
304                            if state.cursor_position > 0 {
305                                state.cursor_position -= 1;
306                                dirty_state = true;
307                            }
308                        }
309                        NavTextChange::MoveCursorRight => {
310                            if state.cursor_position < text.chars().count() {
311                                state.cursor_position += 1;
312                                dirty_state = true;
313                            }
314                        }
315                        NavTextChange::MoveCursorStart => {
316                            state.cursor_position = 0;
317                            dirty_state = true;
318                        }
319                        NavTextChange::MoveCursorEnd => {
320                            state.cursor_position = text.chars().count();
321                            dirty_state = true;
322                        }
323                        NavTextChange::DeleteLeft => {
324                            if state.cursor_position > 0 {
325                                let mut iter = text.chars();
326                                let mut new_text = iter
327                                    .by_ref()
328                                    .take(state.cursor_position - 1)
329                                    .collect::<String>();
330                                iter.by_ref().next();
331                                new_text.extend(iter);
332                                if mode.is_valid(&new_text) {
333                                    state.cursor_position -= 1;
334                                    text = new_text;
335                                    dirty_text = true;
336                                    dirty_state = true;
337                                }
338                            }
339                        }
340                        NavTextChange::DeleteRight => {
341                            let mut iter = text.chars();
342                            let mut new_text = iter
343                                .by_ref()
344                                .take(state.cursor_position)
345                                .collect::<String>();
346                            iter.by_ref().next();
347                            new_text.extend(iter);
348                            if mode.is_valid(&new_text) {
349                                text = new_text;
350                                dirty_text = true;
351                                dirty_state = true;
352                            }
353                        }
354                        NavTextChange::NewLine => {
355                            if props.allow_new_line {
356                                let mut iter = text.chars();
357                                let mut new_text = iter
358                                    .by_ref()
359                                    .take(state.cursor_position)
360                                    .collect::<String>();
361                                new_text.push('\n');
362                                new_text.extend(iter);
363                                if mode.is_valid(&new_text) {
364                                    state.cursor_position += 1;
365                                    text = new_text;
366                                    dirty_text = true;
367                                    dirty_state = true;
368                                }
369                            } else {
370                                submitted = true;
371                                dirty_state = true;
372                            }
373                        }
374                    },
375                    _ => {}
376                }
377            }
378        }
379        if dirty_state {
380            state.cursor_position = state.cursor_position.min(text.chars().count());
381            notify(
382                &context,
383                TextInputNotifyMessage {
384                    sender: context.id.to_owned(),
385                    state,
386                    submitted,
387                },
388            );
389            let _ = context.state.write_with(state);
390        }
391        if dirty_text && let Some(data) = props.text.as_mut() {
392            data.set(text);
393            context.messenger.write(context.id.to_owned(), ());
394        }
395        if submitted {
396            context.signals.write(NavSignal::FocusTextInput(().into()));
397        }
398    });
399}
400
401#[pre_hooks(use_button, use_text_input)]
402pub fn use_input_field(context: &mut WidgetContext) {
403    context.life_cycle.change(|context| {
404        let focused = context
405            .state
406            .map_or_default::<TextInputState, _, _>(|s| s.focused);
407        for msg in context.messenger.messages {
408            if let Some(msg) = msg.as_any().downcast_ref() {
409                match msg {
410                    NavSignal::Accept(true) => {
411                        if !focused {
412                            context
413                                .signals
414                                .write(NavSignal::FocusTextInput(context.id.to_owned().into()));
415                        }
416                    }
417                    NavSignal::Cancel(true) if focused => {
418                        context.signals.write(NavSignal::FocusTextInput(().into()));
419                    }
420                    _ => {}
421                }
422            }
423        }
424    });
425}
426
427#[pre_hooks(use_nav_item, use_text_input)]
428pub fn text_input(mut context: WidgetContext) -> WidgetNode {
429    let WidgetContext {
430        id,
431        props,
432        state,
433        named_slots,
434        ..
435    } = context;
436    unpack_named_slots!(named_slots => content);
437
438    if let Some(p) = content.props_mut() {
439        p.write(state.read_cloned_or_default::<TextInputState>());
440        p.write(props.read_cloned_or_default::<TextInputProps>());
441    }
442
443    AreaBoxNode {
444        id: id.to_owned(),
445        slot: Box::new(content),
446    }
447    .into()
448}
449
450#[pre_hooks(use_nav_item, use_input_field)]
451pub fn input_field(mut context: WidgetContext) -> WidgetNode {
452    let WidgetContext {
453        id,
454        props,
455        state,
456        named_slots,
457        ..
458    } = context;
459    unpack_named_slots!(named_slots => content);
460
461    if let Some(p) = content.props_mut() {
462        p.write(state.read_cloned_or_default::<ButtonProps>());
463        p.write(state.read_cloned_or_default::<TextInputState>());
464        p.write(props.read_cloned_or_default::<TextInputProps>());
465    }
466
467    AreaBoxNode {
468        id: id.to_owned(),
469        slot: Box::new(content),
470    }
471    .into()
472}
473
474pub fn input_text_with_cursor(text: &str, position: usize, cursor: char) -> String {
475    text.chars()
476        .take(position)
477        .chain(std::iter::once(cursor))
478        .chain(text.chars().skip(position))
479        .collect()
480}