1use crate::event::{Event, KeyCode, KeyModifiers, MouseButton, MouseKind};
2use crate::layout::{Command, Direction};
3use crate::rect::Rect;
4use crate::style::{Align, Border, Color, Constraints, Margin, Modifiers, Padding, Style, Theme};
5use crate::widgets::{
6 ListState, ScrollState, SpinnerState, TableState, TabsState, TextInputState, TextareaState,
7 ToastLevel, ToastState,
8};
9use unicode_width::UnicodeWidthStr;
10
11#[derive(Debug, Clone, Copy, Default)]
17pub struct Response {
18 pub clicked: bool,
20 pub hovered: bool,
22}
23
24pub trait Widget {
86 type Response;
89
90 fn ui(&mut self, ctx: &mut Context) -> Self::Response;
96}
97
98pub struct Context {
114 pub(crate) commands: Vec<Command>,
115 pub(crate) events: Vec<Event>,
116 pub(crate) consumed: Vec<bool>,
117 pub(crate) should_quit: bool,
118 pub(crate) area_width: u32,
119 pub(crate) area_height: u32,
120 pub(crate) tick: u64,
121 pub(crate) focus_index: usize,
122 pub(crate) focus_count: usize,
123 prev_focus_count: usize,
124 scroll_count: usize,
125 prev_scroll_infos: Vec<(u32, u32)>,
126 interaction_count: usize,
127 prev_hit_map: Vec<Rect>,
128 mouse_pos: Option<(u32, u32)>,
129 click_pos: Option<(u32, u32)>,
130 last_mouse_pos: Option<(u32, u32)>,
131 last_text_idx: Option<usize>,
132 debug: bool,
133 theme: Theme,
134}
135
136pub struct ContainerBuilder<'a> {
157 ctx: &'a mut Context,
158 gap: u32,
159 align: Align,
160 border: Option<Border>,
161 border_style: Style,
162 padding: Padding,
163 margin: Margin,
164 constraints: Constraints,
165 title: Option<(String, Style)>,
166 grow: u16,
167 scroll_offset: Option<u32>,
168}
169
170impl<'a> ContainerBuilder<'a> {
171 pub fn border(mut self, border: Border) -> Self {
175 self.border = Some(border);
176 self
177 }
178
179 pub fn rounded(self) -> Self {
181 self.border(Border::Rounded)
182 }
183
184 pub fn border_style(mut self, style: Style) -> Self {
186 self.border_style = style;
187 self
188 }
189
190 pub fn p(self, value: u32) -> Self {
194 self.pad(value)
195 }
196
197 pub fn pad(mut self, value: u32) -> Self {
199 self.padding = Padding::all(value);
200 self
201 }
202
203 pub fn px(mut self, value: u32) -> Self {
205 self.padding.left = value;
206 self.padding.right = value;
207 self
208 }
209
210 pub fn py(mut self, value: u32) -> Self {
212 self.padding.top = value;
213 self.padding.bottom = value;
214 self
215 }
216
217 pub fn pt(mut self, value: u32) -> Self {
219 self.padding.top = value;
220 self
221 }
222
223 pub fn pr(mut self, value: u32) -> Self {
225 self.padding.right = value;
226 self
227 }
228
229 pub fn pb(mut self, value: u32) -> Self {
231 self.padding.bottom = value;
232 self
233 }
234
235 pub fn pl(mut self, value: u32) -> Self {
237 self.padding.left = value;
238 self
239 }
240
241 pub fn padding(mut self, padding: Padding) -> Self {
243 self.padding = padding;
244 self
245 }
246
247 pub fn m(mut self, value: u32) -> Self {
251 self.margin = Margin::all(value);
252 self
253 }
254
255 pub fn mx(mut self, value: u32) -> Self {
257 self.margin.left = value;
258 self.margin.right = value;
259 self
260 }
261
262 pub fn my(mut self, value: u32) -> Self {
264 self.margin.top = value;
265 self.margin.bottom = value;
266 self
267 }
268
269 pub fn mt(mut self, value: u32) -> Self {
271 self.margin.top = value;
272 self
273 }
274
275 pub fn mr(mut self, value: u32) -> Self {
277 self.margin.right = value;
278 self
279 }
280
281 pub fn mb(mut self, value: u32) -> Self {
283 self.margin.bottom = value;
284 self
285 }
286
287 pub fn ml(mut self, value: u32) -> Self {
289 self.margin.left = value;
290 self
291 }
292
293 pub fn margin(mut self, margin: Margin) -> Self {
295 self.margin = margin;
296 self
297 }
298
299 pub fn w(mut self, value: u32) -> Self {
303 self.constraints.min_width = Some(value);
304 self.constraints.max_width = Some(value);
305 self
306 }
307
308 pub fn h(mut self, value: u32) -> Self {
310 self.constraints.min_height = Some(value);
311 self.constraints.max_height = Some(value);
312 self
313 }
314
315 pub fn min_w(mut self, value: u32) -> Self {
317 self.constraints.min_width = Some(value);
318 self
319 }
320
321 pub fn max_w(mut self, value: u32) -> Self {
323 self.constraints.max_width = Some(value);
324 self
325 }
326
327 pub fn min_h(mut self, value: u32) -> Self {
329 self.constraints.min_height = Some(value);
330 self
331 }
332
333 pub fn max_h(mut self, value: u32) -> Self {
335 self.constraints.max_height = Some(value);
336 self
337 }
338
339 pub fn min_width(mut self, value: u32) -> Self {
341 self.constraints.min_width = Some(value);
342 self
343 }
344
345 pub fn max_width(mut self, value: u32) -> Self {
347 self.constraints.max_width = Some(value);
348 self
349 }
350
351 pub fn min_height(mut self, value: u32) -> Self {
353 self.constraints.min_height = Some(value);
354 self
355 }
356
357 pub fn max_height(mut self, value: u32) -> Self {
359 self.constraints.max_height = Some(value);
360 self
361 }
362
363 pub fn constraints(mut self, constraints: Constraints) -> Self {
365 self.constraints = constraints;
366 self
367 }
368
369 pub fn gap(mut self, gap: u32) -> Self {
373 self.gap = gap;
374 self
375 }
376
377 pub fn grow(mut self, grow: u16) -> Self {
379 self.grow = grow;
380 self
381 }
382
383 pub fn align(mut self, align: Align) -> Self {
387 self.align = align;
388 self
389 }
390
391 pub fn center(self) -> Self {
393 self.align(Align::Center)
394 }
395
396 pub fn title(self, title: impl Into<String>) -> Self {
400 self.title_styled(title, Style::new())
401 }
402
403 pub fn title_styled(mut self, title: impl Into<String>, style: Style) -> Self {
405 self.title = Some((title.into(), style));
406 self
407 }
408
409 pub fn scroll_offset(mut self, offset: u32) -> Self {
413 self.scroll_offset = Some(offset);
414 self
415 }
416
417 pub fn col(self, f: impl FnOnce(&mut Context)) -> Response {
422 self.finish(Direction::Column, f)
423 }
424
425 pub fn row(self, f: impl FnOnce(&mut Context)) -> Response {
430 self.finish(Direction::Row, f)
431 }
432
433 fn finish(self, direction: Direction, f: impl FnOnce(&mut Context)) -> Response {
434 let interaction_id = self.ctx.interaction_count;
435 self.ctx.interaction_count += 1;
436
437 if let Some(scroll_offset) = self.scroll_offset {
438 self.ctx.commands.push(Command::BeginScrollable {
439 grow: self.grow,
440 border: self.border,
441 border_style: self.border_style,
442 padding: self.padding,
443 margin: self.margin,
444 constraints: self.constraints,
445 title: self.title,
446 scroll_offset,
447 });
448 } else {
449 self.ctx.commands.push(Command::BeginContainer {
450 direction,
451 gap: self.gap,
452 align: self.align,
453 border: self.border,
454 border_style: self.border_style,
455 padding: self.padding,
456 margin: self.margin,
457 constraints: self.constraints,
458 title: self.title,
459 grow: self.grow,
460 });
461 }
462 f(self.ctx);
463 self.ctx.commands.push(Command::EndContainer);
464 self.ctx.last_text_idx = None;
465
466 self.ctx.response_for(interaction_id)
467 }
468}
469
470impl Context {
471 #[allow(clippy::too_many_arguments)]
472 pub(crate) fn new(
473 events: Vec<Event>,
474 width: u32,
475 height: u32,
476 tick: u64,
477 focus_index: usize,
478 prev_focus_count: usize,
479 prev_scroll_infos: Vec<(u32, u32)>,
480 prev_hit_map: Vec<Rect>,
481 debug: bool,
482 theme: Theme,
483 last_mouse_pos: Option<(u32, u32)>,
484 ) -> Self {
485 let consumed = vec![false; events.len()];
486
487 let mut mouse_pos = last_mouse_pos;
488 let mut click_pos = None;
489 for event in &events {
490 if let Event::Mouse(mouse) = event {
491 mouse_pos = Some((mouse.x, mouse.y));
492 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
493 click_pos = Some((mouse.x, mouse.y));
494 }
495 }
496 }
497
498 Self {
499 commands: Vec::new(),
500 events,
501 consumed,
502 should_quit: false,
503 area_width: width,
504 area_height: height,
505 tick,
506 focus_index,
507 focus_count: 0,
508 prev_focus_count,
509 scroll_count: 0,
510 prev_scroll_infos,
511 interaction_count: 0,
512 prev_hit_map,
513 mouse_pos,
514 click_pos,
515 last_mouse_pos,
516 last_text_idx: None,
517 debug,
518 theme,
519 }
520 }
521
522 pub(crate) fn process_focus_keys(&mut self) {
523 for (i, event) in self.events.iter().enumerate() {
524 if let Event::Key(key) = event {
525 if key.code == KeyCode::Tab && !key.modifiers.contains(KeyModifiers::SHIFT) {
526 if self.prev_focus_count > 0 {
527 self.focus_index = (self.focus_index + 1) % self.prev_focus_count;
528 }
529 self.consumed[i] = true;
530 } else if (key.code == KeyCode::Tab && key.modifiers.contains(KeyModifiers::SHIFT))
531 || key.code == KeyCode::BackTab
532 {
533 if self.prev_focus_count > 0 {
534 self.focus_index = if self.focus_index == 0 {
535 self.prev_focus_count - 1
536 } else {
537 self.focus_index - 1
538 };
539 }
540 self.consumed[i] = true;
541 }
542 }
543 }
544 }
545
546 pub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response {
550 w.ui(self)
551 }
552
553 pub fn interaction(&mut self) -> Response {
559 let id = self.interaction_count;
560 self.interaction_count += 1;
561 self.response_for(id)
562 }
563
564 pub fn register_focusable(&mut self) -> bool {
569 let id = self.focus_count;
570 self.focus_count += 1;
571 if self.prev_focus_count == 0 {
572 return true;
573 }
574 self.focus_index % self.prev_focus_count == id
575 }
576
577 pub fn text(&mut self, s: impl Into<String>) -> &mut Self {
590 let content = s.into();
591 self.commands.push(Command::Text {
592 content,
593 style: Style::new(),
594 grow: 0,
595 align: Align::Start,
596 wrap: false,
597 margin: Margin::default(),
598 constraints: Constraints::default(),
599 });
600 self.last_text_idx = Some(self.commands.len() - 1);
601 self
602 }
603
604 pub fn text_wrap(&mut self, s: impl Into<String>) -> &mut Self {
609 let content = s.into();
610 self.commands.push(Command::Text {
611 content,
612 style: Style::new(),
613 grow: 0,
614 align: Align::Start,
615 wrap: true,
616 margin: Margin::default(),
617 constraints: Constraints::default(),
618 });
619 self.last_text_idx = Some(self.commands.len() - 1);
620 self
621 }
622
623 pub fn bold(&mut self) -> &mut Self {
627 self.modify_last_style(|s| s.modifiers |= Modifiers::BOLD);
628 self
629 }
630
631 pub fn dim(&mut self) -> &mut Self {
636 let text_dim = self.theme.text_dim;
637 self.modify_last_style(|s| {
638 s.modifiers |= Modifiers::DIM;
639 if s.fg.is_none() {
640 s.fg = Some(text_dim);
641 }
642 });
643 self
644 }
645
646 pub fn italic(&mut self) -> &mut Self {
648 self.modify_last_style(|s| s.modifiers |= Modifiers::ITALIC);
649 self
650 }
651
652 pub fn underline(&mut self) -> &mut Self {
654 self.modify_last_style(|s| s.modifiers |= Modifiers::UNDERLINE);
655 self
656 }
657
658 pub fn reversed(&mut self) -> &mut Self {
660 self.modify_last_style(|s| s.modifiers |= Modifiers::REVERSED);
661 self
662 }
663
664 pub fn strikethrough(&mut self) -> &mut Self {
666 self.modify_last_style(|s| s.modifiers |= Modifiers::STRIKETHROUGH);
667 self
668 }
669
670 pub fn fg(&mut self, color: Color) -> &mut Self {
672 self.modify_last_style(|s| s.fg = Some(color));
673 self
674 }
675
676 pub fn bg(&mut self, color: Color) -> &mut Self {
678 self.modify_last_style(|s| s.bg = Some(color));
679 self
680 }
681
682 pub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self {
687 self.commands.push(Command::Text {
688 content: s.into(),
689 style,
690 grow: 0,
691 align: Align::Start,
692 wrap: false,
693 margin: Margin::default(),
694 constraints: Constraints::default(),
695 });
696 self.last_text_idx = Some(self.commands.len() - 1);
697 self
698 }
699
700 pub fn wrap(&mut self) -> &mut Self {
702 if let Some(idx) = self.last_text_idx {
703 if let Command::Text { wrap, .. } = &mut self.commands[idx] {
704 *wrap = true;
705 }
706 }
707 self
708 }
709
710 fn modify_last_style(&mut self, f: impl FnOnce(&mut Style)) {
711 if let Some(idx) = self.last_text_idx {
712 if let Command::Text { style, .. } = &mut self.commands[idx] {
713 f(style);
714 }
715 }
716 }
717
718 pub fn col(&mut self, f: impl FnOnce(&mut Context)) -> Response {
736 self.push_container(Direction::Column, 0, f)
737 }
738
739 pub fn col_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response {
743 self.push_container(Direction::Column, gap, f)
744 }
745
746 pub fn row(&mut self, f: impl FnOnce(&mut Context)) -> Response {
763 self.push_container(Direction::Row, 0, f)
764 }
765
766 pub fn row_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response {
770 self.push_container(Direction::Row, gap, f)
771 }
772
773 pub fn container(&mut self) -> ContainerBuilder<'_> {
794 let border = self.theme.border;
795 ContainerBuilder {
796 ctx: self,
797 gap: 0,
798 align: Align::Start,
799 border: None,
800 border_style: Style::new().fg(border),
801 padding: Padding::default(),
802 margin: Margin::default(),
803 constraints: Constraints::default(),
804 title: None,
805 grow: 0,
806 scroll_offset: None,
807 }
808 }
809
810 pub fn scrollable(&mut self, state: &mut ScrollState) -> ContainerBuilder<'_> {
829 let index = self.scroll_count;
830 self.scroll_count += 1;
831 if let Some(&(ch, vh)) = self.prev_scroll_infos.get(index) {
832 state.set_bounds(ch, vh);
833 let max = ch.saturating_sub(vh) as usize;
834 state.offset = state.offset.min(max);
835 }
836
837 let next_id = self.interaction_count;
838 if let Some(rect) = self.prev_hit_map.get(next_id).copied() {
839 self.auto_scroll(&rect, state);
840 }
841
842 self.container().scroll_offset(state.offset as u32)
843 }
844
845 fn auto_scroll(&mut self, rect: &Rect, state: &mut ScrollState) {
846 let last_y = self.last_mouse_pos.map(|(_, y)| y);
847 let mut to_consume: Vec<usize> = Vec::new();
848
849 for (i, event) in self.events.iter().enumerate() {
850 if self.consumed[i] {
851 continue;
852 }
853 if let Event::Mouse(mouse) = event {
854 let in_bounds = mouse.x >= rect.x
855 && mouse.x < rect.right()
856 && mouse.y >= rect.y
857 && mouse.y < rect.bottom();
858 if !in_bounds {
859 continue;
860 }
861 match mouse.kind {
862 MouseKind::ScrollUp => {
863 state.scroll_up(1);
864 to_consume.push(i);
865 }
866 MouseKind::ScrollDown => {
867 state.scroll_down(1);
868 to_consume.push(i);
869 }
870 MouseKind::Drag(MouseButton::Left) => {
871 if let Some(prev_y) = last_y {
872 let delta = mouse.y as i32 - prev_y as i32;
873 if delta < 0 {
874 state.scroll_down((-delta) as usize);
875 } else if delta > 0 {
876 state.scroll_up(delta as usize);
877 }
878 }
879 to_consume.push(i);
880 }
881 _ => {}
882 }
883 }
884 }
885
886 for i in to_consume {
887 self.consumed[i] = true;
888 }
889 }
890
891 pub fn bordered(&mut self, border: Border) -> ContainerBuilder<'_> {
895 self.container().border(border)
896 }
897
898 fn push_container(
899 &mut self,
900 direction: Direction,
901 gap: u32,
902 f: impl FnOnce(&mut Context),
903 ) -> Response {
904 let interaction_id = self.interaction_count;
905 self.interaction_count += 1;
906 let border = self.theme.border;
907
908 self.commands.push(Command::BeginContainer {
909 direction,
910 gap,
911 align: Align::Start,
912 border: None,
913 border_style: Style::new().fg(border),
914 padding: Padding::default(),
915 margin: Margin::default(),
916 constraints: Constraints::default(),
917 title: None,
918 grow: 0,
919 });
920 f(self);
921 self.commands.push(Command::EndContainer);
922 self.last_text_idx = None;
923
924 self.response_for(interaction_id)
925 }
926
927 fn response_for(&self, interaction_id: usize) -> Response {
928 if let Some(rect) = self.prev_hit_map.get(interaction_id) {
929 let clicked = self
930 .click_pos
931 .map(|(mx, my)| {
932 mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom()
933 })
934 .unwrap_or(false);
935 let hovered = self
936 .mouse_pos
937 .map(|(mx, my)| {
938 mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom()
939 })
940 .unwrap_or(false);
941 Response { clicked, hovered }
942 } else {
943 Response::default()
944 }
945 }
946
947 pub fn grow(&mut self, value: u16) -> &mut Self {
952 if let Some(idx) = self.last_text_idx {
953 if let Command::Text { grow, .. } = &mut self.commands[idx] {
954 *grow = value;
955 }
956 }
957 self
958 }
959
960 pub fn align(&mut self, align: Align) -> &mut Self {
962 if let Some(idx) = self.last_text_idx {
963 if let Command::Text {
964 align: text_align, ..
965 } = &mut self.commands[idx]
966 {
967 *text_align = align;
968 }
969 }
970 self
971 }
972
973 pub fn spacer(&mut self) -> &mut Self {
977 self.commands.push(Command::Spacer { grow: 1 });
978 self.last_text_idx = None;
979 self
980 }
981
982 pub fn text_input(&mut self, state: &mut TextInputState) -> &mut Self {
998 let focused = self.register_focusable();
999
1000 if focused {
1001 let mut consumed_indices = Vec::new();
1002 for (i, event) in self.events.iter().enumerate() {
1003 if let Event::Key(key) = event {
1004 match key.code {
1005 KeyCode::Char(ch) => {
1006 if let Some(max) = state.max_length {
1007 if state.value.chars().count() >= max {
1008 continue;
1009 }
1010 }
1011 let index = byte_index_for_char(&state.value, state.cursor);
1012 state.value.insert(index, ch);
1013 state.cursor += 1;
1014 consumed_indices.push(i);
1015 }
1016 KeyCode::Backspace => {
1017 if state.cursor > 0 {
1018 let start = byte_index_for_char(&state.value, state.cursor - 1);
1019 let end = byte_index_for_char(&state.value, state.cursor);
1020 state.value.replace_range(start..end, "");
1021 state.cursor -= 1;
1022 }
1023 consumed_indices.push(i);
1024 }
1025 KeyCode::Left => {
1026 state.cursor = state.cursor.saturating_sub(1);
1027 consumed_indices.push(i);
1028 }
1029 KeyCode::Right => {
1030 state.cursor = (state.cursor + 1).min(state.value.chars().count());
1031 consumed_indices.push(i);
1032 }
1033 KeyCode::Home => {
1034 state.cursor = 0;
1035 consumed_indices.push(i);
1036 }
1037 KeyCode::End => {
1038 state.cursor = state.value.chars().count();
1039 consumed_indices.push(i);
1040 }
1041 _ => {}
1042 }
1043 }
1044 }
1045
1046 for index in consumed_indices {
1047 self.consumed[index] = true;
1048 }
1049 }
1050
1051 if state.value.is_empty() {
1052 self.styled(
1053 state.placeholder.clone(),
1054 Style::new().dim().fg(self.theme.text_dim),
1055 )
1056 } else {
1057 let mut rendered = String::new();
1058 for (idx, ch) in state.value.chars().enumerate() {
1059 if focused && idx == state.cursor {
1060 rendered.push('▎');
1061 }
1062 rendered.push(ch);
1063 }
1064 if focused && state.cursor >= state.value.chars().count() {
1065 rendered.push('▎');
1066 }
1067 self.styled(rendered, Style::new().fg(self.theme.text))
1068 }
1069 }
1070
1071 pub fn spinner(&mut self, state: &SpinnerState) -> &mut Self {
1077 self.styled(
1078 state.frame(self.tick).to_string(),
1079 Style::new().fg(self.theme.primary),
1080 )
1081 }
1082
1083 pub fn toast(&mut self, state: &mut ToastState) -> &mut Self {
1088 state.cleanup(self.tick);
1089 if state.messages.is_empty() {
1090 return self;
1091 }
1092
1093 self.interaction_count += 1;
1094 self.commands.push(Command::BeginContainer {
1095 direction: Direction::Column,
1096 gap: 0,
1097 align: Align::Start,
1098 border: None,
1099 border_style: Style::new().fg(self.theme.border),
1100 padding: Padding::default(),
1101 margin: Margin::default(),
1102 constraints: Constraints::default(),
1103 title: None,
1104 grow: 0,
1105 });
1106 for message in state.messages.iter().rev() {
1107 let color = match message.level {
1108 ToastLevel::Info => self.theme.primary,
1109 ToastLevel::Success => self.theme.success,
1110 ToastLevel::Warning => self.theme.warning,
1111 ToastLevel::Error => self.theme.error,
1112 };
1113 self.styled(format!(" ● {}", message.text), Style::new().fg(color));
1114 }
1115 self.commands.push(Command::EndContainer);
1116 self.last_text_idx = None;
1117
1118 self
1119 }
1120
1121 pub fn textarea(&mut self, state: &mut TextareaState, visible_rows: u32) -> &mut Self {
1126 if state.lines.is_empty() {
1127 state.lines.push(String::new());
1128 }
1129 state.cursor_row = state.cursor_row.min(state.lines.len().saturating_sub(1));
1130 state.cursor_col = state
1131 .cursor_col
1132 .min(state.lines[state.cursor_row].chars().count());
1133
1134 let focused = self.register_focusable();
1135
1136 if focused {
1137 let mut consumed_indices = Vec::new();
1138 for (i, event) in self.events.iter().enumerate() {
1139 if let Event::Key(key) = event {
1140 match key.code {
1141 KeyCode::Char(ch) => {
1142 if let Some(max) = state.max_length {
1143 let total: usize =
1144 state.lines.iter().map(|line| line.chars().count()).sum();
1145 if total >= max {
1146 continue;
1147 }
1148 }
1149 let index = byte_index_for_char(
1150 &state.lines[state.cursor_row],
1151 state.cursor_col,
1152 );
1153 state.lines[state.cursor_row].insert(index, ch);
1154 state.cursor_col += 1;
1155 consumed_indices.push(i);
1156 }
1157 KeyCode::Enter => {
1158 let split_index = byte_index_for_char(
1159 &state.lines[state.cursor_row],
1160 state.cursor_col,
1161 );
1162 let remainder = state.lines[state.cursor_row].split_off(split_index);
1163 state.cursor_row += 1;
1164 state.lines.insert(state.cursor_row, remainder);
1165 state.cursor_col = 0;
1166 consumed_indices.push(i);
1167 }
1168 KeyCode::Backspace => {
1169 if state.cursor_col > 0 {
1170 let start = byte_index_for_char(
1171 &state.lines[state.cursor_row],
1172 state.cursor_col - 1,
1173 );
1174 let end = byte_index_for_char(
1175 &state.lines[state.cursor_row],
1176 state.cursor_col,
1177 );
1178 state.lines[state.cursor_row].replace_range(start..end, "");
1179 state.cursor_col -= 1;
1180 } else if state.cursor_row > 0 {
1181 let current = state.lines.remove(state.cursor_row);
1182 state.cursor_row -= 1;
1183 state.cursor_col = state.lines[state.cursor_row].chars().count();
1184 state.lines[state.cursor_row].push_str(¤t);
1185 }
1186 consumed_indices.push(i);
1187 }
1188 KeyCode::Left => {
1189 if state.cursor_col > 0 {
1190 state.cursor_col -= 1;
1191 } else if state.cursor_row > 0 {
1192 state.cursor_row -= 1;
1193 state.cursor_col = state.lines[state.cursor_row].chars().count();
1194 }
1195 consumed_indices.push(i);
1196 }
1197 KeyCode::Right => {
1198 let line_len = state.lines[state.cursor_row].chars().count();
1199 if state.cursor_col < line_len {
1200 state.cursor_col += 1;
1201 } else if state.cursor_row + 1 < state.lines.len() {
1202 state.cursor_row += 1;
1203 state.cursor_col = 0;
1204 }
1205 consumed_indices.push(i);
1206 }
1207 KeyCode::Up => {
1208 if state.cursor_row > 0 {
1209 state.cursor_row -= 1;
1210 state.cursor_col = state
1211 .cursor_col
1212 .min(state.lines[state.cursor_row].chars().count());
1213 }
1214 consumed_indices.push(i);
1215 }
1216 KeyCode::Down => {
1217 if state.cursor_row + 1 < state.lines.len() {
1218 state.cursor_row += 1;
1219 state.cursor_col = state
1220 .cursor_col
1221 .min(state.lines[state.cursor_row].chars().count());
1222 }
1223 consumed_indices.push(i);
1224 }
1225 KeyCode::Home => {
1226 state.cursor_col = 0;
1227 consumed_indices.push(i);
1228 }
1229 KeyCode::End => {
1230 state.cursor_col = state.lines[state.cursor_row].chars().count();
1231 consumed_indices.push(i);
1232 }
1233 _ => {}
1234 }
1235 }
1236 }
1237
1238 for index in consumed_indices {
1239 self.consumed[index] = true;
1240 }
1241 }
1242
1243 self.interaction_count += 1;
1244 self.commands.push(Command::BeginContainer {
1245 direction: Direction::Column,
1246 gap: 0,
1247 align: Align::Start,
1248 border: None,
1249 border_style: Style::new().fg(self.theme.border),
1250 padding: Padding::default(),
1251 margin: Margin::default(),
1252 constraints: Constraints::default(),
1253 title: None,
1254 grow: 0,
1255 });
1256 for row in 0..visible_rows as usize {
1257 let line = state.lines.get(row).cloned().unwrap_or_default();
1258 let mut rendered = line.clone();
1259 let mut style = if line.is_empty() {
1260 Style::new().fg(self.theme.text_dim)
1261 } else {
1262 Style::new().fg(self.theme.text)
1263 };
1264
1265 if focused && row == state.cursor_row {
1266 rendered.clear();
1267 for (idx, ch) in line.chars().enumerate() {
1268 if idx == state.cursor_col {
1269 rendered.push('▎');
1270 }
1271 rendered.push(ch);
1272 }
1273 if state.cursor_col >= line.chars().count() {
1274 rendered.push('▎');
1275 }
1276 style = Style::new().fg(self.theme.text);
1277 }
1278
1279 self.styled(rendered, style);
1280 }
1281 self.commands.push(Command::EndContainer);
1282 self.last_text_idx = None;
1283
1284 self
1285 }
1286
1287 pub fn progress(&mut self, ratio: f64) -> &mut Self {
1292 self.progress_bar(ratio, 20)
1293 }
1294
1295 pub fn progress_bar(&mut self, ratio: f64, width: u32) -> &mut Self {
1300 let clamped = ratio.clamp(0.0, 1.0);
1301 let filled = (clamped * width as f64).round() as u32;
1302 let empty = width.saturating_sub(filled);
1303 let mut bar = String::new();
1304 for _ in 0..filled {
1305 bar.push('█');
1306 }
1307 for _ in 0..empty {
1308 bar.push('░');
1309 }
1310 self.text(bar)
1311 }
1312
1313 pub fn list(&mut self, state: &mut ListState) -> &mut Self {
1318 if state.items.is_empty() {
1319 state.selected = 0;
1320 return self;
1321 }
1322
1323 let focused = self.register_focusable();
1324
1325 if focused {
1326 let mut consumed_indices = Vec::new();
1327 for (i, event) in self.events.iter().enumerate() {
1328 if let Event::Key(key) = event {
1329 match key.code {
1330 KeyCode::Up | KeyCode::Char('k') => {
1331 state.selected = state.selected.saturating_sub(1);
1332 consumed_indices.push(i);
1333 }
1334 KeyCode::Down | KeyCode::Char('j') => {
1335 state.selected =
1336 (state.selected + 1).min(state.items.len().saturating_sub(1));
1337 consumed_indices.push(i);
1338 }
1339 _ => {}
1340 }
1341 }
1342 }
1343
1344 for index in consumed_indices {
1345 self.consumed[index] = true;
1346 }
1347 }
1348
1349 for (idx, item) in state.items.iter().enumerate() {
1350 if idx == state.selected {
1351 if focused {
1352 self.styled(
1353 format!("▸ {item}"),
1354 Style::new().bold().fg(self.theme.primary),
1355 );
1356 } else {
1357 self.styled(format!("▸ {item}"), Style::new().fg(self.theme.primary));
1358 }
1359 } else {
1360 self.styled(format!(" {item}"), Style::new().fg(self.theme.text));
1361 }
1362 }
1363
1364 self
1365 }
1366
1367 pub fn table(&mut self, state: &mut TableState) -> &mut Self {
1372 if state.is_dirty() {
1373 state.recompute_widths();
1374 }
1375
1376 let focused = self.register_focusable();
1377
1378 if focused && !state.rows.is_empty() {
1379 let mut consumed_indices = Vec::new();
1380 for (i, event) in self.events.iter().enumerate() {
1381 if let Event::Key(key) = event {
1382 match key.code {
1383 KeyCode::Up | KeyCode::Char('k') => {
1384 state.selected = state.selected.saturating_sub(1);
1385 consumed_indices.push(i);
1386 }
1387 KeyCode::Down | KeyCode::Char('j') => {
1388 state.selected =
1389 (state.selected + 1).min(state.rows.len().saturating_sub(1));
1390 consumed_indices.push(i);
1391 }
1392 _ => {}
1393 }
1394 }
1395 }
1396 for index in consumed_indices {
1397 self.consumed[index] = true;
1398 }
1399 }
1400
1401 state.selected = state.selected.min(state.rows.len().saturating_sub(1));
1402
1403 let header_line = format_table_row(&state.headers, state.column_widths(), " │ ");
1404 self.styled(header_line, Style::new().bold().fg(self.theme.text));
1405
1406 let separator = state
1407 .column_widths()
1408 .iter()
1409 .map(|w| "─".repeat(*w as usize))
1410 .collect::<Vec<_>>()
1411 .join("─┼─");
1412 self.text(separator);
1413
1414 for (idx, row) in state.rows.iter().enumerate() {
1415 let line = format_table_row(row, state.column_widths(), " │ ");
1416 if idx == state.selected {
1417 let mut style = Style::new()
1418 .bg(self.theme.selected_bg)
1419 .fg(self.theme.selected_fg);
1420 if focused {
1421 style = style.bold();
1422 }
1423 self.styled(line, style);
1424 } else {
1425 self.styled(line, Style::new().fg(self.theme.text));
1426 }
1427 }
1428
1429 self
1430 }
1431
1432 pub fn tabs(&mut self, state: &mut TabsState) -> &mut Self {
1437 if state.labels.is_empty() {
1438 state.selected = 0;
1439 return self;
1440 }
1441
1442 state.selected = state.selected.min(state.labels.len().saturating_sub(1));
1443 let focused = self.register_focusable();
1444
1445 if focused {
1446 let mut consumed_indices = Vec::new();
1447 for (i, event) in self.events.iter().enumerate() {
1448 if let Event::Key(key) = event {
1449 match key.code {
1450 KeyCode::Left => {
1451 state.selected = if state.selected == 0 {
1452 state.labels.len().saturating_sub(1)
1453 } else {
1454 state.selected - 1
1455 };
1456 consumed_indices.push(i);
1457 }
1458 KeyCode::Right => {
1459 state.selected = (state.selected + 1) % state.labels.len();
1460 consumed_indices.push(i);
1461 }
1462 _ => {}
1463 }
1464 }
1465 }
1466
1467 for index in consumed_indices {
1468 self.consumed[index] = true;
1469 }
1470 }
1471
1472 self.interaction_count += 1;
1473 self.commands.push(Command::BeginContainer {
1474 direction: Direction::Row,
1475 gap: 1,
1476 align: Align::Start,
1477 border: None,
1478 border_style: Style::new().fg(self.theme.border),
1479 padding: Padding::default(),
1480 margin: Margin::default(),
1481 constraints: Constraints::default(),
1482 title: None,
1483 grow: 0,
1484 });
1485 for (idx, label) in state.labels.iter().enumerate() {
1486 let style = if idx == state.selected {
1487 let s = Style::new().fg(self.theme.primary).bold();
1488 if focused {
1489 s.underline()
1490 } else {
1491 s
1492 }
1493 } else {
1494 Style::new().fg(self.theme.text_dim)
1495 };
1496 self.styled(format!("[ {label} ]"), style);
1497 }
1498 self.commands.push(Command::EndContainer);
1499 self.last_text_idx = None;
1500
1501 self
1502 }
1503
1504 pub fn button(&mut self, label: impl Into<String>) -> bool {
1509 let focused = self.register_focusable();
1510 let interaction_id = self.interaction_count;
1511 self.interaction_count += 1;
1512 let response = self.response_for(interaction_id);
1513
1514 let mut activated = response.clicked;
1515 if focused {
1516 let mut consumed_indices = Vec::new();
1517 for (i, event) in self.events.iter().enumerate() {
1518 if let Event::Key(key) = event {
1519 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
1520 activated = true;
1521 consumed_indices.push(i);
1522 }
1523 }
1524 }
1525
1526 for index in consumed_indices {
1527 self.consumed[index] = true;
1528 }
1529 }
1530
1531 let style = if focused {
1532 Style::new().fg(self.theme.primary).bold()
1533 } else if response.hovered {
1534 Style::new().fg(self.theme.accent)
1535 } else {
1536 Style::new().fg(self.theme.text)
1537 };
1538
1539 self.commands.push(Command::BeginContainer {
1540 direction: Direction::Row,
1541 gap: 0,
1542 align: Align::Start,
1543 border: None,
1544 border_style: Style::new().fg(self.theme.border),
1545 padding: Padding::default(),
1546 margin: Margin::default(),
1547 constraints: Constraints::default(),
1548 title: None,
1549 grow: 0,
1550 });
1551 self.styled(format!("[ {} ]", label.into()), style);
1552 self.commands.push(Command::EndContainer);
1553 self.last_text_idx = None;
1554
1555 activated
1556 }
1557
1558 pub fn checkbox(&mut self, label: impl Into<String>, checked: &mut bool) -> &mut Self {
1563 let focused = self.register_focusable();
1564 let interaction_id = self.interaction_count;
1565 self.interaction_count += 1;
1566 let response = self.response_for(interaction_id);
1567 let mut should_toggle = response.clicked;
1568
1569 if focused {
1570 let mut consumed_indices = Vec::new();
1571 for (i, event) in self.events.iter().enumerate() {
1572 if let Event::Key(key) = event {
1573 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
1574 should_toggle = true;
1575 consumed_indices.push(i);
1576 }
1577 }
1578 }
1579
1580 for index in consumed_indices {
1581 self.consumed[index] = true;
1582 }
1583 }
1584
1585 if should_toggle {
1586 *checked = !*checked;
1587 }
1588
1589 self.commands.push(Command::BeginContainer {
1590 direction: Direction::Row,
1591 gap: 1,
1592 align: Align::Start,
1593 border: None,
1594 border_style: Style::new().fg(self.theme.border),
1595 padding: Padding::default(),
1596 margin: Margin::default(),
1597 constraints: Constraints::default(),
1598 title: None,
1599 grow: 0,
1600 });
1601 let marker_style = if *checked {
1602 Style::new().fg(self.theme.success)
1603 } else {
1604 Style::new().fg(self.theme.text_dim)
1605 };
1606 let marker = if *checked { "[x]" } else { "[ ]" };
1607 let label_text = label.into();
1608 if focused {
1609 self.styled(format!("▸ {marker}"), marker_style.bold());
1610 self.styled(label_text, Style::new().fg(self.theme.text).bold());
1611 } else {
1612 self.styled(marker, marker_style);
1613 self.styled(label_text, Style::new().fg(self.theme.text));
1614 }
1615 self.commands.push(Command::EndContainer);
1616 self.last_text_idx = None;
1617
1618 self
1619 }
1620
1621 pub fn toggle(&mut self, label: impl Into<String>, on: &mut bool) -> &mut Self {
1627 let focused = self.register_focusable();
1628 let interaction_id = self.interaction_count;
1629 self.interaction_count += 1;
1630 let response = self.response_for(interaction_id);
1631 let mut should_toggle = response.clicked;
1632
1633 if focused {
1634 let mut consumed_indices = Vec::new();
1635 for (i, event) in self.events.iter().enumerate() {
1636 if let Event::Key(key) = event {
1637 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
1638 should_toggle = true;
1639 consumed_indices.push(i);
1640 }
1641 }
1642 }
1643
1644 for index in consumed_indices {
1645 self.consumed[index] = true;
1646 }
1647 }
1648
1649 if should_toggle {
1650 *on = !*on;
1651 }
1652
1653 self.commands.push(Command::BeginContainer {
1654 direction: Direction::Row,
1655 gap: 2,
1656 align: Align::Start,
1657 border: None,
1658 border_style: Style::new().fg(self.theme.border),
1659 padding: Padding::default(),
1660 margin: Margin::default(),
1661 constraints: Constraints::default(),
1662 title: None,
1663 grow: 0,
1664 });
1665 let label_text = label.into();
1666 let switch = if *on { "●━━ ON" } else { "━━● OFF" };
1667 let switch_style = if *on {
1668 Style::new().fg(self.theme.success)
1669 } else {
1670 Style::new().fg(self.theme.text_dim)
1671 };
1672 if focused {
1673 self.styled(
1674 format!("▸ {label_text}"),
1675 Style::new().fg(self.theme.text).bold(),
1676 );
1677 self.styled(switch, switch_style.bold());
1678 } else {
1679 self.styled(label_text, Style::new().fg(self.theme.text));
1680 self.styled(switch, switch_style);
1681 }
1682 self.commands.push(Command::EndContainer);
1683 self.last_text_idx = None;
1684
1685 self
1686 }
1687
1688 pub fn separator(&mut self) -> &mut Self {
1693 self.commands.push(Command::Text {
1694 content: "─".repeat(200),
1695 style: Style::new().fg(self.theme.border).dim(),
1696 grow: 0,
1697 align: Align::Start,
1698 wrap: false,
1699 margin: Margin::default(),
1700 constraints: Constraints::default(),
1701 });
1702 self.last_text_idx = Some(self.commands.len() - 1);
1703 self
1704 }
1705
1706 pub fn help(&mut self, bindings: &[(&str, &str)]) -> &mut Self {
1712 if bindings.is_empty() {
1713 return self;
1714 }
1715
1716 self.interaction_count += 1;
1717 self.commands.push(Command::BeginContainer {
1718 direction: Direction::Row,
1719 gap: 2,
1720 align: Align::Start,
1721 border: None,
1722 border_style: Style::new().fg(self.theme.border),
1723 padding: Padding::default(),
1724 margin: Margin::default(),
1725 constraints: Constraints::default(),
1726 title: None,
1727 grow: 0,
1728 });
1729 for (idx, (key, action)) in bindings.iter().enumerate() {
1730 if idx > 0 {
1731 self.styled("·", Style::new().fg(self.theme.text_dim));
1732 }
1733 self.styled(*key, Style::new().bold().fg(self.theme.primary));
1734 self.styled(*action, Style::new().fg(self.theme.text_dim));
1735 }
1736 self.commands.push(Command::EndContainer);
1737 self.last_text_idx = None;
1738
1739 self
1740 }
1741
1742 pub fn key(&self, c: char) -> bool {
1748 self.events.iter().enumerate().any(|(i, e)| {
1749 !self.consumed[i] && matches!(e, Event::Key(k) if k.code == KeyCode::Char(c))
1750 })
1751 }
1752
1753 pub fn key_code(&self, code: KeyCode) -> bool {
1757 self.events
1758 .iter()
1759 .enumerate()
1760 .any(|(i, e)| !self.consumed[i] && matches!(e, Event::Key(k) if k.code == code))
1761 }
1762
1763 pub fn key_mod(&self, c: char, modifiers: KeyModifiers) -> bool {
1767 self.events.iter().enumerate().any(|(i, e)| {
1768 !self.consumed[i]
1769 && matches!(e, Event::Key(k) if k.code == KeyCode::Char(c) && k.modifiers.contains(modifiers))
1770 })
1771 }
1772
1773 pub fn mouse_down(&self) -> Option<(u32, u32)> {
1777 self.events.iter().enumerate().find_map(|(i, event)| {
1778 if self.consumed[i] {
1779 return None;
1780 }
1781 if let Event::Mouse(mouse) = event {
1782 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
1783 return Some((mouse.x, mouse.y));
1784 }
1785 }
1786 None
1787 })
1788 }
1789
1790 pub fn mouse_pos(&self) -> Option<(u32, u32)> {
1795 self.mouse_pos
1796 }
1797
1798 pub fn scroll_up(&self) -> bool {
1800 self.events.iter().enumerate().any(|(i, event)| {
1801 !self.consumed[i]
1802 && matches!(event, Event::Mouse(mouse) if matches!(mouse.kind, MouseKind::ScrollUp))
1803 })
1804 }
1805
1806 pub fn scroll_down(&self) -> bool {
1808 self.events.iter().enumerate().any(|(i, event)| {
1809 !self.consumed[i]
1810 && matches!(event, Event::Mouse(mouse) if matches!(mouse.kind, MouseKind::ScrollDown))
1811 })
1812 }
1813
1814 pub fn quit(&mut self) {
1816 self.should_quit = true;
1817 }
1818
1819 pub fn theme(&self) -> &Theme {
1821 &self.theme
1822 }
1823
1824 pub fn set_theme(&mut self, theme: Theme) {
1828 self.theme = theme;
1829 }
1830
1831 pub fn width(&self) -> u32 {
1835 self.area_width
1836 }
1837
1838 pub fn height(&self) -> u32 {
1840 self.area_height
1841 }
1842
1843 pub fn tick(&self) -> u64 {
1848 self.tick
1849 }
1850
1851 pub fn debug_enabled(&self) -> bool {
1855 self.debug
1856 }
1857}
1858
1859fn byte_index_for_char(value: &str, char_index: usize) -> usize {
1860 if char_index == 0 {
1861 return 0;
1862 }
1863 value
1864 .char_indices()
1865 .nth(char_index)
1866 .map_or(value.len(), |(idx, _)| idx)
1867}
1868
1869fn format_table_row(cells: &[String], widths: &[u32], separator: &str) -> String {
1870 let mut parts: Vec<String> = Vec::new();
1871 for (i, width) in widths.iter().enumerate() {
1872 let cell = cells.get(i).map(String::as_str).unwrap_or("");
1873 let cell_width = UnicodeWidthStr::width(cell) as u32;
1874 let padding = (*width).saturating_sub(cell_width) as usize;
1875 parts.push(format!("{cell}{}", " ".repeat(padding)));
1876 }
1877 parts.join(separator)
1878}