1use std::collections::HashSet;
8use unicode_width::UnicodeWidthStr;
9
10type FormValidator = fn(&str) -> Result<(), String>;
11
12pub struct TextInputState {
28 pub value: String,
30 pub cursor: usize,
32 pub placeholder: String,
34 pub max_length: Option<usize>,
36 pub validation_error: Option<String>,
38 pub masked: bool,
40}
41
42impl TextInputState {
43 pub fn new() -> Self {
45 Self {
46 value: String::new(),
47 cursor: 0,
48 placeholder: String::new(),
49 max_length: None,
50 validation_error: None,
51 masked: false,
52 }
53 }
54
55 pub fn with_placeholder(p: impl Into<String>) -> Self {
57 Self {
58 placeholder: p.into(),
59 ..Self::new()
60 }
61 }
62
63 pub fn max_length(mut self, len: usize) -> Self {
65 self.max_length = Some(len);
66 self
67 }
68
69 pub fn validate(&mut self, validator: impl Fn(&str) -> Result<(), String>) {
74 self.validation_error = validator(&self.value).err();
75 }
76}
77
78impl Default for TextInputState {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84pub struct FormField {
86 pub label: String,
88 pub input: TextInputState,
90 pub error: Option<String>,
92}
93
94impl FormField {
95 pub fn new(label: impl Into<String>) -> Self {
97 Self {
98 label: label.into(),
99 input: TextInputState::new(),
100 error: None,
101 }
102 }
103
104 pub fn placeholder(mut self, p: impl Into<String>) -> Self {
106 self.input.placeholder = p.into();
107 self
108 }
109}
110
111pub struct FormState {
113 pub fields: Vec<FormField>,
115 pub submitted: bool,
117}
118
119impl FormState {
120 pub fn new() -> Self {
122 Self {
123 fields: Vec::new(),
124 submitted: false,
125 }
126 }
127
128 pub fn field(mut self, field: FormField) -> Self {
130 self.fields.push(field);
131 self
132 }
133
134 pub fn validate(&mut self, validators: &[FormValidator]) -> bool {
138 let mut all_valid = true;
139 for (i, field) in self.fields.iter_mut().enumerate() {
140 if let Some(validator) = validators.get(i) {
141 match validator(&field.input.value) {
142 Ok(()) => field.error = None,
143 Err(msg) => {
144 field.error = Some(msg);
145 all_valid = false;
146 }
147 }
148 }
149 }
150 all_valid
151 }
152
153 pub fn value(&self, index: usize) -> &str {
155 self.fields
156 .get(index)
157 .map(|f| f.input.value.as_str())
158 .unwrap_or("")
159 }
160}
161
162impl Default for FormState {
163 fn default() -> Self {
164 Self::new()
165 }
166}
167
168pub struct ToastState {
174 pub messages: Vec<ToastMessage>,
176}
177
178pub struct ToastMessage {
180 pub text: String,
182 pub level: ToastLevel,
184 pub created_tick: u64,
186 pub duration_ticks: u64,
188}
189
190pub enum ToastLevel {
192 Info,
194 Success,
196 Warning,
198 Error,
200}
201
202impl ToastState {
203 pub fn new() -> Self {
205 Self {
206 messages: Vec::new(),
207 }
208 }
209
210 pub fn info(&mut self, text: impl Into<String>, tick: u64) {
212 self.push(text, ToastLevel::Info, tick, 30);
213 }
214
215 pub fn success(&mut self, text: impl Into<String>, tick: u64) {
217 self.push(text, ToastLevel::Success, tick, 30);
218 }
219
220 pub fn warning(&mut self, text: impl Into<String>, tick: u64) {
222 self.push(text, ToastLevel::Warning, tick, 50);
223 }
224
225 pub fn error(&mut self, text: impl Into<String>, tick: u64) {
227 self.push(text, ToastLevel::Error, tick, 80);
228 }
229
230 pub fn push(
232 &mut self,
233 text: impl Into<String>,
234 level: ToastLevel,
235 tick: u64,
236 duration_ticks: u64,
237 ) {
238 self.messages.push(ToastMessage {
239 text: text.into(),
240 level,
241 created_tick: tick,
242 duration_ticks,
243 });
244 }
245
246 pub fn cleanup(&mut self, current_tick: u64) {
250 self.messages.retain(|message| {
251 current_tick < message.created_tick.saturating_add(message.duration_ticks)
252 });
253 }
254}
255
256impl Default for ToastState {
257 fn default() -> Self {
258 Self::new()
259 }
260}
261
262pub struct TextareaState {
267 pub lines: Vec<String>,
269 pub cursor_row: usize,
271 pub cursor_col: usize,
273 pub max_length: Option<usize>,
275 pub wrap_width: Option<u32>,
277 pub scroll_offset: usize,
279}
280
281impl TextareaState {
282 pub fn new() -> Self {
284 Self {
285 lines: vec![String::new()],
286 cursor_row: 0,
287 cursor_col: 0,
288 max_length: None,
289 wrap_width: None,
290 scroll_offset: 0,
291 }
292 }
293
294 pub fn value(&self) -> String {
296 self.lines.join("\n")
297 }
298
299 pub fn set_value(&mut self, text: impl Into<String>) {
303 let value = text.into();
304 self.lines = value.split('\n').map(str::to_string).collect();
305 if self.lines.is_empty() {
306 self.lines.push(String::new());
307 }
308 self.cursor_row = 0;
309 self.cursor_col = 0;
310 self.scroll_offset = 0;
311 }
312
313 pub fn max_length(mut self, len: usize) -> Self {
315 self.max_length = Some(len);
316 self
317 }
318
319 pub fn word_wrap(mut self, width: u32) -> Self {
321 self.wrap_width = Some(width);
322 self
323 }
324}
325
326impl Default for TextareaState {
327 fn default() -> Self {
328 Self::new()
329 }
330}
331
332pub struct SpinnerState {
338 chars: Vec<char>,
339}
340
341impl SpinnerState {
342 pub fn dots() -> Self {
346 Self {
347 chars: vec!['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
348 }
349 }
350
351 pub fn line() -> Self {
355 Self {
356 chars: vec!['|', '/', '-', '\\'],
357 }
358 }
359
360 pub fn frame(&self, tick: u64) -> char {
362 if self.chars.is_empty() {
363 return ' ';
364 }
365 self.chars[tick as usize % self.chars.len()]
366 }
367}
368
369impl Default for SpinnerState {
370 fn default() -> Self {
371 Self::dots()
372 }
373}
374
375pub struct ListState {
380 pub items: Vec<String>,
382 pub selected: usize,
384}
385
386impl ListState {
387 pub fn new(items: Vec<impl Into<String>>) -> Self {
389 Self {
390 items: items.into_iter().map(Into::into).collect(),
391 selected: 0,
392 }
393 }
394
395 pub fn selected_item(&self) -> Option<&str> {
397 self.items.get(self.selected).map(String::as_str)
398 }
399}
400
401pub struct TabsState {
406 pub labels: Vec<String>,
408 pub selected: usize,
410}
411
412impl TabsState {
413 pub fn new(labels: Vec<impl Into<String>>) -> Self {
415 Self {
416 labels: labels.into_iter().map(Into::into).collect(),
417 selected: 0,
418 }
419 }
420
421 pub fn selected_label(&self) -> Option<&str> {
423 self.labels.get(self.selected).map(String::as_str)
424 }
425}
426
427pub struct TableState {
433 pub headers: Vec<String>,
435 pub rows: Vec<Vec<String>>,
437 pub selected: usize,
439 column_widths: Vec<u32>,
440 dirty: bool,
441 pub sort_column: Option<usize>,
443 pub sort_ascending: bool,
445 pub filter: String,
447 pub page: usize,
449 pub page_size: usize,
451 view_indices: Vec<usize>,
452}
453
454impl TableState {
455 pub fn new(headers: Vec<impl Into<String>>, rows: Vec<Vec<impl Into<String>>>) -> Self {
457 let headers: Vec<String> = headers.into_iter().map(Into::into).collect();
458 let rows: Vec<Vec<String>> = rows
459 .into_iter()
460 .map(|r| r.into_iter().map(Into::into).collect())
461 .collect();
462 let mut state = Self {
463 headers,
464 rows,
465 selected: 0,
466 column_widths: Vec::new(),
467 dirty: true,
468 sort_column: None,
469 sort_ascending: true,
470 filter: String::new(),
471 page: 0,
472 page_size: 0,
473 view_indices: Vec::new(),
474 };
475 state.rebuild_view();
476 state.recompute_widths();
477 state
478 }
479
480 pub fn set_rows(&mut self, rows: Vec<Vec<impl Into<String>>>) {
485 self.rows = rows
486 .into_iter()
487 .map(|r| r.into_iter().map(Into::into).collect())
488 .collect();
489 self.rebuild_view();
490 }
491
492 pub fn toggle_sort(&mut self, column: usize) {
494 if self.sort_column == Some(column) {
495 self.sort_ascending = !self.sort_ascending;
496 } else {
497 self.sort_column = Some(column);
498 self.sort_ascending = true;
499 }
500 self.rebuild_view();
501 }
502
503 pub fn sort_by(&mut self, column: usize) {
505 self.sort_column = Some(column);
506 self.sort_ascending = true;
507 self.rebuild_view();
508 }
509
510 pub fn set_filter(&mut self, filter: impl Into<String>) {
512 self.filter = filter.into();
513 self.page = 0;
514 self.rebuild_view();
515 }
516
517 pub fn clear_sort(&mut self) {
519 self.sort_column = None;
520 self.sort_ascending = true;
521 self.rebuild_view();
522 }
523
524 pub fn next_page(&mut self) {
526 if self.page_size == 0 {
527 return;
528 }
529 let last_page = self.total_pages().saturating_sub(1);
530 self.page = (self.page + 1).min(last_page);
531 }
532
533 pub fn prev_page(&mut self) {
535 self.page = self.page.saturating_sub(1);
536 }
537
538 pub fn total_pages(&self) -> usize {
540 if self.page_size == 0 {
541 return 1;
542 }
543
544 let len = self.view_indices.len();
545 if len == 0 {
546 1
547 } else {
548 len.div_ceil(self.page_size)
549 }
550 }
551
552 pub fn visible_indices(&self) -> &[usize] {
554 &self.view_indices
555 }
556
557 pub fn selected_row(&self) -> Option<&[String]> {
559 if self.view_indices.is_empty() {
560 return None;
561 }
562 let data_idx = self.view_indices.get(self.selected)?;
563 self.rows.get(*data_idx).map(|r| r.as_slice())
564 }
565
566 fn rebuild_view(&mut self) {
568 let mut indices: Vec<usize> = (0..self.rows.len()).collect();
569
570 if !self.filter.is_empty() {
571 let needle = self.filter.to_lowercase();
572 indices.retain(|&idx| {
573 self.rows
574 .get(idx)
575 .map(|row| {
576 row.iter()
577 .any(|cell| cell.to_lowercase().contains(needle.as_str()))
578 })
579 .unwrap_or(false)
580 });
581 }
582
583 if let Some(column) = self.sort_column {
584 indices.sort_by(|a, b| {
585 let left = self
586 .rows
587 .get(*a)
588 .and_then(|row| row.get(column))
589 .map(String::as_str)
590 .unwrap_or("");
591 let right = self
592 .rows
593 .get(*b)
594 .and_then(|row| row.get(column))
595 .map(String::as_str)
596 .unwrap_or("");
597
598 match (left.parse::<f64>(), right.parse::<f64>()) {
599 (Ok(l), Ok(r)) => l.partial_cmp(&r).unwrap_or(std::cmp::Ordering::Equal),
600 _ => left.to_lowercase().cmp(&right.to_lowercase()),
601 }
602 });
603
604 if !self.sort_ascending {
605 indices.reverse();
606 }
607 }
608
609 self.view_indices = indices;
610
611 if self.page_size > 0 {
612 self.page = self.page.min(self.total_pages().saturating_sub(1));
613 } else {
614 self.page = 0;
615 }
616
617 self.selected = self.selected.min(self.view_indices.len().saturating_sub(1));
618 self.dirty = true;
619 }
620
621 pub(crate) fn recompute_widths(&mut self) {
622 let col_count = self.headers.len();
623 self.column_widths = vec![0u32; col_count];
624 for (i, header) in self.headers.iter().enumerate() {
625 let mut width = UnicodeWidthStr::width(header.as_str()) as u32;
626 if self.sort_column == Some(i) {
627 width += 2;
628 }
629 self.column_widths[i] = width;
630 }
631 for row in &self.rows {
632 for (i, cell) in row.iter().enumerate() {
633 if i < col_count {
634 let w = UnicodeWidthStr::width(cell.as_str()) as u32;
635 self.column_widths[i] = self.column_widths[i].max(w);
636 }
637 }
638 }
639 self.dirty = false;
640 }
641
642 pub(crate) fn column_widths(&self) -> &[u32] {
643 &self.column_widths
644 }
645
646 pub(crate) fn is_dirty(&self) -> bool {
647 self.dirty
648 }
649}
650
651pub struct ScrollState {
657 pub offset: usize,
659 content_height: u32,
660 viewport_height: u32,
661}
662
663impl ScrollState {
664 pub fn new() -> Self {
666 Self {
667 offset: 0,
668 content_height: 0,
669 viewport_height: 0,
670 }
671 }
672
673 pub fn can_scroll_up(&self) -> bool {
675 self.offset > 0
676 }
677
678 pub fn can_scroll_down(&self) -> bool {
680 (self.offset as u32) + self.viewport_height < self.content_height
681 }
682
683 pub fn content_height(&self) -> u32 {
685 self.content_height
686 }
687
688 pub fn viewport_height(&self) -> u32 {
690 self.viewport_height
691 }
692
693 pub fn progress(&self) -> f32 {
695 let max = self.content_height.saturating_sub(self.viewport_height);
696 if max == 0 {
697 0.0
698 } else {
699 self.offset as f32 / max as f32
700 }
701 }
702
703 pub fn scroll_up(&mut self, amount: usize) {
705 self.offset = self.offset.saturating_sub(amount);
706 }
707
708 pub fn scroll_down(&mut self, amount: usize) {
710 let max_offset = self.content_height.saturating_sub(self.viewport_height) as usize;
711 self.offset = (self.offset + amount).min(max_offset);
712 }
713
714 pub(crate) fn set_bounds(&mut self, content_height: u32, viewport_height: u32) {
715 self.content_height = content_height;
716 self.viewport_height = viewport_height;
717 }
718}
719
720impl Default for ScrollState {
721 fn default() -> Self {
722 Self::new()
723 }
724}
725
726#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
736pub enum ButtonVariant {
737 #[default]
739 Default,
740 Primary,
742 Danger,
744 Outline,
746}
747
748pub struct SelectState {
755 pub items: Vec<String>,
756 pub selected: usize,
757 pub open: bool,
758 pub placeholder: String,
759 cursor: usize,
760}
761
762impl SelectState {
763 pub fn new(items: Vec<impl Into<String>>) -> Self {
764 Self {
765 items: items.into_iter().map(Into::into).collect(),
766 selected: 0,
767 open: false,
768 placeholder: String::new(),
769 cursor: 0,
770 }
771 }
772
773 pub fn placeholder(mut self, p: impl Into<String>) -> Self {
774 self.placeholder = p.into();
775 self
776 }
777
778 pub fn selected_item(&self) -> Option<&str> {
779 self.items.get(self.selected).map(String::as_str)
780 }
781
782 pub(crate) fn cursor(&self) -> usize {
783 self.cursor
784 }
785
786 pub(crate) fn set_cursor(&mut self, c: usize) {
787 self.cursor = c;
788 }
789}
790
791pub struct RadioState {
797 pub items: Vec<String>,
798 pub selected: usize,
799}
800
801impl RadioState {
802 pub fn new(items: Vec<impl Into<String>>) -> Self {
803 Self {
804 items: items.into_iter().map(Into::into).collect(),
805 selected: 0,
806 }
807 }
808
809 pub fn selected_item(&self) -> Option<&str> {
810 self.items.get(self.selected).map(String::as_str)
811 }
812}
813
814pub struct MultiSelectState {
820 pub items: Vec<String>,
821 pub cursor: usize,
822 pub selected: HashSet<usize>,
823}
824
825impl MultiSelectState {
826 pub fn new(items: Vec<impl Into<String>>) -> Self {
827 Self {
828 items: items.into_iter().map(Into::into).collect(),
829 cursor: 0,
830 selected: HashSet::new(),
831 }
832 }
833
834 pub fn selected_items(&self) -> Vec<&str> {
835 let mut indices: Vec<usize> = self.selected.iter().copied().collect();
836 indices.sort();
837 indices
838 .iter()
839 .filter_map(|&i| self.items.get(i).map(String::as_str))
840 .collect()
841 }
842
843 pub fn toggle(&mut self, index: usize) {
844 if self.selected.contains(&index) {
845 self.selected.remove(&index);
846 } else {
847 self.selected.insert(index);
848 }
849 }
850}
851
852pub struct TreeNode {
856 pub label: String,
857 pub children: Vec<TreeNode>,
858 pub expanded: bool,
859}
860
861impl TreeNode {
862 pub fn new(label: impl Into<String>) -> Self {
863 Self {
864 label: label.into(),
865 children: Vec::new(),
866 expanded: false,
867 }
868 }
869
870 pub fn expanded(mut self) -> Self {
871 self.expanded = true;
872 self
873 }
874
875 pub fn children(mut self, children: Vec<TreeNode>) -> Self {
876 self.children = children;
877 self
878 }
879
880 pub fn is_leaf(&self) -> bool {
881 self.children.is_empty()
882 }
883
884 fn flatten(&self, depth: usize, out: &mut Vec<FlatTreeEntry>) {
885 out.push(FlatTreeEntry {
886 depth,
887 label: self.label.clone(),
888 is_leaf: self.is_leaf(),
889 expanded: self.expanded,
890 });
891 if self.expanded {
892 for child in &self.children {
893 child.flatten(depth + 1, out);
894 }
895 }
896 }
897}
898
899pub(crate) struct FlatTreeEntry {
900 pub depth: usize,
901 pub label: String,
902 pub is_leaf: bool,
903 pub expanded: bool,
904}
905
906pub struct TreeState {
908 pub nodes: Vec<TreeNode>,
909 pub selected: usize,
910}
911
912impl TreeState {
913 pub fn new(nodes: Vec<TreeNode>) -> Self {
914 Self { nodes, selected: 0 }
915 }
916
917 pub(crate) fn flatten(&self) -> Vec<FlatTreeEntry> {
918 let mut entries = Vec::new();
919 for node in &self.nodes {
920 node.flatten(0, &mut entries);
921 }
922 entries
923 }
924
925 pub(crate) fn toggle_at(&mut self, flat_index: usize) {
926 let mut counter = 0usize;
927 Self::toggle_recursive(&mut self.nodes, flat_index, &mut counter);
928 }
929
930 fn toggle_recursive(nodes: &mut [TreeNode], target: usize, counter: &mut usize) -> bool {
931 for node in nodes.iter_mut() {
932 if *counter == target {
933 if !node.is_leaf() {
934 node.expanded = !node.expanded;
935 }
936 return true;
937 }
938 *counter += 1;
939 if node.expanded && Self::toggle_recursive(&mut node.children, target, counter) {
940 return true;
941 }
942 }
943 false
944 }
945}
946
947pub struct PaletteCommand {
951 pub label: String,
952 pub description: String,
953 pub shortcut: Option<String>,
954}
955
956impl PaletteCommand {
957 pub fn new(label: impl Into<String>, description: impl Into<String>) -> Self {
958 Self {
959 label: label.into(),
960 description: description.into(),
961 shortcut: None,
962 }
963 }
964
965 pub fn shortcut(mut self, s: impl Into<String>) -> Self {
966 self.shortcut = Some(s.into());
967 self
968 }
969}
970
971pub struct CommandPaletteState {
975 pub commands: Vec<PaletteCommand>,
976 pub input: String,
977 pub cursor: usize,
978 pub open: bool,
979 selected: usize,
980}
981
982impl CommandPaletteState {
983 pub fn new(commands: Vec<PaletteCommand>) -> Self {
984 Self {
985 commands,
986 input: String::new(),
987 cursor: 0,
988 open: false,
989 selected: 0,
990 }
991 }
992
993 pub fn toggle(&mut self) {
994 self.open = !self.open;
995 if self.open {
996 self.input.clear();
997 self.cursor = 0;
998 self.selected = 0;
999 }
1000 }
1001
1002 pub(crate) fn filtered_indices(&self) -> Vec<usize> {
1003 if self.input.is_empty() {
1004 return (0..self.commands.len()).collect();
1005 }
1006 let query = self.input.to_lowercase();
1007 self.commands
1008 .iter()
1009 .enumerate()
1010 .filter(|(_, cmd)| {
1011 cmd.label.to_lowercase().contains(&query)
1012 || cmd.description.to_lowercase().contains(&query)
1013 })
1014 .map(|(i, _)| i)
1015 .collect()
1016 }
1017
1018 pub(crate) fn selected(&self) -> usize {
1019 self.selected
1020 }
1021
1022 pub(crate) fn set_selected(&mut self, s: usize) {
1023 self.selected = s;
1024 }
1025}
1026
1027pub struct StreamingTextState {
1032 pub content: String,
1034 pub streaming: bool,
1036 pub(crate) cursor_visible: bool,
1038 pub(crate) cursor_tick: u64,
1039}
1040
1041impl StreamingTextState {
1042 pub fn new() -> Self {
1044 Self {
1045 content: String::new(),
1046 streaming: false,
1047 cursor_visible: true,
1048 cursor_tick: 0,
1049 }
1050 }
1051
1052 pub fn push(&mut self, chunk: &str) {
1054 self.content.push_str(chunk);
1055 }
1056
1057 pub fn finish(&mut self) {
1059 self.streaming = false;
1060 }
1061
1062 pub fn start(&mut self) {
1064 self.content.clear();
1065 self.streaming = true;
1066 self.cursor_visible = true;
1067 self.cursor_tick = 0;
1068 }
1069
1070 pub fn clear(&mut self) {
1072 self.content.clear();
1073 self.streaming = false;
1074 self.cursor_visible = true;
1075 self.cursor_tick = 0;
1076 }
1077}
1078
1079impl Default for StreamingTextState {
1080 fn default() -> Self {
1081 Self::new()
1082 }
1083}
1084
1085#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1087pub enum ApprovalAction {
1088 Pending,
1090 Approved,
1092 Rejected,
1094}
1095
1096pub struct ToolApprovalState {
1102 pub tool_name: String,
1104 pub description: String,
1106 pub action: ApprovalAction,
1108}
1109
1110impl ToolApprovalState {
1111 pub fn new(tool_name: impl Into<String>, description: impl Into<String>) -> Self {
1113 Self {
1114 tool_name: tool_name.into(),
1115 description: description.into(),
1116 action: ApprovalAction::Pending,
1117 }
1118 }
1119
1120 pub fn reset(&mut self) {
1122 self.action = ApprovalAction::Pending;
1123 }
1124}
1125
1126#[derive(Debug, Clone)]
1128pub struct ContextItem {
1129 pub label: String,
1131 pub tokens: usize,
1133}
1134
1135impl ContextItem {
1136 pub fn new(label: impl Into<String>, tokens: usize) -> Self {
1138 Self {
1139 label: label.into(),
1140 tokens,
1141 }
1142 }
1143}