envision 0.10.1

A ratatui framework for collaborative TUI development with headless testing support
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! A list component with per-item loading and error states.
//!
//! [`LoadingList<T>`] extends the basic list pattern with loading indicators and
//! error states for each item. Useful for lists where items can be fetched
//! or processed asynchronously. State is stored in [`LoadingListState<T>`],
//! updated via [`LoadingListMessage`], and produces [`LoadingListOutput`].
//! Items are wrapped in [`LoadingItem<T>`].
//!
//! Implements [`Focusable`] and [`Disableable`].
//!
//! See also [`SelectableList`](super::SelectableList) for a simpler list.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{LoadingList, LoadingListState, LoadingListMessage, ItemState, Component};
//!
//! #[derive(Clone, Debug)]
//! struct Book {
//!     id: String,
//!     title: String,
//! }
//!
//! let books = vec![
//!     Book { id: "1".to_string(), title: "Book One".to_string() },
//!     Book { id: "2".to_string(), title: "Book Two".to_string() },
//! ];
//!
//! let mut state = LoadingListState::with_items(books, |b| b.title.clone());
//!
//! // Set first item as loading
//! LoadingList::update(&mut state, LoadingListMessage::SetLoading(0));
//!
//! // Later, mark as ready or error
//! LoadingList::update(&mut state, LoadingListMessage::SetReady(0));
//! // Or: LoadingList::update(&mut state, LoadingListMessage::SetError { index: 0, message: "Failed".to_string() });
//! ```

use ratatui::prelude::*;

use super::{Component, Disableable, Focusable, ViewContext};
use crate::input::{Event, KeyCode};
use crate::scroll::ScrollState;
use crate::theme::Theme;

mod render;

/// Loading state of an individual item.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum ItemState {
    /// Item is ready (normal state).
    #[default]
    Ready,
    /// Item is currently loading.
    Loading,
    /// Item has an error.
    Error(String),
}

impl ItemState {
    /// Returns true if the item is loading.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ItemState;
    ///
    /// assert!(!ItemState::Ready.is_loading());
    /// assert!(ItemState::Loading.is_loading());
    /// ```
    pub fn is_loading(&self) -> bool {
        matches!(self, Self::Loading)
    }

    /// Returns true if the item has an error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ItemState;
    ///
    /// assert!(!ItemState::Ready.is_error());
    /// assert!(ItemState::Error("failed".into()).is_error());
    /// ```
    pub fn is_error(&self) -> bool {
        matches!(self, Self::Error(_))
    }

    /// Returns true if the item is ready.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ItemState;
    ///
    /// assert!(ItemState::Ready.is_ready());
    /// assert!(!ItemState::Loading.is_ready());
    /// ```
    pub fn is_ready(&self) -> bool {
        matches!(self, Self::Ready)
    }

    /// Returns the error message if in error state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ItemState;
    ///
    /// let state = ItemState::Error("connection lost".into());
    /// assert_eq!(state.error_message(), Some("connection lost"));
    ///
    /// assert_eq!(ItemState::Ready.error_message(), None);
    /// ```
    pub fn error_message(&self) -> Option<&str> {
        if let Self::Error(msg) = self {
            Some(msg)
        } else {
            None
        }
    }

    /// Returns the symbol for this state.
    pub fn symbol(&self, spinner_frame: usize) -> &'static str {
        match self {
            Self::Ready => " ",
            Self::Loading => {
                // Braille dots animation matching SpinnerStyle::Dots
                const LOADING_FRAMES: [&str; 10] =
                    ["", "", "", "", "", "", "", "", "", ""];
                LOADING_FRAMES[spinner_frame % LOADING_FRAMES.len()]
            }
            Self::Error(_) => "",
        }
    }

    /// Returns the style for this state using the theme.
    pub fn style(&self, theme: &Theme) -> Style {
        match self {
            Self::Ready => theme.normal_style(),
            Self::Loading => theme.warning_style(),
            Self::Error(_) => theme.error_style(),
        }
    }
}

/// A single item in the loading list.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct LoadingListItem<T: Clone> {
    /// The underlying data.
    data: T,
    /// Display label.
    label: String,
    /// Current loading state.
    state: ItemState,
}

impl<T: Clone + PartialEq> PartialEq for LoadingListItem<T> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data && self.label == other.label && self.state == other.state
    }
}

impl<T: Clone> LoadingListItem<T> {
    /// Creates a new item.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListItem;
    ///
    /// let item = LoadingListItem::new("data", "Label");
    /// assert_eq!(item.label(), "Label");
    /// assert!(item.is_ready());
    /// ```
    pub fn new(data: T, label: impl Into<String>) -> Self {
        Self {
            data,
            label: label.into(),
            state: ItemState::Ready,
        }
    }

    /// Returns the underlying data.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListItem;
    ///
    /// let item = LoadingListItem::new(42, "Answer");
    /// assert_eq!(*item.data(), 42);
    /// ```
    pub fn data(&self) -> &T {
        &self.data
    }

    /// Returns a mutable reference to the data.
    pub fn data_mut(&mut self) -> &mut T {
        &mut self.data
    }

    /// Returns the label.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Sets the label.
    pub fn set_label(&mut self, label: impl Into<String>) {
        self.label = label.into();
    }

    /// Returns the current state.
    pub fn state(&self) -> &ItemState {
        &self.state
    }

    /// Sets the state.
    pub fn set_state(&mut self, state: ItemState) {
        self.state = state;
    }

    /// Returns true if the item is loading.
    pub fn is_loading(&self) -> bool {
        self.state.is_loading()
    }

    /// Returns true if the item has an error.
    pub fn is_error(&self) -> bool {
        self.state.is_error()
    }

    /// Returns true if the item is ready.
    pub fn is_ready(&self) -> bool {
        self.state.is_ready()
    }
}

/// Messages for the LoadingList component.
#[derive(Clone, Debug, PartialEq)]
pub enum LoadingListMessage<T: Clone> {
    /// Set all items.
    SetItems(Vec<T>),
    /// Set an item's state to loading.
    SetLoading(usize),
    /// Set an item's state to ready.
    SetReady(usize),
    /// Set an item's state to error.
    SetError {
        /// Item index.
        index: usize,
        /// Error message.
        message: String,
    },
    /// Clear an item's error (set to ready).
    ClearError(usize),
    /// Move selection up.
    Up,
    /// Move selection down.
    Down,
    /// Move to first item.
    First,
    /// Move to last item.
    Last,
    /// Select the current item.
    Select,
    /// Tick animation (advances spinner frame).
    Tick,
}

/// Output messages from LoadingList.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LoadingListOutput<T: Clone> {
    /// An item was selected.
    Selected(T),
    /// Selection changed.
    SelectionChanged(usize),
    /// An item's state changed.
    ItemStateChanged {
        /// Item index.
        index: usize,
        /// New state.
        state: ItemState,
    },
}

/// State for the LoadingList component.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct LoadingListState<T: Clone> {
    /// All items.
    items: Vec<LoadingListItem<T>>,
    /// Currently selected index.
    selected: Option<usize>,
    /// Whether the component is focused.
    focused: bool,
    /// Whether the component is disabled.
    disabled: bool,
    /// Current spinner animation frame.
    spinner_frame: usize,
    /// Optional title.
    title: Option<String>,
    /// Whether to show loading indicators.
    show_indicators: bool,
    /// Scroll state for virtual scrolling and scrollbar rendering.
    #[cfg_attr(feature = "serialization", serde(skip))]
    scroll: ScrollState,
}

impl<T: Clone + PartialEq> PartialEq for LoadingListState<T> {
    fn eq(&self, other: &Self) -> bool {
        self.items == other.items
            && self.selected == other.selected
            && self.focused == other.focused
            && self.disabled == other.disabled
            && self.spinner_frame == other.spinner_frame
            && self.title == other.title
            && self.show_indicators == other.show_indicators
    }
}

impl<T: Clone> Default for LoadingListState<T> {
    fn default() -> Self {
        Self {
            items: Vec::new(),
            selected: None,
            focused: false,
            disabled: false,
            spinner_frame: 0,
            title: None,
            show_indicators: true,
            scroll: ScrollState::default(),
        }
    }
}

impl<T: Clone> LoadingListState<T> {
    /// Creates a new empty LoadingList state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new();
    /// assert!(state.is_empty());
    /// assert_eq!(state.len(), 0);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a state with items, using a label extractor function.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Item { name: String }
    ///
    /// let items = vec![
    ///     Item { name: "One".to_string() },
    ///     Item { name: "Two".to_string() },
    /// ];
    ///
    /// let state = LoadingListState::with_items(items, |i| i.name.clone());
    /// assert_eq!(state.len(), 2);
    /// ```
    pub fn with_items<F>(items: Vec<T>, label_fn: F) -> Self
    where
        F: Fn(&T) -> String,
    {
        let list_items: Vec<LoadingListItem<T>> = items
            .into_iter()
            .map(|data| {
                let label = label_fn(&data);
                LoadingListItem::new(data, label)
            })
            .collect();

        let scroll = ScrollState::new(list_items.len());

        Self {
            items: list_items,
            selected: None,
            focused: false,
            disabled: false,
            spinner_frame: 0,
            title: None,
            show_indicators: true,
            scroll,
        }
    }

    /// Sets the initially selected index (builder method).
    ///
    /// The index is clamped to the valid range. Has no effect on empty lists.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let state = LoadingListState::with_items(
    ///     vec![
    ///         Task { name: "Build".to_string() },
    ///         Task { name: "Test".to_string() },
    ///         Task { name: "Deploy".to_string() },
    ///     ],
    ///     |t| t.name.clone(),
    /// ).with_selected(1);
    /// assert_eq!(state.selected_index(), Some(1));
    /// ```
    pub fn with_selected(mut self, index: usize) -> Self {
        if self.items.is_empty() {
            return self;
        }
        self.selected = Some(index.min(self.items.len() - 1));
        self
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new()
    ///     .with_title("Tasks");
    /// assert_eq!(state.title(), Some("Tasks"));
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets whether to show loading indicators.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new()
    ///     .with_indicators(false);
    /// assert!(!state.show_indicators());
    /// ```
    pub fn with_indicators(mut self, show: bool) -> Self {
        self.show_indicators = show;
        self
    }

    /// Sets the disabled state using builder pattern.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new().with_disabled(true);
    /// assert!(state.is_disabled());
    /// ```
    pub fn with_disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Returns all items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::with_items(
    ///     vec!["alpha".to_string(), "beta".to_string()],
    ///     |s| s.clone(),
    /// );
    /// assert_eq!(state.items().len(), 2);
    /// assert_eq!(state.items()[0].label(), "alpha");
    /// ```
    pub fn items(&self) -> &[LoadingListItem<T>] {
        &self.items
    }

    /// Returns a mutable reference to all items.
    pub fn items_mut(&mut self) -> &mut Vec<LoadingListItem<T>> {
        &mut self.items
    }

    /// Returns the number of items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::with_items(
    ///     vec!["a".to_string(), "b".to_string()],
    ///     |s| s.clone(),
    /// );
    /// assert_eq!(state.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns true if there are no items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new();
    /// assert!(state.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Returns the selected index.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::with_items(
    ///     vec!["a".to_string()],
    ///     |s| s.clone(),
    /// ).with_selected(0);
    /// assert_eq!(state.selected_index(), Some(0));
    /// ```
    pub fn selected_index(&self) -> Option<usize> {
        self.selected
    }

    /// Alias for [`selected_index()`](Self::selected_index).
    pub fn selected(&self) -> Option<usize> {
        self.selected_index()
    }

    /// Returns the selected item.
    ///
    /// Returns `None` if no item is selected.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec![Task { name: "Build".to_string() }],
    ///     |t| t.name.clone(),
    /// );
    /// assert!(state.selected_item().is_none());
    ///
    /// state.set_selected(Some(0));
    /// assert_eq!(state.selected_item().unwrap().label(), "Build");
    /// ```
    pub fn selected_item(&self) -> Option<&LoadingListItem<T>> {
        self.selected.and_then(|i| self.items.get(i))
    }

    /// Returns the selected item's data.
    pub fn selected_data(&self) -> Option<&T> {
        self.selected_item().map(|item| item.data())
    }

    /// Sets the selected index.
    pub fn set_selected(&mut self, index: Option<usize>) {
        self.selected = index.map(|i| i.min(self.items.len().saturating_sub(1)));
    }

    /// Returns an item by index.
    pub fn get(&self, index: usize) -> Option<&LoadingListItem<T>> {
        self.items.get(index)
    }

    /// Returns a mutable item by index.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut LoadingListItem<T>> {
        self.items.get_mut(index)
    }

    /// Sets the loading state for an item.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec![Task { name: "Build".to_string() }],
    ///     |t| t.name.clone(),
    /// );
    /// state.set_loading(0);
    /// assert!(state.has_loading());
    /// ```
    pub fn set_loading(&mut self, index: usize) {
        if let Some(item) = self.items.get_mut(index) {
            item.state = ItemState::Loading;
        }
    }

    /// Sets the ready state for an item.
    pub fn set_ready(&mut self, index: usize) {
        if let Some(item) = self.items.get_mut(index) {
            item.state = ItemState::Ready;
        }
    }

    /// Sets the error state for an item.
    pub fn set_error(&mut self, index: usize, message: impl Into<String>) {
        if let Some(item) = self.items.get_mut(index) {
            item.state = ItemState::Error(message.into());
        }
    }

    /// Returns the number of items currently loading.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec![
    ///         Task { name: "A".to_string() },
    ///         Task { name: "B".to_string() },
    ///     ],
    ///     |t| t.name.clone(),
    /// );
    /// state.set_loading(0);
    /// state.set_loading(1);
    /// assert_eq!(state.loading_count(), 2);
    /// ```
    pub fn loading_count(&self) -> usize {
        self.items.iter().filter(|i| i.is_loading()).count()
    }

    /// Returns the number of items with errors.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec![
    ///         Task { name: "A".to_string() },
    ///         Task { name: "B".to_string() },
    ///     ],
    ///     |t| t.name.clone(),
    /// );
    /// state.set_error(0, "failed");
    /// assert_eq!(state.error_count(), 1);
    /// ```
    pub fn error_count(&self) -> usize {
        self.items.iter().filter(|i| i.is_error()).count()
    }

    /// Returns true if any item is loading.
    pub fn has_loading(&self) -> bool {
        self.items.iter().any(|i| i.is_loading())
    }

    /// Returns true if any item has an error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// #[derive(Clone)]
    /// struct Task { name: String }
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec![Task { name: "Build".to_string() }],
    ///     |t| t.name.clone(),
    /// );
    /// assert!(!state.has_errors());
    /// state.set_error(0, "Failed to build");
    /// assert!(state.has_errors());
    /// ```
    pub fn has_errors(&self) -> bool {
        self.items.iter().any(|i| i.is_error())
    }

    /// Returns the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new().with_title("Tasks");
    /// assert_eq!(state.title(), Some("Tasks"));
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let mut state = LoadingListState::<String>::new();
    /// state.set_title(Some("Downloads".to_string()));
    /// assert_eq!(state.title(), Some("Downloads"));
    /// ```
    pub fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    /// Returns whether indicators are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let state = LoadingListState::<String>::new();
    /// assert!(state.show_indicators()); // enabled by default
    /// ```
    pub fn show_indicators(&self) -> bool {
        self.show_indicators
    }

    /// Sets whether to show indicators.
    pub fn set_show_indicators(&mut self, show: bool) {
        self.show_indicators = show;
    }

    /// Returns the current spinner frame.
    pub fn spinner_frame(&self) -> usize {
        self.spinner_frame
    }

    /// Clears all items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::LoadingListState;
    ///
    /// let mut state = LoadingListState::with_items(
    ///     vec!["a".to_string()],
    ///     |s| s.clone(),
    /// );
    /// assert_eq!(state.len(), 1);
    /// state.clear();
    /// assert!(state.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.items.clear();
        self.selected = None;
        self.scroll.set_content_length(0);
    }
}

impl<T: Clone + 'static> LoadingListState<T> {
    /// Returns true if the loading list is focused.
    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// Sets the focus state.
    pub fn set_focused(&mut self, focused: bool) {
        self.focused = focused;
    }

    /// Returns true if the loading list is disabled.
    pub fn is_disabled(&self) -> bool {
        self.disabled
    }

    /// Sets the disabled state.
    ///
    /// Disabled loading lists do not respond to input events.
    pub fn set_disabled(&mut self, disabled: bool) {
        self.disabled = disabled;
    }

    /// Maps an input event to a loading list message.
    pub fn handle_event(&self, event: &Event) -> Option<LoadingListMessage<T>> {
        LoadingList::handle_event(self, event)
    }

    /// Dispatches an event, updating state and returning any output.
    pub fn dispatch_event(&mut self, event: &Event) -> Option<LoadingListOutput<T>> {
        LoadingList::dispatch_event(self, event)
    }

    /// Updates the loading list state with a message, returning any output.
    pub fn update(&mut self, msg: LoadingListMessage<T>) -> Option<LoadingListOutput<T>> {
        LoadingList::update(self, msg)
    }
}

/// A list component with per-item loading and error states.
///
/// # Visual Format
///
/// ```text
/// ┌─Items───────────────────────────┐
/// │   Item 1                        │
/// │ ⠙ Item 2 (loading)              │
/// │ ▸ Item 3 (selected)             │
/// │ ✗ Item 4 - Error: Failed        │
/// └─────────────────────────────────┘
/// ```
pub struct LoadingList<T: Clone>(std::marker::PhantomData<T>);

impl<T: Clone> Component for LoadingList<T> {
    type State = LoadingListState<T>;
    type Message = LoadingListMessage<T>;
    type Output = LoadingListOutput<T>;

    fn init() -> Self::State {
        LoadingListState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        // Block user-initiated navigation/selection when disabled.
        // Programmatic state changes (SetItems, SetLoading, etc.) still work.
        if state.disabled {
            match msg {
                LoadingListMessage::Up
                | LoadingListMessage::Down
                | LoadingListMessage::First
                | LoadingListMessage::Last
                | LoadingListMessage::Select => return None,
                _ => {}
            }
        }

        match msg {
            LoadingListMessage::SetItems(items) => {
                // Convert items without a label function - uses Debug if available
                // In practice, users should use LoadingListState::with_items
                state.items = items
                    .into_iter()
                    .enumerate()
                    .map(|(i, data)| LoadingListItem::new(data, format!("Item {}", i + 1)))
                    .collect();
                state.selected = None;
                state.scroll.set_content_length(state.items.len());
                None
            }

            LoadingListMessage::SetLoading(index) => {
                if let Some(item) = state.items.get_mut(index) {
                    item.state = ItemState::Loading;
                    Some(LoadingListOutput::ItemStateChanged {
                        index,
                        state: ItemState::Loading,
                    })
                } else {
                    None
                }
            }

            LoadingListMessage::SetReady(index) => {
                if let Some(item) = state.items.get_mut(index) {
                    item.state = ItemState::Ready;
                    Some(LoadingListOutput::ItemStateChanged {
                        index,
                        state: ItemState::Ready,
                    })
                } else {
                    None
                }
            }

            LoadingListMessage::SetError { index, message } => {
                if let Some(item) = state.items.get_mut(index) {
                    let new_state = ItemState::Error(message.clone());
                    item.state = new_state.clone();
                    Some(LoadingListOutput::ItemStateChanged {
                        index,
                        state: new_state,
                    })
                } else {
                    None
                }
            }

            LoadingListMessage::ClearError(index) => {
                if let Some(item) = state.items.get_mut(index) {
                    if item.is_error() {
                        item.state = ItemState::Ready;
                        return Some(LoadingListOutput::ItemStateChanged {
                            index,
                            state: ItemState::Ready,
                        });
                    }
                }
                None
            }

            LoadingListMessage::Up => {
                if state.items.is_empty() {
                    return None;
                }

                let new_index = match state.selected {
                    Some(i) if i > 0 => i - 1,
                    Some(_) => state.items.len() - 1, // Wrap to bottom
                    None => state.items.len() - 1,
                };

                state.selected = Some(new_index);
                state.scroll.ensure_visible(new_index);
                Some(LoadingListOutput::SelectionChanged(new_index))
            }

            LoadingListMessage::Down => {
                if state.items.is_empty() {
                    return None;
                }

                let new_index = match state.selected {
                    Some(i) if i < state.items.len() - 1 => i + 1,
                    Some(_) => 0, // Wrap to top
                    None => 0,
                };

                state.selected = Some(new_index);
                state.scroll.ensure_visible(new_index);
                Some(LoadingListOutput::SelectionChanged(new_index))
            }

            LoadingListMessage::First => {
                if state.items.is_empty() {
                    return None;
                }

                state.selected = Some(0);
                state.scroll.ensure_visible(0);
                Some(LoadingListOutput::SelectionChanged(0))
            }

            LoadingListMessage::Last => {
                if state.items.is_empty() {
                    return None;
                }

                let last = state.items.len() - 1;
                state.selected = Some(last);
                state.scroll.ensure_visible(last);
                Some(LoadingListOutput::SelectionChanged(last))
            }

            LoadingListMessage::Select => {
                if let Some(index) = state.selected {
                    if let Some(item) = state.items.get(index) {
                        return Some(LoadingListOutput::Selected(item.data.clone()));
                    }
                }
                None
            }

            LoadingListMessage::Tick => {
                state.spinner_frame = (state.spinner_frame + 1) % 4;
                None
            }
        }
    }

    fn handle_event(state: &Self::State, event: &Event) -> Option<Self::Message> {
        if !state.focused || state.disabled {
            return None;
        }
        if let Some(key) = event.as_key() {
            match key.code {
                KeyCode::Up | KeyCode::Char('k') => Some(LoadingListMessage::Up),
                KeyCode::Down | KeyCode::Char('j') => Some(LoadingListMessage::Down),
                KeyCode::Enter => Some(LoadingListMessage::Select),
                _ => None,
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, frame: &mut Frame, area: Rect, theme: &Theme, ctx: &ViewContext) {
        render::render_loading_list(state, frame, area, theme, ctx.focused, ctx.disabled);
    }
}

impl<T: Clone> Focusable for LoadingList<T> {
    fn is_focused(state: &Self::State) -> bool {
        state.focused
    }

    fn set_focused(state: &mut Self::State, focused: bool) {
        state.focused = focused;
    }
}

impl<T: Clone> Disableable for LoadingList<T> {
    fn is_disabled(state: &Self::State) -> bool {
        state.disabled
    }

    fn set_disabled(state: &mut Self::State, disabled: bool) {
        state.disabled = disabled;
    }
}

#[cfg(test)]
mod snapshot_tests;
#[cfg(test)]
mod tests;