tuirealm 4.0.0

A tui-rs framework to build tui interfaces, inspired by React and Elm.
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! This module exposes the View structure, which is the wrapper for all the components in an application.

use std::collections::HashMap;
use std::hash::Hash;

use ratatui::Frame;
use thiserror::Error;

use crate::component::AppComponent;
use crate::event::Event;
use crate::injector::Injector;
use crate::props::{AttrValue, Attribute, QueryResult};
use crate::ratatui::layout::Rect;
use crate::state::State;

/// A boxed component. Shorthand for View components map
pub(crate) type WrappedComponent<Msg, UserEvent> = Box<dyn AppComponent<Msg, UserEvent>>;

/// Result for view methods.
/// Returns a variable Ok and a ViewError in case of error.
pub type ViewResult<T> = Result<T, ViewError>;

/// An error returned by the view
#[derive(Debug, Error)]
pub enum ViewError {
    #[error("component already mounted")]
    ComponentAlreadyMounted,
    #[error("component not found")]
    ComponentNotFound,
    #[error("there's no component to blur")]
    NoComponentToBlur,
}

/// View is the wrapper and manager for all the components.
/// A View is a container for all the components in a certain layout.
/// Each View can have only one focused component at the time. At least one component must be always focused
pub struct View<ComponentId, Msg, UserEvent>
where
    ComponentId: Eq + PartialEq + Clone + Hash,
    Msg: PartialEq,
    UserEvent: Eq + PartialEq + Clone,
{
    /// Components Mounted onto View
    components: HashMap<ComponentId, WrappedComponent<Msg, UserEvent>>,
    /// Current active component
    focus: Option<ComponentId>,
    /// Focus stack; used to determine which component should hold focus in case the current element is blurred
    focus_stack: Vec<ComponentId>,
    /// Property injectors
    injectors: Vec<Box<dyn Injector<ComponentId>>>,
}

impl<ComponentId, Msg, UserEvent> Default for View<ComponentId, Msg, UserEvent>
where
    ComponentId: Eq + PartialEq + Clone + Hash,
    Msg: PartialEq,
    UserEvent: Eq + PartialEq + Clone,
{
    fn default() -> Self {
        Self {
            components: HashMap::new(),
            focus: None,
            focus_stack: Vec::new(),
            injectors: Vec::new(),
        }
    }
}

impl<ComponentId, Msg, UserEvent> View<ComponentId, Msg, UserEvent>
where
    ComponentId: Eq + PartialEq + Clone + Hash,
    Msg: PartialEq + 'static,
    UserEvent: Eq + PartialEq + Clone + 'static,
{
    /// Mount component on View.
    /// Returns error if the component is already mounted
    pub fn mount(
        &mut self,
        id: &ComponentId,
        component: WrappedComponent<Msg, UserEvent>,
    ) -> ViewResult<()> {
        if self.mounted(id) {
            Err(ViewError::ComponentAlreadyMounted)
        } else {
            // Insert
            self.components.insert(id.clone(), component);
            // Inject properties
            self.inject(id)
        }
    }

    /// Umount component from View
    pub fn umount(&mut self, id: &ComponentId) -> ViewResult<()> {
        if !self.mounted(id) {
            return Err(ViewError::ComponentNotFound);
        }
        if self.has_focus(id) {
            let _ = self.blur();
        }
        // Remove component from stack
        self.pop_from_stack(id);
        // Umount
        self.components.remove(id);
        Ok(())
    }

    /// Remount component. This method WON'T change the focus stack
    pub fn remount(
        &mut self,
        id: &ComponentId,
        component: WrappedComponent<Msg, UserEvent>,
    ) -> ViewResult<()> {
        // Umount, but keep focus
        let had_focus = self.has_focus(id);
        if self.mounted(id) {
            self.components.remove(id);
        }
        // remount
        self.components.insert(id.clone(), component);
        // Inject properties
        self.inject(id)?;
        // give focus if needed
        if had_focus { self.active(id) } else { Ok(()) }
    }

    /// Umount all components in the view and clear focus stack and state
    pub fn umount_all(&mut self) {
        self.components.clear();
        self.focus_stack.clear();
        self.focus = None;
    }

    /// Returns whether component `id` is mounted
    pub fn mounted(&self, id: &ComponentId) -> bool {
        self.components.contains_key(id)
    }

    /// Get a reference to the registered component for the given `id`, if there is one.
    pub fn get_component(&self, id: &ComponentId) -> Option<&dyn AppComponent<Msg, UserEvent>> {
        self.components.get(id).map(|v| &**v)
    }

    /// Get a mutable reference to the registered component for the given `id`, if there is one.
    pub fn get_component_mut(
        &mut self,
        id: &ComponentId,
    ) -> Option<&mut dyn AppComponent<Msg, UserEvent>> {
        self.components.get_mut(id).map(|v| &mut **v)
    }

    /// Returns current active element (if any)
    pub(crate) fn focus(&self) -> Option<&ComponentId> {
        self.focus.as_ref()
    }

    /// Render component called `id`
    pub fn view(&mut self, id: &ComponentId, f: &mut Frame, area: Rect) {
        if let Some(c) = self.components.get_mut(id) {
            c.view(f, area);
        }
    }

    /// Forward `event` (call `on()`) on component `id` and return a `Msg` if any.
    /// Returns error if the component doesn't exist
    pub(crate) fn forward(
        &mut self,
        id: &ComponentId,
        event: &Event<UserEvent>,
    ) -> ViewResult<Option<Msg>> {
        match self.components.get_mut(id) {
            None => Err(ViewError::ComponentNotFound),
            Some(c) => Ok(c.on(event)),
        }
    }

    /// Query view component for a certain `AttrValue`
    /// Returns error if the component doesn't exist
    /// Returns None if the attribute doesn't exist.
    pub fn query<'a>(
        &'a self,
        id: &ComponentId,
        query: Attribute,
    ) -> ViewResult<Option<QueryResult<'a>>> {
        match self.components.get(id) {
            None => Err(ViewError::ComponentNotFound),
            Some(c) => Ok(c.query(query)),
        }
    }

    /// Set attribute for component `id`
    /// Returns error if the component doesn't exist
    pub fn attr(&mut self, id: &ComponentId, attr: Attribute, value: AttrValue) -> ViewResult<()> {
        if let Some(c) = self.components.get_mut(id) {
            c.attr(attr, value);
            Ok(())
        } else {
            Err(ViewError::ComponentNotFound)
        }
    }

    /// Get state for component `id`.
    /// Returns `Err` if component doesn't exist
    pub fn state(&self, id: &ComponentId) -> ViewResult<State> {
        self.components
            .get(id)
            .map(|c| c.state())
            .ok_or(ViewError::ComponentNotFound)
    }

    // -- shorthands

    /// Shorthand for `attr(id, Attribute::Focus(AttrValue::Flag(true)))`.
    /// It also sets the component as the current one having focus.
    /// Previous active component, if any, GETS PUSHED to the STACK
    /// Returns error: if component doesn't exist. Use `mounted()` to check if component exists
    ///
    /// > NOTE: users should always use this function to give focus to components.
    pub fn active(&mut self, id: &ComponentId) -> ViewResult<()> {
        self.set_focus(id, true)?;
        self.change_focus(id);
        Ok(())
    }

    /// Blur selected element AND DON'T PUSH CURRENT ACTIVE ELEMENT INTO THE STACK
    /// Shorthand for `attr(id, Attribute::Focus(AttrValue::Flag(false)))`.
    /// It also unset the current focus and give it to the first element in stack.
    /// Returns error: if no component has focus
    ///
    /// > NOTE: users should always use this function to remove focus to components.
    pub fn blur(&mut self) -> ViewResult<()> {
        if let Some(id) = self.focus.take() {
            self.set_focus(&id, false)?;
            self.focus_to_last();
            Ok(())
        } else {
            Err(ViewError::NoComponentToBlur)
        }
    }

    // -- injectors

    /// Add an injector to the view
    pub fn add_injector(&mut self, injector: Box<dyn Injector<ComponentId>>) {
        self.injectors.push(injector);
    }

    // -- private

    /// Push component `id` to focus stack
    /// In case it is already in the focus stack,
    /// it will be first removed from it.
    fn push_to_stack(&mut self, id: ComponentId) {
        self.pop_from_stack(&id);
        self.focus_stack.push(id);
    }

    /// Pop component `id` from focus stack
    fn pop_from_stack(&mut self, id: &ComponentId) {
        self.focus_stack.retain(|x| x != id);
    }

    /// Returns whether `who` has focus
    pub(crate) fn has_focus(&self, who: &ComponentId) -> bool {
        match self.focus.as_ref() {
            None => false,
            Some(id) => who == id,
        }
    }

    /// If focus is `Some`, move it to the top of the stack and set it to `None`.
    /// Then pop from stack `new_focus` and set it to current `focus`.
    ///
    /// > Panics if `new_focus` doesn't exist in components
    fn change_focus(&mut self, new_focus: &ComponentId) {
        if let Some(focus) = self.focus.take() {
            // dont do anything, if the newfocus is the same component
            // otherwise we would be removing focus on remount
            if focus == *new_focus {
                self.focus = Some(focus);
                return;
            }

            // Remove focus (can't return error)
            let _ = self.set_focus(&focus, false);
            // Push to stack
            self.push_to_stack(focus);
        }
        self.pop_from_stack(new_focus);
        // Get key from focus_stack (otherwise lifetime won't be valid)
        let key = self.components.keys().find(|x| *x == new_focus).unwrap();
        self.focus = Some(key.clone());
    }

    /// Give focus to the last component in the stack
    fn focus_to_last(&mut self) {
        if let Some(focus) = self.take_last_from_stack() {
            let _ = self.active(&focus);
        }
    }

    /// Take last element from stack if any
    fn take_last_from_stack(&mut self) -> Option<ComponentId> {
        self.focus_stack.pop()
    }

    /// Set focus value for component
    fn set_focus(&mut self, id: &ComponentId, value: bool) -> ViewResult<()> {
        if let Some(c) = self.components.get_mut(id) {
            c.attr(Attribute::Focus, AttrValue::Flag(value));
            Ok(())
        } else {
            Err(ViewError::ComponentNotFound)
        }
    }

    /// Inject properties for `id` using view injectors
    fn inject(&mut self, id: &ComponentId) -> ViewResult<()> {
        for (attr, value) in self.properties_to_inject(id) {
            self.attr(id, attr, value)?;
        }
        Ok(())
    }

    /// Collect properties to inject for component `K`
    fn properties_to_inject(&self, id: &ComponentId) -> Vec<(Attribute, AttrValue)> {
        self.injectors.iter().flat_map(|x| x.inject(id)).collect()
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::event::{Key, KeyEvent};
    use crate::mock::{
        MockBarInput, MockComponentId, MockEvent, MockFooInput, MockInjector, MockInput, MockMsg,
    };
    use crate::state::StateValue;

    #[test]
    fn default_view_should_be_empty() {
        let view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        assert!(view.components.is_empty());
        assert_eq!(view.focus, None);
        assert!(view.focus_stack.is_empty());
    }

    #[test]
    fn view_should_mount_and_umount_components() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        // Mount foo
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert_eq!(view.components.len(), 1);
        assert!(view.mounted(&MockComponentId::InputFoo));
        assert_eq!(view.mounted(&MockComponentId::InputBar), false);
        // Mount bar
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        assert_eq!(view.components.len(), 2);
        assert!(view.mounted(&MockComponentId::InputBar));
        // Mount twice
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_err()
        );
        assert_eq!(view.components.len(), 2);
        assert!(view.mounted(&MockComponentId::InputBar));
        // Umount
        assert!(view.umount(&MockComponentId::InputFoo).is_ok());
        assert_eq!(view.components.len(), 1);
        assert_eq!(view.mounted(&MockComponentId::InputFoo), false);
        assert_eq!(view.mounted(&MockComponentId::InputBar), true);
        assert!(view.umount(&MockComponentId::InputBar).is_ok());
        assert_eq!(view.components.len(), 0);
        assert_eq!(view.mounted(&MockComponentId::InputBar), false);
        // Umount twice
        assert!(view.umount(&MockComponentId::InputBar).is_err());
    }

    #[test]
    fn view_should_remount_component_without_losing_focus_stack() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        // Mount foo
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert!(view.active(&MockComponentId::InputFoo).is_ok());
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        // mount another component
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        assert!(view.active(&MockComponentId::InputBar).is_ok());
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(false)
        );
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        // Remount foo
        assert!(
            view.remount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten(),
            None
        );
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        // Blur bar
        assert!(view.blur().is_ok());
        // Foo MUST have focus now
        assert!(view.has_focus(&MockComponentId::InputFoo));
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(false)
        );
    }

    #[test]
    fn view_should_preserve_focus_on_remount() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        // Mount foo
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        // mount another component
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );

        assert!(view.active(&MockComponentId::InputFoo).is_ok());
        assert!(view.has_focus(&MockComponentId::InputFoo));
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .flatten(),
            None
        );

        // Remount foo
        assert!(
            view.remount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );

        // Foo should still have the focus as before
        assert!(view.has_focus(&MockComponentId::InputFoo));
        // Foo should also have the proper focus attribute
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .flatten(),
            None
        );
    }

    #[test]
    fn view_should_umount_all() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        // Mount foo
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert_eq!(view.components.len(), 1);
        assert!(view.mounted(&MockComponentId::InputFoo));
        assert_eq!(view.mounted(&MockComponentId::InputBar), false);
        // Mount bar
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        assert_eq!(view.components.len(), 2);
        assert!(view.mounted(&MockComponentId::InputBar));
        // Mount twice
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_err()
        );
        assert_eq!(view.components.len(), 2);
        // Give focus
        assert!(view.active(&MockComponentId::InputFoo).is_ok());
        assert!(view.active(&MockComponentId::InputBar).is_ok());
        // Umount all
        view.umount_all();
        assert!(view.components.is_empty());
        assert!(view.focus_stack.is_empty());
        assert!(view.focus.is_none());
    }

    #[test]
    fn view_should_compile_with_dynamic_names() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        let names: Vec<MockComponentId> = (0..10)
            .map(|x| MockComponentId::Dyn(format!("INPUT_{}", x)))
            .collect();
        names.iter().for_each(|x| {
            assert!(view.mount(x, Box::new(MockBarInput::default())).is_ok());
        });
        assert_eq!(view.components.len(), 10);
        names.iter().for_each(|x| assert!(view.mounted(x)));
    }

    #[test]
    fn view_should_handle_focus() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        assert!(
            view.mount(
                &MockComponentId::InputOmar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        // Active foo
        assert!(view.active(&MockComponentId::InputFoo).is_ok());
        assert_eq!(view.focus(), Some(&MockComponentId::InputFoo));
        assert!(view.has_focus(&MockComponentId::InputFoo));
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .unwrap()
                .unwrap(),
            AttrValue::Flag(true)
        );
        assert_eq!(view.focus.to_owned().unwrap(), MockComponentId::InputFoo);
        assert!(view.focus_stack.is_empty());
        // Give focus to BAR
        assert!(view.active(&MockComponentId::InputBar).is_ok());
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .ok()
                .unwrap()
                .unwrap(),
            AttrValue::Flag(true)
        );
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .unwrap()
                .unwrap(),
            AttrValue::Flag(false)
        );
        assert!(view.has_focus(&MockComponentId::InputBar));
        assert_eq!(view.focus_stack.len(), 1);
        // Give focus to OMAR
        assert!(view.active(&MockComponentId::InputOmar).is_ok());
        assert!(view.has_focus(&MockComponentId::InputOmar));
        assert_eq!(view.focus_stack.len(), 2);
        // Give focus back to FOO
        assert!(view.active(&MockComponentId::InputFoo).is_ok());
        assert!(view.has_focus(&MockComponentId::InputFoo));
        assert_eq!(view.focus_stack.len(), 2);
        // Umount FOO
        assert!(view.umount(&MockComponentId::InputFoo).is_ok());
        // OMAR should have focus
        assert!(view.has_focus(&MockComponentId::InputOmar));
        assert_eq!(view.focus_stack.len(), 1);
        // Umount BAR
        assert!(view.umount(&MockComponentId::InputBar).is_ok());
        // Give focus to unexisting component
        assert!(view.active(&MockComponentId::InputBar).is_err());
        // OMAR should still have focus, but focus will be empty
        assert!(view.has_focus(&MockComponentId::InputOmar));
        assert_eq!(view.focus_stack.len(), 0);
        // Remount BAR
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        // Active BAR
        assert!(view.active(&MockComponentId::InputBar).is_ok());
        // Blur
        assert!(view.blur().is_ok());
        // Focus should be held by OMAR, but BAR should not be in stack
        assert!(view.has_focus(&MockComponentId::InputOmar));
        assert_eq!(view.focus_stack.len(), 0);
        assert!(view.mounted(&MockComponentId::InputBar));
        // Blur again
        assert!(view.blur().is_ok());
        // None has focus
        assert!(view.blur().is_err());
    }

    #[test]
    fn view_should_forward_events() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        let ev: Event<MockEvent> = Event::Keyboard(KeyEvent::from(Key::Char('a')));
        assert_eq!(
            view.forward(&MockComponentId::InputFoo, &ev)
                .ok()
                .unwrap()
                .unwrap(),
            MockMsg::FooInputChanged(String::from("a"))
        );
        // To non-existing component
        assert!(
            view.forward(&MockComponentId::InputBar, &Event::Tick)
                .is_err()
        );
    }

    #[test]
    fn view_should_read_and_write_attributes() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .unwrap(),
            None
        );
        assert!(
            view.query(&MockComponentId::InputBar, Attribute::Focus)
                .is_err()
        );
        assert!(
            view.attr(
                &MockComponentId::InputFoo,
                Attribute::Focus,
                AttrValue::Flag(true)
            )
            .is_ok()
        );
        assert_eq!(
            view.query(&MockComponentId::InputFoo, Attribute::Focus)
                .ok()
                .flatten()
                .unwrap(),
            AttrValue::Flag(true)
        );
    }

    #[test]
    fn view_should_read_state() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(MockFooInput::default())
            )
            .is_ok()
        );
        assert_eq!(
            view.state(&MockComponentId::InputFoo).unwrap(),
            State::Single(StateValue::String(String::new()))
        );
        assert!(view.state(&MockComponentId::InputBar).is_err());
    }

    #[test]
    fn view_should_inject_properties() {
        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        view.add_injector(Box::new(MockInjector));
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );
        // Check if property has been injected
        assert_eq!(
            view.query(&MockComponentId::InputBar, Attribute::Text)
                .ok()
                .unwrap()
                .unwrap(),
            AttrValue::String(String::from("hello, world!"))
        );
    }

    #[test]
    fn view_component_should_be_downcastable() {
        /// Some struct we can reference and has "&self" and "&mut self" requirements.
        #[derive(Component, Default)]
        pub struct OurMockFooInput {
            component: MockInput,
        }

        impl OurMockFooInput {
            fn some_mut_fn(&mut self) -> usize {
                10
            }

            fn some_ref_fn(&self) -> usize {
                20
            }
        }

        impl AppComponent<MockMsg, MockEvent> for OurMockFooInput {
            fn on(&mut self, _ev: &Event<MockEvent>) -> Option<MockMsg> {
                None
            }
        }

        let mut view: View<MockComponentId, MockMsg, MockEvent> = View::default();
        // Mount foo
        assert!(
            view.mount(
                &MockComponentId::InputFoo,
                Box::new(OurMockFooInput::default())
            )
            .is_ok()
        );
        assert!(
            view.mount(
                &MockComponentId::InputBar,
                Box::new(MockBarInput::default())
            )
            .is_ok()
        );

        // shouldnt return component for non-mounted id
        assert!(view.get_component(&MockComponentId::InputOmar).is_none());

        // reference
        let comp = view.get_component(&MockComponentId::InputFoo).unwrap();

        let downcasted = (comp).as_any().downcast_ref::<OurMockFooInput>().unwrap();
        downcasted.some_ref_fn();

        // mutable reference
        let comp_mut = view.get_component_mut(&MockComponentId::InputFoo).unwrap();

        let downcasted_mut = (comp_mut)
            .as_any_mut()
            .downcast_mut::<OurMockFooInput>()
            .unwrap();
        downcasted_mut.some_mut_fn();

        // reference shouldnt downcast to another component
        let comp = view.get_component(&MockComponentId::InputFoo).unwrap();
        assert!((comp).as_any().downcast_ref::<MockFooInput>().is_none());
    }
}