raui_core/widget/component/interactive/
input_field.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::{
    pre_hooks, unpack_named_slots,
    view_model::ViewModelValue,
    widget::{
        component::interactive::{
            button::{use_button, ButtonProps},
            navigation::{use_nav_item, use_nav_text_input, NavSignal, NavTextChange},
        },
        context::{WidgetContext, WidgetMountOrChangeContext},
        node::WidgetNode,
        unit::area::AreaBoxNode,
        WidgetId, WidgetIdOrRef,
    },
    Integer, MessageData, PropsData, Scalar, UnsignedInteger,
};
use intuicio_data::managed::ManagedLazy;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

fn is_false(v: &bool) -> bool {
    !*v
}

fn is_zero(v: &usize) -> bool {
    *v == 0
}

pub trait TextInputProxy: Send + Sync {
    fn get(&self) -> String;
    fn set(&mut self, value: String);
}

impl<T> TextInputProxy for T
where
    T: ToString + FromStr + Send + Sync,
{
    fn get(&self) -> String {
        self.to_string()
    }

    fn set(&mut self, value: String) {
        if let Ok(value) = value.parse() {
            *self = value;
        }
    }
}

impl<T> TextInputProxy for ViewModelValue<T>
where
    T: ToString + FromStr + Send + Sync,
{
    fn get(&self) -> String {
        self.to_string()
    }

    fn set(&mut self, value: String) {
        if let Ok(value) = value.parse() {
            **self = value;
        }
    }
}

#[derive(Clone)]
pub struct TextInput(ManagedLazy<dyn TextInputProxy>);

impl TextInput {
    pub fn new(data: ManagedLazy<impl TextInputProxy + 'static>) -> Self {
        let (lifetime, data) = data.into_inner();
        let data = data as *mut dyn TextInputProxy;
        unsafe { Self(ManagedLazy::<dyn TextInputProxy>::new_raw(data, lifetime).unwrap()) }
    }

    pub fn into_inner(self) -> ManagedLazy<dyn TextInputProxy> {
        self.0
    }

    pub fn get(&self) -> String {
        self.0.read().map(|data| data.get()).unwrap_or_default()
    }

    pub fn set(&mut self, value: impl ToString) {
        if let Some(mut data) = self.0.write() {
            data.set(value.to_string());
        }
    }
}

impl std::fmt::Debug for TextInput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("TextInput")
            .field(&self.0.read().map(|data| data.get()).unwrap_or_default())
            .finish()
    }
}

impl<T: TextInputProxy + 'static> From<ManagedLazy<T>> for TextInput {
    fn from(value: ManagedLazy<T>) -> Self {
        Self::new(value)
    }
}

#[derive(PropsData, Debug, Default, Clone, Copy, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub enum TextInputMode {
    #[default]
    Text,
    Number,
    Integer,
    UnsignedInteger,
    #[serde(skip)]
    Filter(fn(usize, char) -> bool),
}

impl TextInputMode {
    pub fn is_text(&self) -> bool {
        matches!(self, Self::Text)
    }

    pub fn is_number(&self) -> bool {
        matches!(self, Self::Number)
    }

    pub fn is_integer(&self) -> bool {
        matches!(self, Self::Integer)
    }

    pub fn is_unsigned_integer(&self) -> bool {
        matches!(self, Self::UnsignedInteger)
    }

    pub fn is_filter(&self) -> bool {
        matches!(self, Self::Filter(_))
    }

    pub fn process(&self, text: &str) -> Option<String> {
        match self {
            Self::Text => Some(text.to_owned()),
            Self::Number => text.parse::<Scalar>().ok().map(|v| v.to_string()),
            Self::Integer => text.parse::<Integer>().ok().map(|v| v.to_string()),
            Self::UnsignedInteger => text.parse::<UnsignedInteger>().ok().map(|v| v.to_string()),
            Self::Filter(f) => {
                if text.char_indices().any(|(i, c)| !f(i, c)) {
                    None
                } else {
                    Some(text.to_owned())
                }
            }
        }
    }

    pub fn is_valid(&self, text: &str) -> bool {
        match self {
            Self::Text => true,
            Self::Number => text.parse::<Scalar>().is_ok() || text == "-",
            Self::Integer => text.parse::<Integer>().is_ok() || text == "-",
            Self::UnsignedInteger => text.parse::<UnsignedInteger>().is_ok(),
            Self::Filter(f) => text.char_indices().all(|(i, c)| f(i, c)),
        }
    }
}

#[derive(PropsData, Debug, Default, Clone, Copy, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct TextInputState {
    #[serde(default)]
    #[serde(skip_serializing_if = "is_false")]
    pub focused: bool,
    #[serde(default)]
    #[serde(skip_serializing_if = "is_zero")]
    pub cursor_position: usize,
}

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct TextInputProps {
    #[serde(default)]
    #[serde(skip_serializing_if = "is_false")]
    pub allow_new_line: bool,
    #[serde(default)]
    #[serde(skip)]
    pub text: Option<TextInput>,
}

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct TextInputNotifyProps(
    #[serde(default)]
    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
    pub WidgetIdOrRef,
);

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct TextInputControlNotifyProps(
    #[serde(default)]
    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
    pub WidgetIdOrRef,
);

#[derive(MessageData, Debug, Clone)]
#[message_data(crate::messenger::MessageData)]
pub struct TextInputNotifyMessage {
    pub sender: WidgetId,
    pub state: TextInputState,
    pub submitted: bool,
}

#[derive(MessageData, Debug, Clone)]
#[message_data(crate::messenger::MessageData)]
pub struct TextInputControlNotifyMessage {
    pub sender: WidgetId,
    pub character: char,
}

pub fn use_text_input_notified_state(context: &mut WidgetContext) {
    context.life_cycle.change(|context| {
        for msg in context.messenger.messages {
            if let Some(msg) = msg.as_any().downcast_ref::<TextInputNotifyMessage>() {
                let _ = context.state.write_with(msg.state.to_owned());
            }
        }
    });
}

#[pre_hooks(use_nav_text_input)]
pub fn use_text_input(context: &mut WidgetContext) {
    fn notify(context: &WidgetMountOrChangeContext, data: TextInputNotifyMessage) {
        if let Ok(notify) = context.props.read::<TextInputNotifyProps>() {
            if let Some(to) = notify.0.read() {
                context.messenger.write(to, data);
            }
        }
    }

    context.life_cycle.mount(|context| {
        notify(
            &context,
            TextInputNotifyMessage {
                sender: context.id.to_owned(),
                state: Default::default(),
                submitted: false,
            },
        );
        let _ = context.state.write_with(TextInputState::default());
    });

    context.life_cycle.change(|context| {
        let mode = context.props.read_cloned_or_default::<TextInputMode>();
        let mut props = context.props.read_cloned_or_default::<TextInputProps>();
        let mut state = context.state.read_cloned_or_default::<TextInputState>();
        let mut text = props
            .text
            .as_ref()
            .map(|text| text.get())
            .unwrap_or_default();
        let mut dirty_text = false;
        let mut dirty_state = false;
        let mut submitted = false;
        for msg in context.messenger.messages {
            if let Some(msg) = msg.as_any().downcast_ref() {
                match msg {
                    NavSignal::FocusTextInput(idref) => {
                        state.focused = idref.is_some();
                        dirty_state = true;
                    }
                    NavSignal::TextChange(change) => {
                        if state.focused {
                            match change {
                                NavTextChange::InsertCharacter(c) => {
                                    if c.is_control() {
                                        if let Ok(notify) =
                                            context.props.read::<TextInputControlNotifyProps>()
                                        {
                                            if let Some(to) = notify.0.read() {
                                                context.messenger.write(
                                                    to,
                                                    TextInputControlNotifyMessage {
                                                        sender: context.id.to_owned(),
                                                        character: *c,
                                                    },
                                                );
                                            }
                                        }
                                    } else {
                                        state.cursor_position =
                                            state.cursor_position.min(text.chars().count());
                                        let mut iter = text.chars();
                                        let mut new_text = iter
                                            .by_ref()
                                            .take(state.cursor_position)
                                            .collect::<String>();
                                        new_text.push(*c);
                                        new_text.extend(iter);
                                        if mode.is_valid(&new_text) {
                                            state.cursor_position += 1;
                                            text = new_text;
                                            dirty_text = true;
                                            dirty_state = true;
                                        }
                                    }
                                }
                                NavTextChange::MoveCursorLeft => {
                                    if state.cursor_position > 0 {
                                        state.cursor_position -= 1;
                                        dirty_state = true;
                                    }
                                }
                                NavTextChange::MoveCursorRight => {
                                    if state.cursor_position < text.chars().count() {
                                        state.cursor_position += 1;
                                        dirty_state = true;
                                    }
                                }
                                NavTextChange::MoveCursorStart => {
                                    state.cursor_position = 0;
                                    dirty_state = true;
                                }
                                NavTextChange::MoveCursorEnd => {
                                    state.cursor_position = text.chars().count();
                                    dirty_state = true;
                                }
                                NavTextChange::DeleteLeft => {
                                    if state.cursor_position > 0 {
                                        let mut iter = text.chars();
                                        let mut new_text = iter
                                            .by_ref()
                                            .take(state.cursor_position - 1)
                                            .collect::<String>();
                                        iter.by_ref().next();
                                        new_text.extend(iter);
                                        if mode.is_valid(&new_text) {
                                            state.cursor_position -= 1;
                                            text = new_text;
                                            dirty_text = true;
                                            dirty_state = true;
                                        }
                                    }
                                }
                                NavTextChange::DeleteRight => {
                                    let mut iter = text.chars();
                                    let mut new_text = iter
                                        .by_ref()
                                        .take(state.cursor_position)
                                        .collect::<String>();
                                    iter.by_ref().next();
                                    new_text.extend(iter);
                                    if mode.is_valid(&new_text) {
                                        text = new_text;
                                        dirty_text = true;
                                        dirty_state = true;
                                    }
                                }
                                NavTextChange::NewLine => {
                                    if props.allow_new_line {
                                        let mut iter = text.chars();
                                        let mut new_text = iter
                                            .by_ref()
                                            .take(state.cursor_position)
                                            .collect::<String>();
                                        new_text.push('\n');
                                        new_text.extend(iter);
                                        if mode.is_valid(&new_text) {
                                            state.cursor_position += 1;
                                            text = new_text;
                                            dirty_text = true;
                                            dirty_state = true;
                                        }
                                    } else {
                                        submitted = true;
                                        dirty_state = true;
                                    }
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
        if dirty_state {
            state.cursor_position = state.cursor_position.min(text.chars().count());
            notify(
                &context,
                TextInputNotifyMessage {
                    sender: context.id.to_owned(),
                    state,
                    submitted,
                },
            );
            let _ = context.state.write_with(state);
        }
        if dirty_text {
            if let Some(data) = props.text.as_mut() {
                data.set(text);
                context.messenger.write(context.id.to_owned(), ());
            }
        }
        if submitted {
            context.signals.write(NavSignal::FocusTextInput(().into()));
        }
    });
}

#[pre_hooks(use_button, use_text_input)]
pub fn use_input_field(context: &mut WidgetContext) {
    context.life_cycle.change(|context| {
        let focused = context
            .state
            .map_or_default::<TextInputState, _, _>(|s| s.focused);
        for msg in context.messenger.messages {
            if let Some(msg) = msg.as_any().downcast_ref() {
                match msg {
                    NavSignal::Accept(true) => {
                        if !focused {
                            context
                                .signals
                                .write(NavSignal::FocusTextInput(context.id.to_owned().into()));
                        }
                    }
                    NavSignal::Cancel(true) => {
                        if focused {
                            context.signals.write(NavSignal::FocusTextInput(().into()));
                        }
                    }
                    _ => {}
                }
            }
        }
    });
}

#[pre_hooks(use_nav_item, use_text_input)]
pub fn text_input(mut context: WidgetContext) -> WidgetNode {
    let WidgetContext {
        id,
        props,
        state,
        named_slots,
        ..
    } = context;
    unpack_named_slots!(named_slots => content);

    if let Some(p) = content.props_mut() {
        p.write(state.read_cloned_or_default::<TextInputState>());
        p.write(props.read_cloned_or_default::<TextInputProps>());
    }

    AreaBoxNode {
        id: id.to_owned(),
        slot: Box::new(content),
    }
    .into()
}

#[pre_hooks(use_nav_item, use_input_field)]
pub fn input_field(mut context: WidgetContext) -> WidgetNode {
    let WidgetContext {
        id,
        props,
        state,
        named_slots,
        ..
    } = context;
    unpack_named_slots!(named_slots => content);

    if let Some(p) = content.props_mut() {
        p.write(state.read_cloned_or_default::<ButtonProps>());
        p.write(state.read_cloned_or_default::<TextInputState>());
        p.write(props.read_cloned_or_default::<TextInputProps>());
    }

    AreaBoxNode {
        id: id.to_owned(),
        slot: Box::new(content),
    }
    .into()
}

pub fn input_text_with_cursor(text: &str, position: usize, cursor: char) -> String {
    text.chars()
        .take(position)
        .chain(std::iter::once(cursor))
        .chain(text.chars().skip(position))
        .collect()
}