freya-components 0.5.0

Components for Freya apps
Documentation
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
use std::time::Duration;

use freya::prelude::*;
use freya_testing::prelude::*;

#[test]
fn input_setter_reducer_test() {
    use freya::radio::*;

    #[derive(Default)]
    struct AppState {
        equation: String,
        result: usize,
        edits: usize,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    enum AppChannel {
        Equation,
    }

    impl RadioChannel<AppState> for AppChannel {}

    enum AppAction {
        SetEquation(String),
    }

    impl DataReducer for AppState {
        type Channel = AppChannel;
        type Action = AppAction;

        fn reduce(&mut self, action: AppAction) -> ChannelSelection<AppChannel> {
            match action {
                AppAction::SetEquation(equation) => {
                    self.result = equation.len();
                    self.equation = equation;
                    self.edits += 1;
                }
            }

            ChannelSelection::Current
        }
    }

    fn app() -> impl IntoElement {
        use_init_radio_station::<AppState, AppChannel>(AppState::default);
        let mut radio = use_radio(AppChannel::Equation);

        rect()
            .child(
                Input::new(WritableSetter::new(
                    radio.slice_current(|state| &state.equation),
                    move |equation| {
                        radio.apply(AppAction::SetEquation(equation));
                    },
                ))
                .height(Size::px(40.)),
            )
            .child(
                rect()
                    .height(Size::px(40.))
                    .on_press(move |_| {
                        radio.apply(AppAction::SetEquation("external".to_string()));
                    })
                    .child("Replace"),
            )
            .child(format!(
                "{}:{}:{}",
                radio.read().equation,
                radio.read().result,
                radio.read().edits,
            ))
    }

    let mut test = launch_test(app);
    test.click_cursor((15., 15.));
    test.write_text("123");

    assert!(
        test.find(|_, element| {
            Label::try_downcast(element).filter(|label| label.text.as_ref() == "123:3:1")
        })
        .is_some()
    );

    test.click_cursor((15., 60.));

    assert!(
        test.find(|_, element| {
            Paragraph::try_downcast(element)
                .filter(|paragraph| paragraph.spans.iter().any(|span| span.text == "external"))
        })
        .is_some()
    );
    assert!(
        test.find(|_, element| {
            Label::try_downcast(element).filter(|label| label.text.as_ref() == "external:8:2")
        })
        .is_some()
    );
}

#[test]
fn input_setter_transform_and_reject_test() {
    fn app() -> impl IntoElement {
        let mut value = use_state(String::new);

        Input::new(WritableSetter::new(value, move |text: String| {
            if text
                .chars()
                .all(|character| character.is_ascii_alphabetic())
            {
                value.set(text.to_uppercase());
            }
        }))
    }

    let mut test = launch_test(app);
    test.click_cursor((15., 15.));
    test.write_text("a");
    test.write_text("1");

    assert!(
        test.find(|_, element| {
            Paragraph::try_downcast(element)
                .filter(|paragraph| paragraph.spans.iter().any(|span| span.text == "A"))
        })
        .is_some()
    );

    test.press_key(Key::Named(NamedKey::End));
    test.write_text("b");

    assert!(
        test.find(|_, element| {
            Paragraph::try_downcast(element)
                .filter(|paragraph| paragraph.spans.iter().any(|span| span.text == "AB"))
        })
        .is_some()
    );
}

#[test]
fn input_mutable_radio_slice_test() {
    use freya::radio::*;

    #[derive(Default)]
    struct AppState {
        text: String,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    enum AppChannel {
        Text,
    }

    impl RadioChannel<AppState> for AppChannel {}

    fn app() -> impl IntoElement {
        use_init_radio_station::<AppState, AppChannel>(AppState::default);
        let radio = use_radio(AppChannel::Text);

        rect()
            .child(Input::new(radio.slice_mut_current(|state| &mut state.text)))
            .child(format!("text={}", radio.read().text))
    }

    let mut test = launch_test(app);
    test.click_cursor((15., 15.));
    test.write_text("radio");

    assert!(
        test.find(|_, element| {
            Label::try_downcast(element).filter(|label| label.text.as_ref() == "text=radio")
        })
        .is_some()
    );
}

#[test]
pub fn input_test() {
    fn input_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .spacing(6.)
            .child(Input::new(value).placeholder("Type your name"))
            .child(format!("Your name is {}", value.read()))
    }

    let mut test = launch_test(input_app);

    let placeholder = test.find(|_, element| {
        Paragraph::try_downcast(element)
            .filter(|paragraph| paragraph.spans.iter().any(|s| s.text == "Type your name"))
    });
    assert!(placeholder.is_some());
    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "Your name is ")
    });
    assert!(label.is_some());

    // Focus
    test.click_cursor((15.0, 15.0));
    // Type
    test.write_text("Rust");

    let text = test.find(|_, element| {
        Paragraph::try_downcast(element)
            .filter(|paragraph| paragraph.spans.iter().any(|s| s.text == "Rust"))
    });
    assert!(text.is_some());
    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "Your name is Rust")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_password_mode_test() {
    fn password_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .child(Input::new(value).mode(InputMode::new_password()))
            .child(format!("value={}", value.read()))
    }

    let mut test = launch_test(password_app);

    // Focus and type
    test.click_cursor((15.0, 15.0));
    test.write_text("secret");

    // The rendered paragraph should show masked characters
    let masked = test.find(|_, element| {
        Paragraph::try_downcast(element)
            .filter(|paragraph| paragraph.spans.iter().any(|s| s.text == "******"))
    });
    assert!(masked.is_some());

    // But the underlying state should hold the real value
    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=secret")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_validator_test() {
    fn validator_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .child(
                Input::new(value).on_validate(move |validator: InputValidator| {
                    // Only allow numeric input
                    if !validator.text().chars().all(|c| c.is_ascii_digit()) {
                        validator.set_valid(false);
                    }
                }),
            )
            .child(format!("value={}", value.read()))
    }

    let mut test = launch_test(validator_app);

    // Focus
    test.click_cursor((15.0, 15.0));

    // Type invalid text (letters), should be rejected
    test.write_text("abc");

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=")
    });
    assert!(label.is_some());

    // Type valid text (digits), should be accepted
    test.write_text("123");

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=123")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_submit_test() {
    fn submit_app() -> impl IntoElement {
        let value = use_state(String::new);
        let mut submitted = use_state(String::new);

        rect()
            .child(Input::new(value).on_submit(move |text: String| {
                submitted.set(text);
            }))
            .child(format!("submitted={}", submitted.read()))
    }

    let mut test = launch_test(submit_app);

    // Focus and type
    test.click_cursor((15.0, 15.0));
    test.write_text("hello");

    // Not yet submitted
    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "submitted=")
    });
    assert!(label.is_some());

    // Press Enter to submit
    test.press_key(Key::Named(NamedKey::Enter));

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "submitted=hello")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_multiline_test() {
    fn multiline_app() -> impl IntoElement {
        let value = use_state(String::new);
        let mut submitted = use_state(|| false);

        rect()
            .child(
                Input::new(value)
                    .multiline(true)
                    .on_submit(move |_| submitted.set(true)),
            )
            .child(format!(
                "value={:?} submitted={}",
                value.read(),
                submitted.read()
            ))
    }

    let mut test = launch_test(multiline_app);

    // Focus and type two lines
    test.click_cursor((15.0, 15.0));
    test.write_text("hello");
    test.press_key(Key::Named(NamedKey::Enter));
    test.write_text("world");

    // Enter inserted a line break instead of submitting
    let label = test.find(|_, element| {
        Label::try_downcast(element)
            .filter(|label| label.text.as_ref() == "value=\"hello\\nworld\" submitted=false")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_multiline_fixed_height_follows_cursor_test() {
    fn multiline_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect().child(
            Input::new(value)
                .multiline(true)
                .width(Size::px(300.))
                .height(Size::px(60.)),
        )
    }

    let mut test = launch_test(multiline_app);
    test.click_cursor((15.0, 15.0));

    for line in 1..=6 {
        test.write_text("A line of text");
        test.press_key(Key::Named(NamedKey::Enter));
        test.sync_and_update();
        test.sync_and_update();

        if line >= 5 {
            let (paragraph_y, paragraph_height) = test
                .find(|node, element| {
                    Paragraph::try_downcast(element)
                        .map(|_| (node.layout().area.min_y(), node.layout().area.height()))
                })
                .expect("input paragraph should be present");
            assert!(
                paragraph_y < 0.0,
                "paragraph should scroll when text overflows"
            );
            assert!(
                paragraph_y + paragraph_height - 8.0 <= 61.0,
                "cursor line should remain visible, paragraph_y={paragraph_y} paragraph_height={paragraph_height}"
            );
        }
    }
}

#[test]
pub fn input_multiline_scrollbar_press_test() {
    fn scrollbar_app() -> impl IntoElement {
        let value = use_state(|| "One\nTwo\nThree\nFour\nFive\nSix\nSeven".to_string());

        rect().child(
            Input::new(value)
                .multiline(true)
                .width(Size::px(300.))
                .height(Size::px(120.)),
        )
    }

    let mut test = launch_test(scrollbar_app);
    test.sync_and_update();

    test.click_cursor((100.0, 40.0));
    test.press_cursor((292.0, 30.0));
    test.move_cursor((100.0, 90.0));
    test.sync_and_update();

    let highlights =
        test.find(|_, element| Some(Paragraph::try_downcast(element)?.highlights.clone()));
    assert_eq!(highlights, Some(vec![]));
}

#[test]
pub fn input_disabled_test() {
    fn disabled_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .child(Input::new(value).enabled(false))
            .child(format!("value={}", value.read()))
    }

    let mut test = launch_test(disabled_app);

    // Try to focus and type
    test.click_cursor((15.0, 15.0));
    test.write_text("hello");

    // Value should remain empty since input is disabled
    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_escape_unfocus_test() {
    fn escape_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .child(Input::new(value))
            .child(format!("value={}", value.read()))
    }

    let mut test = launch_test(escape_app);

    // Focus and type
    test.click_cursor((15.0, 15.0));
    test.write_text("hello");

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=hello")
    });
    assert!(label.is_some());

    // Press Escape to unfocus.
    test.press_key(Key::Named(NamedKey::Escape));
    test.sync_and_update();

    // Type more text, should not be captured since the input lost focus
    test.write_text("world");

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=hello")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_shift_wheel_scroll_test() {
    fn scroll_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect().child(Input::new(value).width(Size::px(150.)))
    }

    let mut test = launch_test(scroll_app);

    // Focus and fill with text wider than the input
    test.click_cursor((15.0, 15.0));
    test.write_text("this is a very long text that overflows the input width");
    test.sync_and_update();
    test.sync_and_update();

    let paragraph_x = |test: &TestingRunner| {
        test.find(|node, element| {
            Paragraph::try_downcast(element).map(|_| node.layout().area.min_x())
        })
        .unwrap()
    };

    // Move the cursor back to the start so the input is scrolled to the beginning
    test.press_key(Key::Named(NamedKey::Home));
    test.sync_and_update();
    let initial_x = paragraph_x(&test);

    // Hold Shift and wheel over the input to scroll it horizontally while focused
    test.send_event(PlatformEvent::Keyboard {
        name: KeyboardEventName::KeyDown,
        key: Key::Named(NamedKey::Shift),
        code: Code::ShiftLeft,
        modifiers: Modifiers::SHIFT,
    });
    test.sync_and_update();

    test.send_event(PlatformEvent::Wheel {
        name: WheelEventName::Wheel,
        scroll: (0.0, -50.0).into(),
        cursor: (75.0, 15.0).into(),
        source: WheelSource::Line,
        phase: TouchPhase::Moved,
    });
    test.sync_and_update();

    test.poll(Duration::from_millis(16), Duration::from_millis(500));

    let scrolled_x = paragraph_x(&test);
    assert!(scrolled_x < initial_x);
}

#[test]
pub fn input_drag_scrolls_to_cursor_test() {
    fn drag_app() -> impl IntoElement {
        let value =
            use_state(|| "this is a very long text that overflows the input width".to_string());

        rect().child(Input::new(value).width(Size::px(150.)))
    }

    let mut test = launch_test(drag_app);
    test.sync_and_update();

    let paragraph_x = |test: &TestingRunner| {
        test.find(|node, element| {
            Paragraph::try_downcast(element).map(|_| node.layout().area.min_x())
        })
        .unwrap()
    };
    let initial_x = paragraph_x(&test);

    test.press_cursor((100.0, 15.0));
    test.sync_and_update();
    test.move_cursor((170.0, 15.0));
    test.sync_and_update();

    let dragged_x = paragraph_x(&test);
    assert!(dragged_x < initial_x);
    assert!(initial_x - dragged_x < 100.0);

    // Dragging back past the left edge scrolls back to the beginning
    test.move_cursor((-500.0, 15.0));
    test.sync_and_update();

    assert_eq!(paragraph_x(&test), initial_x);

    test.release_cursor((-500.0, 15.0));
}

#[test]
pub fn input_auto_focus_test() {
    fn auto_focus_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect()
            .child(Input::new(value).auto_focus(true))
            .child(format!("value={}", value.read()))
    }

    let mut test = launch_test(auto_focus_app);

    test.sync_and_update();

    // Type without clicking, auto_focus should have focused the input
    test.write_text("typed");

    let label = test.find(|_, element| {
        Label::try_downcast(element).filter(|label| label.text.as_ref() == "value=typed")
    });
    assert!(label.is_some());
}

#[test]
pub fn input_long_typing_follows_cursor_test() {
    fn typing_app() -> impl IntoElement {
        let value = use_state(String::new);

        rect().child(Input::new(value).width(Size::px(150.)))
    }

    let mut test = launch_test(typing_app);

    let paragraph_metrics = |test: &TestingRunner| {
        test.find(|node, element| {
            Paragraph::try_downcast(element)
                .map(|_| (node.layout().area.min_x(), node.layout().area.width()))
        })
        .unwrap()
    };

    test.click_cursor((15.0, 15.0));
    let (initial_x, _) = paragraph_metrics(&test);

    // Keep typing way beyond the input width, the scroll must follow the cursor every time
    for _ in 0..20 {
        test.write_text("some more text ");
        test.sync_and_update();
        test.sync_and_update();

        let (min_x, width) = paragraph_metrics(&test);
        if width > 150.0 {
            let right_edge = min_x + width;
            assert!(
                (right_edge - 150.0).abs() < 2.0,
                "text end should stay at the right edge, min_x={min_x} width={width}"
            );
        }
    }

    // Moving the cursor back to the start scrolls the input back to the beginning
    test.press_key(Key::Named(NamedKey::Home));
    test.sync_and_update();

    let (home_x, _) = paragraph_metrics(&test);
    assert_eq!(home_x, initial_x);
}