1use crate::chart::{build_histogram_config, render_chart, ChartBuilder, HistogramBuilder};
2use crate::event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseKind};
3use crate::halfblock::HalfBlockImage;
4use crate::layout::{Command, Direction};
5use crate::rect::Rect;
6use crate::style::{
7 Align, Border, BorderSides, Breakpoint, Color, Constraints, Justify, Margin, Modifiers,
8 Padding, Style, Theme,
9};
10use crate::widgets::{
11 ApprovalAction, ButtonVariant, CommandPaletteState, ContextItem, FormField, FormState,
12 ListState, MultiSelectState, RadioState, ScrollState, SelectState, SpinnerState,
13 StreamingTextState, TableState, TabsState, TextInputState, TextareaState, ToastLevel,
14 ToastState, ToolApprovalState, TreeState,
15};
16use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
17
18#[allow(dead_code)]
19fn slt_assert(condition: bool, msg: &str) {
20 if !condition {
21 panic!("[SLT] {}", msg);
22 }
23}
24
25#[cfg(debug_assertions)]
26#[allow(dead_code)]
27fn slt_warn(msg: &str) {
28 eprintln!("\x1b[33m[SLT warning]\x1b[0m {}", msg);
29}
30
31#[cfg(not(debug_assertions))]
32#[allow(dead_code)]
33fn slt_warn(_msg: &str) {}
34
35pub struct State<T> {
37 idx: usize,
38 _marker: std::marker::PhantomData<T>,
39}
40
41impl<T: 'static> State<T> {
42 pub fn get<'a>(&self, ui: &'a Context) -> &'a T {
44 ui.hook_states[self.idx]
45 .downcast_ref::<T>()
46 .expect("use_state type mismatch")
47 }
48
49 pub fn get_mut<'a>(&self, ui: &'a mut Context) -> &'a mut T {
51 ui.hook_states[self.idx]
52 .downcast_mut::<T>()
53 .expect("use_state type mismatch")
54 }
55}
56
57#[derive(Debug, Clone, Copy, Default)]
63pub struct Response {
64 pub clicked: bool,
66 pub hovered: bool,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum BarDirection {
73 Horizontal,
75 Vertical,
77}
78
79#[derive(Debug, Clone)]
81pub struct Bar {
82 pub label: String,
84 pub value: f64,
86 pub color: Option<Color>,
88}
89
90impl Bar {
91 pub fn new(label: impl Into<String>, value: f64) -> Self {
93 Self {
94 label: label.into(),
95 value,
96 color: None,
97 }
98 }
99
100 pub fn color(mut self, color: Color) -> Self {
102 self.color = Some(color);
103 self
104 }
105}
106
107#[derive(Debug, Clone)]
109pub struct BarGroup {
110 pub label: String,
112 pub bars: Vec<Bar>,
114}
115
116impl BarGroup {
117 pub fn new(label: impl Into<String>, bars: Vec<Bar>) -> Self {
119 Self {
120 label: label.into(),
121 bars,
122 }
123 }
124}
125
126pub trait Widget {
188 type Response;
191
192 fn ui(&mut self, ctx: &mut Context) -> Self::Response;
198}
199
200pub struct Context {
216 pub(crate) commands: Vec<Command>,
217 pub(crate) events: Vec<Event>,
218 pub(crate) consumed: Vec<bool>,
219 pub(crate) should_quit: bool,
220 pub(crate) area_width: u32,
221 pub(crate) area_height: u32,
222 pub(crate) tick: u64,
223 pub(crate) focus_index: usize,
224 pub(crate) focus_count: usize,
225 pub(crate) hook_states: Vec<Box<dyn std::any::Any>>,
226 pub(crate) hook_cursor: usize,
227 prev_focus_count: usize,
228 scroll_count: usize,
229 prev_scroll_infos: Vec<(u32, u32)>,
230 prev_scroll_rects: Vec<Rect>,
231 interaction_count: usize,
232 pub(crate) prev_hit_map: Vec<Rect>,
233 pub(crate) group_stack: Vec<String>,
234 pub(crate) prev_group_rects: Vec<(String, Rect)>,
235 group_count: usize,
236 prev_focus_groups: Vec<Option<String>>,
237 _prev_focus_rects: Vec<(usize, Rect)>,
238 mouse_pos: Option<(u32, u32)>,
239 click_pos: Option<(u32, u32)>,
240 last_text_idx: Option<usize>,
241 overlay_depth: usize,
242 pub(crate) modal_active: bool,
243 prev_modal_active: bool,
244 pub(crate) clipboard_text: Option<String>,
245 debug: bool,
246 theme: Theme,
247 pub(crate) dark_mode: bool,
248}
249
250#[must_use = "configure and finalize with .col() or .row()"]
271pub struct ContainerBuilder<'a> {
272 ctx: &'a mut Context,
273 gap: u32,
274 align: Align,
275 justify: Justify,
276 border: Option<Border>,
277 border_sides: BorderSides,
278 border_style: Style,
279 bg_color: Option<Color>,
280 dark_bg_color: Option<Color>,
281 dark_border_style: Option<Style>,
282 group_hover_bg: Option<Color>,
283 group_hover_border_style: Option<Style>,
284 group_name: Option<String>,
285 padding: Padding,
286 margin: Margin,
287 constraints: Constraints,
288 title: Option<(String, Style)>,
289 grow: u16,
290 scroll_offset: Option<u32>,
291}
292
293#[derive(Debug, Clone, Copy)]
300struct CanvasPixel {
301 bits: u32,
302 color: Color,
303}
304
305#[derive(Debug, Clone)]
307struct CanvasLabel {
308 x: usize,
309 y: usize,
310 text: String,
311 color: Color,
312}
313
314#[derive(Debug, Clone)]
316struct CanvasLayer {
317 grid: Vec<Vec<CanvasPixel>>,
318 labels: Vec<CanvasLabel>,
319}
320
321pub struct CanvasContext {
322 layers: Vec<CanvasLayer>,
323 cols: usize,
324 rows: usize,
325 px_w: usize,
326 px_h: usize,
327 current_color: Color,
328}
329
330impl CanvasContext {
331 fn new(cols: usize, rows: usize) -> Self {
332 Self {
333 layers: vec![Self::new_layer(cols, rows)],
334 cols,
335 rows,
336 px_w: cols * 2,
337 px_h: rows * 4,
338 current_color: Color::Reset,
339 }
340 }
341
342 fn new_layer(cols: usize, rows: usize) -> CanvasLayer {
343 CanvasLayer {
344 grid: vec![
345 vec![
346 CanvasPixel {
347 bits: 0,
348 color: Color::Reset,
349 };
350 cols
351 ];
352 rows
353 ],
354 labels: Vec::new(),
355 }
356 }
357
358 fn current_layer_mut(&mut self) -> Option<&mut CanvasLayer> {
359 self.layers.last_mut()
360 }
361
362 fn dot_with_color(&mut self, x: usize, y: usize, color: Color) {
363 if x >= self.px_w || y >= self.px_h {
364 return;
365 }
366
367 let char_col = x / 2;
368 let char_row = y / 4;
369 let sub_col = x % 2;
370 let sub_row = y % 4;
371 const LEFT_BITS: [u32; 4] = [0x01, 0x02, 0x04, 0x40];
372 const RIGHT_BITS: [u32; 4] = [0x08, 0x10, 0x20, 0x80];
373
374 let bit = if sub_col == 0 {
375 LEFT_BITS[sub_row]
376 } else {
377 RIGHT_BITS[sub_row]
378 };
379
380 if let Some(layer) = self.current_layer_mut() {
381 let cell = &mut layer.grid[char_row][char_col];
382 let new_bits = cell.bits | bit;
383 if new_bits != cell.bits {
384 cell.bits = new_bits;
385 cell.color = color;
386 }
387 }
388 }
389
390 fn dot_isize(&mut self, x: isize, y: isize) {
391 if x >= 0 && y >= 0 {
392 self.dot(x as usize, y as usize);
393 }
394 }
395
396 pub fn width(&self) -> usize {
398 self.px_w
399 }
400
401 pub fn height(&self) -> usize {
403 self.px_h
404 }
405
406 pub fn dot(&mut self, x: usize, y: usize) {
408 self.dot_with_color(x, y, self.current_color);
409 }
410
411 pub fn line(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
413 let (mut x, mut y) = (x0 as isize, y0 as isize);
414 let (x1, y1) = (x1 as isize, y1 as isize);
415 let dx = (x1 - x).abs();
416 let dy = -(y1 - y).abs();
417 let sx = if x < x1 { 1 } else { -1 };
418 let sy = if y < y1 { 1 } else { -1 };
419 let mut err = dx + dy;
420
421 loop {
422 self.dot_isize(x, y);
423 if x == x1 && y == y1 {
424 break;
425 }
426 let e2 = 2 * err;
427 if e2 >= dy {
428 err += dy;
429 x += sx;
430 }
431 if e2 <= dx {
432 err += dx;
433 y += sy;
434 }
435 }
436 }
437
438 pub fn rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
440 if w == 0 || h == 0 {
441 return;
442 }
443
444 self.line(x, y, x + w.saturating_sub(1), y);
445 self.line(
446 x + w.saturating_sub(1),
447 y,
448 x + w.saturating_sub(1),
449 y + h.saturating_sub(1),
450 );
451 self.line(
452 x + w.saturating_sub(1),
453 y + h.saturating_sub(1),
454 x,
455 y + h.saturating_sub(1),
456 );
457 self.line(x, y + h.saturating_sub(1), x, y);
458 }
459
460 pub fn circle(&mut self, cx: usize, cy: usize, r: usize) {
462 let mut x = r as isize;
463 let mut y: isize = 0;
464 let mut err: isize = 1 - x;
465 let (cx, cy) = (cx as isize, cy as isize);
466
467 while x >= y {
468 for &(dx, dy) in &[
469 (x, y),
470 (y, x),
471 (-x, y),
472 (-y, x),
473 (x, -y),
474 (y, -x),
475 (-x, -y),
476 (-y, -x),
477 ] {
478 let px = cx + dx;
479 let py = cy + dy;
480 self.dot_isize(px, py);
481 }
482
483 y += 1;
484 if err < 0 {
485 err += 2 * y + 1;
486 } else {
487 x -= 1;
488 err += 2 * (y - x) + 1;
489 }
490 }
491 }
492
493 pub fn set_color(&mut self, color: Color) {
495 self.current_color = color;
496 }
497
498 pub fn color(&self) -> Color {
500 self.current_color
501 }
502
503 pub fn filled_rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
505 if w == 0 || h == 0 {
506 return;
507 }
508
509 let x_end = x.saturating_add(w).min(self.px_w);
510 let y_end = y.saturating_add(h).min(self.px_h);
511 if x >= x_end || y >= y_end {
512 return;
513 }
514
515 for yy in y..y_end {
516 self.line(x, yy, x_end.saturating_sub(1), yy);
517 }
518 }
519
520 pub fn filled_circle(&mut self, cx: usize, cy: usize, r: usize) {
522 let (cx, cy, r) = (cx as isize, cy as isize, r as isize);
523 for y in (cy - r)..=(cy + r) {
524 let dy = y - cy;
525 let span_sq = (r * r - dy * dy).max(0);
526 let dx = (span_sq as f64).sqrt() as isize;
527 for x in (cx - dx)..=(cx + dx) {
528 self.dot_isize(x, y);
529 }
530 }
531 }
532
533 pub fn triangle(&mut self, x0: usize, y0: usize, x1: usize, y1: usize, x2: usize, y2: usize) {
535 self.line(x0, y0, x1, y1);
536 self.line(x1, y1, x2, y2);
537 self.line(x2, y2, x0, y0);
538 }
539
540 pub fn filled_triangle(
542 &mut self,
543 x0: usize,
544 y0: usize,
545 x1: usize,
546 y1: usize,
547 x2: usize,
548 y2: usize,
549 ) {
550 let vertices = [
551 (x0 as isize, y0 as isize),
552 (x1 as isize, y1 as isize),
553 (x2 as isize, y2 as isize),
554 ];
555 let min_y = vertices.iter().map(|(_, y)| *y).min().unwrap_or(0);
556 let max_y = vertices.iter().map(|(_, y)| *y).max().unwrap_or(-1);
557
558 for y in min_y..=max_y {
559 let mut intersections: Vec<f64> = Vec::new();
560
561 for edge in [(0usize, 1usize), (1usize, 2usize), (2usize, 0usize)] {
562 let (x_a, y_a) = vertices[edge.0];
563 let (x_b, y_b) = vertices[edge.1];
564 if y_a == y_b {
565 continue;
566 }
567
568 let (x_start, y_start, x_end, y_end) = if y_a < y_b {
569 (x_a, y_a, x_b, y_b)
570 } else {
571 (x_b, y_b, x_a, y_a)
572 };
573
574 if y < y_start || y >= y_end {
575 continue;
576 }
577
578 let t = (y - y_start) as f64 / (y_end - y_start) as f64;
579 intersections.push(x_start as f64 + t * (x_end - x_start) as f64);
580 }
581
582 intersections.sort_by(|a, b| a.total_cmp(b));
583 let mut i = 0usize;
584 while i + 1 < intersections.len() {
585 let x_start = intersections[i].ceil() as isize;
586 let x_end = intersections[i + 1].floor() as isize;
587 for x in x_start..=x_end {
588 self.dot_isize(x, y);
589 }
590 i += 2;
591 }
592 }
593
594 self.triangle(x0, y0, x1, y1, x2, y2);
595 }
596
597 pub fn points(&mut self, pts: &[(usize, usize)]) {
599 for &(x, y) in pts {
600 self.dot(x, y);
601 }
602 }
603
604 pub fn polyline(&mut self, pts: &[(usize, usize)]) {
606 for window in pts.windows(2) {
607 if let [(x0, y0), (x1, y1)] = window {
608 self.line(*x0, *y0, *x1, *y1);
609 }
610 }
611 }
612
613 pub fn print(&mut self, x: usize, y: usize, text: &str) {
616 if text.is_empty() {
617 return;
618 }
619
620 let color = self.current_color;
621 if let Some(layer) = self.current_layer_mut() {
622 layer.labels.push(CanvasLabel {
623 x,
624 y,
625 text: text.to_string(),
626 color,
627 });
628 }
629 }
630
631 pub fn layer(&mut self) {
633 self.layers.push(Self::new_layer(self.cols, self.rows));
634 }
635
636 pub(crate) fn render(&self) -> Vec<Vec<(String, Color)>> {
637 let mut final_grid = vec![
638 vec![
639 CanvasPixel {
640 bits: 0,
641 color: Color::Reset,
642 };
643 self.cols
644 ];
645 self.rows
646 ];
647 let mut labels_overlay: Vec<Vec<Option<(char, Color)>>> =
648 vec![vec![None; self.cols]; self.rows];
649
650 for layer in &self.layers {
651 for (row, final_row) in final_grid.iter_mut().enumerate().take(self.rows) {
652 for (col, dst) in final_row.iter_mut().enumerate().take(self.cols) {
653 let src = layer.grid[row][col];
654 if src.bits == 0 {
655 continue;
656 }
657
658 let merged = dst.bits | src.bits;
659 if merged != dst.bits {
660 dst.bits = merged;
661 dst.color = src.color;
662 }
663 }
664 }
665
666 for label in &layer.labels {
667 let row = label.y / 4;
668 if row >= self.rows {
669 continue;
670 }
671 let start_col = label.x / 2;
672 for (offset, ch) in label.text.chars().enumerate() {
673 let col = start_col + offset;
674 if col >= self.cols {
675 break;
676 }
677 labels_overlay[row][col] = Some((ch, label.color));
678 }
679 }
680 }
681
682 let mut lines: Vec<Vec<(String, Color)>> = Vec::with_capacity(self.rows);
683 for row in 0..self.rows {
684 let mut segments: Vec<(String, Color)> = Vec::new();
685 let mut current_color: Option<Color> = None;
686 let mut current_text = String::new();
687
688 for col in 0..self.cols {
689 let (ch, color) = if let Some((label_ch, label_color)) = labels_overlay[row][col] {
690 (label_ch, label_color)
691 } else {
692 let bits = final_grid[row][col].bits;
693 let ch = char::from_u32(0x2800 + bits).unwrap_or(' ');
694 (ch, final_grid[row][col].color)
695 };
696
697 match current_color {
698 Some(c) if c == color => {
699 current_text.push(ch);
700 }
701 Some(c) => {
702 segments.push((std::mem::take(&mut current_text), c));
703 current_text.push(ch);
704 current_color = Some(color);
705 }
706 None => {
707 current_text.push(ch);
708 current_color = Some(color);
709 }
710 }
711 }
712
713 if let Some(color) = current_color {
714 segments.push((current_text, color));
715 }
716 lines.push(segments);
717 }
718
719 lines
720 }
721}
722
723impl<'a> ContainerBuilder<'a> {
724 pub fn border(mut self, border: Border) -> Self {
728 self.border = Some(border);
729 self
730 }
731
732 pub fn border_top(mut self, show: bool) -> Self {
734 self.border_sides.top = show;
735 self
736 }
737
738 pub fn border_right(mut self, show: bool) -> Self {
740 self.border_sides.right = show;
741 self
742 }
743
744 pub fn border_bottom(mut self, show: bool) -> Self {
746 self.border_sides.bottom = show;
747 self
748 }
749
750 pub fn border_left(mut self, show: bool) -> Self {
752 self.border_sides.left = show;
753 self
754 }
755
756 pub fn border_sides(mut self, sides: BorderSides) -> Self {
758 self.border_sides = sides;
759 self
760 }
761
762 pub fn rounded(self) -> Self {
764 self.border(Border::Rounded)
765 }
766
767 pub fn border_style(mut self, style: Style) -> Self {
769 self.border_style = style;
770 self
771 }
772
773 pub fn dark_border_style(mut self, style: Style) -> Self {
775 self.dark_border_style = Some(style);
776 self
777 }
778
779 pub fn bg(mut self, color: Color) -> Self {
780 self.bg_color = Some(color);
781 self
782 }
783
784 pub fn dark_bg(mut self, color: Color) -> Self {
786 self.dark_bg_color = Some(color);
787 self
788 }
789
790 pub fn group_hover_bg(mut self, color: Color) -> Self {
792 self.group_hover_bg = Some(color);
793 self
794 }
795
796 pub fn group_hover_border_style(mut self, style: Style) -> Self {
798 self.group_hover_border_style = Some(style);
799 self
800 }
801
802 pub fn p(self, value: u32) -> Self {
806 self.pad(value)
807 }
808
809 pub fn pad(mut self, value: u32) -> Self {
811 self.padding = Padding::all(value);
812 self
813 }
814
815 pub fn px(mut self, value: u32) -> Self {
817 self.padding.left = value;
818 self.padding.right = value;
819 self
820 }
821
822 pub fn py(mut self, value: u32) -> Self {
824 self.padding.top = value;
825 self.padding.bottom = value;
826 self
827 }
828
829 pub fn pt(mut self, value: u32) -> Self {
831 self.padding.top = value;
832 self
833 }
834
835 pub fn pr(mut self, value: u32) -> Self {
837 self.padding.right = value;
838 self
839 }
840
841 pub fn pb(mut self, value: u32) -> Self {
843 self.padding.bottom = value;
844 self
845 }
846
847 pub fn pl(mut self, value: u32) -> Self {
849 self.padding.left = value;
850 self
851 }
852
853 pub fn padding(mut self, padding: Padding) -> Self {
855 self.padding = padding;
856 self
857 }
858
859 pub fn m(mut self, value: u32) -> Self {
863 self.margin = Margin::all(value);
864 self
865 }
866
867 pub fn mx(mut self, value: u32) -> Self {
869 self.margin.left = value;
870 self.margin.right = value;
871 self
872 }
873
874 pub fn my(mut self, value: u32) -> Self {
876 self.margin.top = value;
877 self.margin.bottom = value;
878 self
879 }
880
881 pub fn mt(mut self, value: u32) -> Self {
883 self.margin.top = value;
884 self
885 }
886
887 pub fn mr(mut self, value: u32) -> Self {
889 self.margin.right = value;
890 self
891 }
892
893 pub fn mb(mut self, value: u32) -> Self {
895 self.margin.bottom = value;
896 self
897 }
898
899 pub fn ml(mut self, value: u32) -> Self {
901 self.margin.left = value;
902 self
903 }
904
905 pub fn margin(mut self, margin: Margin) -> Self {
907 self.margin = margin;
908 self
909 }
910
911 pub fn w(mut self, value: u32) -> Self {
915 self.constraints.min_width = Some(value);
916 self.constraints.max_width = Some(value);
917 self
918 }
919
920 pub fn xs_w(self, value: u32) -> Self {
927 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
928 if is_xs {
929 self.w(value)
930 } else {
931 self
932 }
933 }
934
935 pub fn sm_w(self, value: u32) -> Self {
937 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
938 if is_sm {
939 self.w(value)
940 } else {
941 self
942 }
943 }
944
945 pub fn md_w(self, value: u32) -> Self {
947 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
948 if is_md {
949 self.w(value)
950 } else {
951 self
952 }
953 }
954
955 pub fn lg_w(self, value: u32) -> Self {
957 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
958 if is_lg {
959 self.w(value)
960 } else {
961 self
962 }
963 }
964
965 pub fn xl_w(self, value: u32) -> Self {
967 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
968 if is_xl {
969 self.w(value)
970 } else {
971 self
972 }
973 }
974
975 pub fn h(mut self, value: u32) -> Self {
977 self.constraints.min_height = Some(value);
978 self.constraints.max_height = Some(value);
979 self
980 }
981
982 pub fn xs_h(self, value: u32) -> Self {
984 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
985 if is_xs {
986 self.h(value)
987 } else {
988 self
989 }
990 }
991
992 pub fn sm_h(self, value: u32) -> Self {
994 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
995 if is_sm {
996 self.h(value)
997 } else {
998 self
999 }
1000 }
1001
1002 pub fn md_h(self, value: u32) -> Self {
1004 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1005 if is_md {
1006 self.h(value)
1007 } else {
1008 self
1009 }
1010 }
1011
1012 pub fn lg_h(self, value: u32) -> Self {
1014 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1015 if is_lg {
1016 self.h(value)
1017 } else {
1018 self
1019 }
1020 }
1021
1022 pub fn xl_h(self, value: u32) -> Self {
1024 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1025 if is_xl {
1026 self.h(value)
1027 } else {
1028 self
1029 }
1030 }
1031
1032 pub fn min_w(mut self, value: u32) -> Self {
1034 self.constraints.min_width = Some(value);
1035 self
1036 }
1037
1038 pub fn xs_min_w(self, value: u32) -> Self {
1040 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1041 if is_xs {
1042 self.min_w(value)
1043 } else {
1044 self
1045 }
1046 }
1047
1048 pub fn sm_min_w(self, value: u32) -> Self {
1050 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1051 if is_sm {
1052 self.min_w(value)
1053 } else {
1054 self
1055 }
1056 }
1057
1058 pub fn md_min_w(self, value: u32) -> Self {
1060 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1061 if is_md {
1062 self.min_w(value)
1063 } else {
1064 self
1065 }
1066 }
1067
1068 pub fn lg_min_w(self, value: u32) -> Self {
1070 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1071 if is_lg {
1072 self.min_w(value)
1073 } else {
1074 self
1075 }
1076 }
1077
1078 pub fn xl_min_w(self, value: u32) -> Self {
1080 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1081 if is_xl {
1082 self.min_w(value)
1083 } else {
1084 self
1085 }
1086 }
1087
1088 pub fn max_w(mut self, value: u32) -> Self {
1090 self.constraints.max_width = Some(value);
1091 self
1092 }
1093
1094 pub fn xs_max_w(self, value: u32) -> Self {
1096 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1097 if is_xs {
1098 self.max_w(value)
1099 } else {
1100 self
1101 }
1102 }
1103
1104 pub fn sm_max_w(self, value: u32) -> Self {
1106 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1107 if is_sm {
1108 self.max_w(value)
1109 } else {
1110 self
1111 }
1112 }
1113
1114 pub fn md_max_w(self, value: u32) -> Self {
1116 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1117 if is_md {
1118 self.max_w(value)
1119 } else {
1120 self
1121 }
1122 }
1123
1124 pub fn lg_max_w(self, value: u32) -> Self {
1126 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1127 if is_lg {
1128 self.max_w(value)
1129 } else {
1130 self
1131 }
1132 }
1133
1134 pub fn xl_max_w(self, value: u32) -> Self {
1136 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1137 if is_xl {
1138 self.max_w(value)
1139 } else {
1140 self
1141 }
1142 }
1143
1144 pub fn min_h(mut self, value: u32) -> Self {
1146 self.constraints.min_height = Some(value);
1147 self
1148 }
1149
1150 pub fn max_h(mut self, value: u32) -> Self {
1152 self.constraints.max_height = Some(value);
1153 self
1154 }
1155
1156 pub fn min_width(mut self, value: u32) -> Self {
1158 self.constraints.min_width = Some(value);
1159 self
1160 }
1161
1162 pub fn max_width(mut self, value: u32) -> Self {
1164 self.constraints.max_width = Some(value);
1165 self
1166 }
1167
1168 pub fn min_height(mut self, value: u32) -> Self {
1170 self.constraints.min_height = Some(value);
1171 self
1172 }
1173
1174 pub fn max_height(mut self, value: u32) -> Self {
1176 self.constraints.max_height = Some(value);
1177 self
1178 }
1179
1180 pub fn w_pct(mut self, pct: u8) -> Self {
1182 self.constraints.width_pct = Some(pct.min(100));
1183 self
1184 }
1185
1186 pub fn h_pct(mut self, pct: u8) -> Self {
1188 self.constraints.height_pct = Some(pct.min(100));
1189 self
1190 }
1191
1192 pub fn constraints(mut self, constraints: Constraints) -> Self {
1194 self.constraints = constraints;
1195 self
1196 }
1197
1198 pub fn gap(mut self, gap: u32) -> Self {
1202 self.gap = gap;
1203 self
1204 }
1205
1206 pub fn xs_gap(self, value: u32) -> Self {
1208 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1209 if is_xs {
1210 self.gap(value)
1211 } else {
1212 self
1213 }
1214 }
1215
1216 pub fn sm_gap(self, value: u32) -> Self {
1218 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1219 if is_sm {
1220 self.gap(value)
1221 } else {
1222 self
1223 }
1224 }
1225
1226 pub fn md_gap(self, value: u32) -> Self {
1233 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1234 if is_md {
1235 self.gap(value)
1236 } else {
1237 self
1238 }
1239 }
1240
1241 pub fn lg_gap(self, value: u32) -> Self {
1243 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1244 if is_lg {
1245 self.gap(value)
1246 } else {
1247 self
1248 }
1249 }
1250
1251 pub fn xl_gap(self, value: u32) -> Self {
1253 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1254 if is_xl {
1255 self.gap(value)
1256 } else {
1257 self
1258 }
1259 }
1260
1261 pub fn grow(mut self, grow: u16) -> Self {
1263 self.grow = grow;
1264 self
1265 }
1266
1267 pub fn xs_grow(self, value: u16) -> Self {
1269 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1270 if is_xs {
1271 self.grow(value)
1272 } else {
1273 self
1274 }
1275 }
1276
1277 pub fn sm_grow(self, value: u16) -> Self {
1279 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1280 if is_sm {
1281 self.grow(value)
1282 } else {
1283 self
1284 }
1285 }
1286
1287 pub fn md_grow(self, value: u16) -> Self {
1289 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1290 if is_md {
1291 self.grow(value)
1292 } else {
1293 self
1294 }
1295 }
1296
1297 pub fn lg_grow(self, value: u16) -> Self {
1299 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1300 if is_lg {
1301 self.grow(value)
1302 } else {
1303 self
1304 }
1305 }
1306
1307 pub fn xl_grow(self, value: u16) -> Self {
1309 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1310 if is_xl {
1311 self.grow(value)
1312 } else {
1313 self
1314 }
1315 }
1316
1317 pub fn xs_p(self, value: u32) -> Self {
1319 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1320 if is_xs {
1321 self.p(value)
1322 } else {
1323 self
1324 }
1325 }
1326
1327 pub fn sm_p(self, value: u32) -> Self {
1329 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1330 if is_sm {
1331 self.p(value)
1332 } else {
1333 self
1334 }
1335 }
1336
1337 pub fn md_p(self, value: u32) -> Self {
1339 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1340 if is_md {
1341 self.p(value)
1342 } else {
1343 self
1344 }
1345 }
1346
1347 pub fn lg_p(self, value: u32) -> Self {
1349 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1350 if is_lg {
1351 self.p(value)
1352 } else {
1353 self
1354 }
1355 }
1356
1357 pub fn xl_p(self, value: u32) -> Self {
1359 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1360 if is_xl {
1361 self.p(value)
1362 } else {
1363 self
1364 }
1365 }
1366
1367 pub fn align(mut self, align: Align) -> Self {
1371 self.align = align;
1372 self
1373 }
1374
1375 pub fn center(self) -> Self {
1377 self.align(Align::Center)
1378 }
1379
1380 pub fn justify(mut self, justify: Justify) -> Self {
1382 self.justify = justify;
1383 self
1384 }
1385
1386 pub fn space_between(self) -> Self {
1388 self.justify(Justify::SpaceBetween)
1389 }
1390
1391 pub fn space_around(self) -> Self {
1393 self.justify(Justify::SpaceAround)
1394 }
1395
1396 pub fn space_evenly(self) -> Self {
1398 self.justify(Justify::SpaceEvenly)
1399 }
1400
1401 pub fn title(self, title: impl Into<String>) -> Self {
1405 self.title_styled(title, Style::new())
1406 }
1407
1408 pub fn title_styled(mut self, title: impl Into<String>, style: Style) -> Self {
1410 self.title = Some((title.into(), style));
1411 self
1412 }
1413
1414 pub fn scroll_offset(mut self, offset: u32) -> Self {
1418 self.scroll_offset = Some(offset);
1419 self
1420 }
1421
1422 fn group_name(mut self, name: String) -> Self {
1423 self.group_name = Some(name);
1424 self
1425 }
1426
1427 pub fn col(self, f: impl FnOnce(&mut Context)) -> Response {
1432 self.finish(Direction::Column, f)
1433 }
1434
1435 pub fn row(self, f: impl FnOnce(&mut Context)) -> Response {
1440 self.finish(Direction::Row, f)
1441 }
1442
1443 pub fn line(mut self, f: impl FnOnce(&mut Context)) -> Response {
1448 self.gap = 0;
1449 self.finish(Direction::Row, f)
1450 }
1451
1452 fn finish(self, direction: Direction, f: impl FnOnce(&mut Context)) -> Response {
1453 let interaction_id = self.ctx.interaction_count;
1454 self.ctx.interaction_count += 1;
1455
1456 let in_hovered_group = self
1457 .group_name
1458 .as_ref()
1459 .map(|name| self.ctx.is_group_hovered(name))
1460 .unwrap_or(false)
1461 || self
1462 .ctx
1463 .group_stack
1464 .last()
1465 .map(|name| self.ctx.is_group_hovered(name))
1466 .unwrap_or(false);
1467 let in_focused_group = self
1468 .group_name
1469 .as_ref()
1470 .map(|name| self.ctx.is_group_focused(name))
1471 .unwrap_or(false)
1472 || self
1473 .ctx
1474 .group_stack
1475 .last()
1476 .map(|name| self.ctx.is_group_focused(name))
1477 .unwrap_or(false);
1478
1479 let resolved_bg = if self.ctx.dark_mode {
1480 self.dark_bg_color.or(self.bg_color)
1481 } else {
1482 self.bg_color
1483 };
1484 let resolved_border_style = if self.ctx.dark_mode {
1485 self.dark_border_style.unwrap_or(self.border_style)
1486 } else {
1487 self.border_style
1488 };
1489 let bg_color = if in_hovered_group || in_focused_group {
1490 self.group_hover_bg.or(resolved_bg)
1491 } else {
1492 resolved_bg
1493 };
1494 let border_style = if in_hovered_group || in_focused_group {
1495 self.group_hover_border_style
1496 .unwrap_or(resolved_border_style)
1497 } else {
1498 resolved_border_style
1499 };
1500 let group_name = self.group_name.clone();
1501 let is_group_container = group_name.is_some();
1502
1503 if let Some(scroll_offset) = self.scroll_offset {
1504 self.ctx.commands.push(Command::BeginScrollable {
1505 grow: self.grow,
1506 border: self.border,
1507 border_sides: self.border_sides,
1508 border_style,
1509 padding: self.padding,
1510 margin: self.margin,
1511 constraints: self.constraints,
1512 title: self.title,
1513 scroll_offset,
1514 });
1515 } else {
1516 self.ctx.commands.push(Command::BeginContainer {
1517 direction,
1518 gap: self.gap,
1519 align: self.align,
1520 justify: self.justify,
1521 border: self.border,
1522 border_sides: self.border_sides,
1523 border_style,
1524 bg_color,
1525 padding: self.padding,
1526 margin: self.margin,
1527 constraints: self.constraints,
1528 title: self.title,
1529 grow: self.grow,
1530 group_name,
1531 });
1532 }
1533 f(self.ctx);
1534 self.ctx.commands.push(Command::EndContainer);
1535 self.ctx.last_text_idx = None;
1536
1537 if is_group_container {
1538 self.ctx.group_stack.pop();
1539 self.ctx.group_count = self.ctx.group_count.saturating_sub(1);
1540 }
1541
1542 self.ctx.response_for(interaction_id)
1543 }
1544}
1545
1546impl Context {
1547 #[allow(clippy::too_many_arguments)]
1548 pub(crate) fn new(
1549 events: Vec<Event>,
1550 width: u32,
1551 height: u32,
1552 tick: u64,
1553 mut focus_index: usize,
1554 prev_focus_count: usize,
1555 prev_scroll_infos: Vec<(u32, u32)>,
1556 prev_scroll_rects: Vec<Rect>,
1557 prev_hit_map: Vec<Rect>,
1558 prev_group_rects: Vec<(String, Rect)>,
1559 prev_focus_rects: Vec<(usize, Rect)>,
1560 prev_focus_groups: Vec<Option<String>>,
1561 prev_hook_states: Vec<Box<dyn std::any::Any>>,
1562 debug: bool,
1563 theme: Theme,
1564 last_mouse_pos: Option<(u32, u32)>,
1565 prev_modal_active: bool,
1566 ) -> Self {
1567 let consumed = vec![false; events.len()];
1568
1569 let mut mouse_pos = last_mouse_pos;
1570 let mut click_pos = None;
1571 for event in &events {
1572 if let Event::Mouse(mouse) = event {
1573 mouse_pos = Some((mouse.x, mouse.y));
1574 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
1575 click_pos = Some((mouse.x, mouse.y));
1576 }
1577 }
1578 }
1579
1580 if let Some((mx, my)) = click_pos {
1581 let mut best: Option<(usize, u64)> = None;
1582 for &(fid, rect) in &prev_focus_rects {
1583 if mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom() {
1584 let area = rect.width as u64 * rect.height as u64;
1585 if best.map_or(true, |(_, ba)| area < ba) {
1586 best = Some((fid, area));
1587 }
1588 }
1589 }
1590 if let Some((fid, _)) = best {
1591 focus_index = fid;
1592 }
1593 }
1594
1595 Self {
1596 commands: Vec::new(),
1597 events,
1598 consumed,
1599 should_quit: false,
1600 area_width: width,
1601 area_height: height,
1602 tick,
1603 focus_index,
1604 focus_count: 0,
1605 hook_states: prev_hook_states,
1606 hook_cursor: 0,
1607 prev_focus_count,
1608 scroll_count: 0,
1609 prev_scroll_infos,
1610 prev_scroll_rects,
1611 interaction_count: 0,
1612 prev_hit_map,
1613 group_stack: Vec::new(),
1614 prev_group_rects,
1615 group_count: 0,
1616 prev_focus_groups,
1617 _prev_focus_rects: prev_focus_rects,
1618 mouse_pos,
1619 click_pos,
1620 last_text_idx: None,
1621 overlay_depth: 0,
1622 modal_active: false,
1623 prev_modal_active,
1624 clipboard_text: None,
1625 debug,
1626 theme,
1627 dark_mode: true,
1628 }
1629 }
1630
1631 pub(crate) fn process_focus_keys(&mut self) {
1632 for (i, event) in self.events.iter().enumerate() {
1633 if let Event::Key(key) = event {
1634 if key.kind != KeyEventKind::Press {
1635 continue;
1636 }
1637 if key.code == KeyCode::Tab && !key.modifiers.contains(KeyModifiers::SHIFT) {
1638 if self.prev_focus_count > 0 {
1639 self.focus_index = (self.focus_index + 1) % self.prev_focus_count;
1640 }
1641 self.consumed[i] = true;
1642 } else if (key.code == KeyCode::Tab && key.modifiers.contains(KeyModifiers::SHIFT))
1643 || key.code == KeyCode::BackTab
1644 {
1645 if self.prev_focus_count > 0 {
1646 self.focus_index = if self.focus_index == 0 {
1647 self.prev_focus_count - 1
1648 } else {
1649 self.focus_index - 1
1650 };
1651 }
1652 self.consumed[i] = true;
1653 }
1654 }
1655 }
1656 }
1657
1658 pub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response {
1662 w.ui(self)
1663 }
1664
1665 pub fn error_boundary(&mut self, f: impl FnOnce(&mut Context)) {
1680 self.error_boundary_with(f, |ui, msg| {
1681 ui.styled(
1682 format!("⚠ Error: {msg}"),
1683 Style::new().fg(ui.theme.error).bold(),
1684 );
1685 });
1686 }
1687
1688 pub fn error_boundary_with(
1708 &mut self,
1709 f: impl FnOnce(&mut Context),
1710 fallback: impl FnOnce(&mut Context, String),
1711 ) {
1712 let cmd_count = self.commands.len();
1713 let last_text_idx = self.last_text_idx;
1714
1715 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1716 f(self);
1717 }));
1718
1719 match result {
1720 Ok(()) => {}
1721 Err(panic_info) => {
1722 self.commands.truncate(cmd_count);
1723 self.last_text_idx = last_text_idx;
1724
1725 let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
1726 (*s).to_string()
1727 } else if let Some(s) = panic_info.downcast_ref::<String>() {
1728 s.clone()
1729 } else {
1730 "widget panicked".to_string()
1731 };
1732
1733 fallback(self, msg);
1734 }
1735 }
1736 }
1737
1738 pub fn interaction(&mut self) -> Response {
1744 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
1745 return Response::default();
1746 }
1747 let id = self.interaction_count;
1748 self.interaction_count += 1;
1749 self.response_for(id)
1750 }
1751
1752 pub fn register_focusable(&mut self) -> bool {
1757 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
1758 return false;
1759 }
1760 let id = self.focus_count;
1761 self.focus_count += 1;
1762 self.commands.push(Command::FocusMarker(id));
1763 if self.prev_focus_count == 0 {
1764 return true;
1765 }
1766 self.focus_index % self.prev_focus_count == id
1767 }
1768
1769 pub fn use_state<T: 'static>(&mut self, init: impl FnOnce() -> T) -> State<T> {
1787 let idx = self.hook_cursor;
1788 self.hook_cursor += 1;
1789
1790 if idx >= self.hook_states.len() {
1791 self.hook_states.push(Box::new(init()));
1792 }
1793
1794 State {
1795 idx,
1796 _marker: std::marker::PhantomData,
1797 }
1798 }
1799
1800 pub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>(
1808 &mut self,
1809 deps: &D,
1810 compute: impl FnOnce(&D) -> T,
1811 ) -> &T {
1812 let idx = self.hook_cursor;
1813 self.hook_cursor += 1;
1814
1815 let should_recompute = if idx >= self.hook_states.len() {
1816 true
1817 } else {
1818 let (stored_deps, _) = self.hook_states[idx]
1819 .downcast_ref::<(D, T)>()
1820 .expect("use_memo type mismatch");
1821 stored_deps != deps
1822 };
1823
1824 if should_recompute {
1825 let value = compute(deps);
1826 let slot = Box::new((deps.clone(), value));
1827 if idx < self.hook_states.len() {
1828 self.hook_states[idx] = slot;
1829 } else {
1830 self.hook_states.push(slot);
1831 }
1832 }
1833
1834 let (_, value) = self.hook_states[idx]
1835 .downcast_ref::<(D, T)>()
1836 .expect("use_memo type mismatch");
1837 value
1838 }
1839
1840 pub fn text(&mut self, s: impl Into<String>) -> &mut Self {
1853 let content = s.into();
1854 self.commands.push(Command::Text {
1855 content,
1856 style: Style::new(),
1857 grow: 0,
1858 align: Align::Start,
1859 wrap: false,
1860 margin: Margin::default(),
1861 constraints: Constraints::default(),
1862 });
1863 self.last_text_idx = Some(self.commands.len() - 1);
1864 self
1865 }
1866
1867 pub fn link(&mut self, text: impl Into<String>, url: impl Into<String>) -> &mut Self {
1873 let url_str = url.into();
1874 let focused = self.register_focusable();
1875 let interaction_id = self.interaction_count;
1876 self.interaction_count += 1;
1877 let response = self.response_for(interaction_id);
1878
1879 let mut activated = response.clicked;
1880 if focused {
1881 for (i, event) in self.events.iter().enumerate() {
1882 if let Event::Key(key) = event {
1883 if key.kind != KeyEventKind::Press {
1884 continue;
1885 }
1886 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
1887 activated = true;
1888 self.consumed[i] = true;
1889 }
1890 }
1891 }
1892 }
1893
1894 if activated {
1895 let _ = open_url(&url_str);
1896 }
1897
1898 let style = if focused {
1899 Style::new()
1900 .fg(self.theme.primary)
1901 .bg(self.theme.surface_hover)
1902 .underline()
1903 .bold()
1904 } else if response.hovered {
1905 Style::new()
1906 .fg(self.theme.accent)
1907 .bg(self.theme.surface_hover)
1908 .underline()
1909 } else {
1910 Style::new().fg(self.theme.primary).underline()
1911 };
1912
1913 self.commands.push(Command::Link {
1914 text: text.into(),
1915 url: url_str,
1916 style,
1917 margin: Margin::default(),
1918 constraints: Constraints::default(),
1919 });
1920 self.last_text_idx = Some(self.commands.len() - 1);
1921 self
1922 }
1923
1924 pub fn text_wrap(&mut self, s: impl Into<String>) -> &mut Self {
1929 let content = s.into();
1930 self.commands.push(Command::Text {
1931 content,
1932 style: Style::new(),
1933 grow: 0,
1934 align: Align::Start,
1935 wrap: true,
1936 margin: Margin::default(),
1937 constraints: Constraints::default(),
1938 });
1939 self.last_text_idx = Some(self.commands.len() - 1);
1940 self
1941 }
1942
1943 pub fn bold(&mut self) -> &mut Self {
1947 self.modify_last_style(|s| s.modifiers |= Modifiers::BOLD);
1948 self
1949 }
1950
1951 pub fn dim(&mut self) -> &mut Self {
1956 let text_dim = self.theme.text_dim;
1957 self.modify_last_style(|s| {
1958 s.modifiers |= Modifiers::DIM;
1959 if s.fg.is_none() {
1960 s.fg = Some(text_dim);
1961 }
1962 });
1963 self
1964 }
1965
1966 pub fn italic(&mut self) -> &mut Self {
1968 self.modify_last_style(|s| s.modifiers |= Modifiers::ITALIC);
1969 self
1970 }
1971
1972 pub fn underline(&mut self) -> &mut Self {
1974 self.modify_last_style(|s| s.modifiers |= Modifiers::UNDERLINE);
1975 self
1976 }
1977
1978 pub fn reversed(&mut self) -> &mut Self {
1980 self.modify_last_style(|s| s.modifiers |= Modifiers::REVERSED);
1981 self
1982 }
1983
1984 pub fn strikethrough(&mut self) -> &mut Self {
1986 self.modify_last_style(|s| s.modifiers |= Modifiers::STRIKETHROUGH);
1987 self
1988 }
1989
1990 pub fn fg(&mut self, color: Color) -> &mut Self {
1992 self.modify_last_style(|s| s.fg = Some(color));
1993 self
1994 }
1995
1996 pub fn bg(&mut self, color: Color) -> &mut Self {
1998 self.modify_last_style(|s| s.bg = Some(color));
1999 self
2000 }
2001
2002 pub fn group_hover_fg(&mut self, color: Color) -> &mut Self {
2003 let apply_group_style = self
2004 .group_stack
2005 .last()
2006 .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
2007 .unwrap_or(false);
2008 if apply_group_style {
2009 self.modify_last_style(|s| s.fg = Some(color));
2010 }
2011 self
2012 }
2013
2014 pub fn group_hover_bg(&mut self, color: Color) -> &mut Self {
2015 let apply_group_style = self
2016 .group_stack
2017 .last()
2018 .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
2019 .unwrap_or(false);
2020 if apply_group_style {
2021 self.modify_last_style(|s| s.bg = Some(color));
2022 }
2023 self
2024 }
2025
2026 pub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self {
2031 self.commands.push(Command::Text {
2032 content: s.into(),
2033 style,
2034 grow: 0,
2035 align: Align::Start,
2036 wrap: false,
2037 margin: Margin::default(),
2038 constraints: Constraints::default(),
2039 });
2040 self.last_text_idx = Some(self.commands.len() - 1);
2041 self
2042 }
2043
2044 pub fn image(&mut self, img: &HalfBlockImage) {
2066 let width = img.width;
2067 let height = img.height;
2068
2069 self.container().w(width).h(height).gap(0).col(|ui| {
2070 for row in 0..height {
2071 ui.container().gap(0).row(|ui| {
2072 for col in 0..width {
2073 let idx = (row * width + col) as usize;
2074 if let Some(&(upper, lower)) = img.pixels.get(idx) {
2075 ui.styled("▀", Style::new().fg(upper).bg(lower));
2076 }
2077 }
2078 });
2079 }
2080 });
2081 }
2082
2083 pub fn streaming_text(&mut self, state: &mut StreamingTextState) {
2099 if state.streaming {
2100 state.cursor_tick = state.cursor_tick.wrapping_add(1);
2101 state.cursor_visible = (state.cursor_tick / 8) % 2 == 0;
2102 }
2103
2104 if state.content.is_empty() && state.streaming {
2105 let cursor = if state.cursor_visible { "▌" } else { " " };
2106 let primary = self.theme.primary;
2107 self.text(cursor).fg(primary);
2108 return;
2109 }
2110
2111 if !state.content.is_empty() {
2112 if state.streaming && state.cursor_visible {
2113 self.text_wrap(format!("{}▌", state.content));
2114 } else {
2115 self.text_wrap(&state.content);
2116 }
2117 }
2118 }
2119
2120 pub fn tool_approval(&mut self, state: &mut ToolApprovalState) {
2135 let theme = self.theme;
2136 self.bordered(Border::Rounded).col(|ui| {
2137 ui.row(|ui| {
2138 ui.text("⚡").fg(theme.warning);
2139 ui.text(&state.tool_name).bold().fg(theme.primary);
2140 });
2141 ui.text(&state.description).dim();
2142
2143 if state.action == ApprovalAction::Pending {
2144 ui.row(|ui| {
2145 if ui.button("✓ Approve") {
2146 state.action = ApprovalAction::Approved;
2147 }
2148 if ui.button("✗ Reject") {
2149 state.action = ApprovalAction::Rejected;
2150 }
2151 });
2152 } else {
2153 let (label, color) = match state.action {
2154 ApprovalAction::Approved => ("✓ Approved", theme.success),
2155 ApprovalAction::Rejected => ("✗ Rejected", theme.error),
2156 ApprovalAction::Pending => unreachable!(),
2157 };
2158 ui.text(label).fg(color).bold();
2159 }
2160 });
2161 }
2162
2163 pub fn context_bar(&mut self, items: &[ContextItem]) {
2176 if items.is_empty() {
2177 return;
2178 }
2179
2180 let theme = self.theme;
2181 let total: usize = items.iter().map(|item| item.tokens).sum();
2182
2183 self.container().row(|ui| {
2184 ui.text("📎").dim();
2185 for item in items {
2186 ui.text(format!(
2187 "{} ({})",
2188 item.label,
2189 format_token_count(item.tokens)
2190 ))
2191 .fg(theme.secondary);
2192 }
2193 ui.spacer();
2194 ui.text(format!("Σ {}", format_token_count(total))).dim();
2195 });
2196 }
2197
2198 pub fn wrap(&mut self) -> &mut Self {
2200 if let Some(idx) = self.last_text_idx {
2201 if let Command::Text { wrap, .. } = &mut self.commands[idx] {
2202 *wrap = true;
2203 }
2204 }
2205 self
2206 }
2207
2208 fn modify_last_style(&mut self, f: impl FnOnce(&mut Style)) {
2209 if let Some(idx) = self.last_text_idx {
2210 match &mut self.commands[idx] {
2211 Command::Text { style, .. } | Command::Link { style, .. } => f(style),
2212 _ => {}
2213 }
2214 }
2215 }
2216
2217 pub fn col(&mut self, f: impl FnOnce(&mut Context)) -> Response {
2235 self.push_container(Direction::Column, 0, f)
2236 }
2237
2238 pub fn col_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response {
2242 self.push_container(Direction::Column, gap, f)
2243 }
2244
2245 pub fn row(&mut self, f: impl FnOnce(&mut Context)) -> Response {
2262 self.push_container(Direction::Row, 0, f)
2263 }
2264
2265 pub fn row_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response {
2269 self.push_container(Direction::Row, gap, f)
2270 }
2271
2272 pub fn line(&mut self, f: impl FnOnce(&mut Context)) -> &mut Self {
2289 let _ = self.push_container(Direction::Row, 0, f);
2290 self
2291 }
2292
2293 pub fn line_wrap(&mut self, f: impl FnOnce(&mut Context)) -> &mut Self {
2312 let start = self.commands.len();
2313 f(self);
2314 let mut segments: Vec<(String, Style)> = Vec::new();
2315 for cmd in self.commands.drain(start..) {
2316 if let Command::Text { content, style, .. } = cmd {
2317 segments.push((content, style));
2318 }
2319 }
2320 self.commands.push(Command::RichText {
2321 segments,
2322 wrap: true,
2323 align: Align::Start,
2324 margin: Margin::default(),
2325 constraints: Constraints::default(),
2326 });
2327 self.last_text_idx = None;
2328 self
2329 }
2330
2331 pub fn modal(&mut self, f: impl FnOnce(&mut Context)) {
2333 self.commands.push(Command::BeginOverlay { modal: true });
2334 self.overlay_depth += 1;
2335 self.modal_active = true;
2336 f(self);
2337 self.overlay_depth = self.overlay_depth.saturating_sub(1);
2338 self.commands.push(Command::EndOverlay);
2339 self.last_text_idx = None;
2340 }
2341
2342 pub fn overlay(&mut self, f: impl FnOnce(&mut Context)) {
2344 self.commands.push(Command::BeginOverlay { modal: false });
2345 self.overlay_depth += 1;
2346 f(self);
2347 self.overlay_depth = self.overlay_depth.saturating_sub(1);
2348 self.commands.push(Command::EndOverlay);
2349 self.last_text_idx = None;
2350 }
2351
2352 pub fn group(&mut self, name: &str) -> ContainerBuilder<'_> {
2354 self.group_count = self.group_count.saturating_add(1);
2355 self.group_stack.push(name.to_string());
2356 self.container().group_name(name.to_string())
2357 }
2358
2359 pub fn container(&mut self) -> ContainerBuilder<'_> {
2380 let border = self.theme.border;
2381 ContainerBuilder {
2382 ctx: self,
2383 gap: 0,
2384 align: Align::Start,
2385 justify: Justify::Start,
2386 border: None,
2387 border_sides: BorderSides::all(),
2388 border_style: Style::new().fg(border),
2389 bg_color: None,
2390 dark_bg_color: None,
2391 dark_border_style: None,
2392 group_hover_bg: None,
2393 group_hover_border_style: None,
2394 group_name: None,
2395 padding: Padding::default(),
2396 margin: Margin::default(),
2397 constraints: Constraints::default(),
2398 title: None,
2399 grow: 0,
2400 scroll_offset: None,
2401 }
2402 }
2403
2404 pub fn scrollable(&mut self, state: &mut ScrollState) -> ContainerBuilder<'_> {
2423 let index = self.scroll_count;
2424 self.scroll_count += 1;
2425 if let Some(&(ch, vh)) = self.prev_scroll_infos.get(index) {
2426 state.set_bounds(ch, vh);
2427 let max = ch.saturating_sub(vh) as usize;
2428 state.offset = state.offset.min(max);
2429 }
2430
2431 let next_id = self.interaction_count;
2432 if let Some(rect) = self.prev_hit_map.get(next_id).copied() {
2433 let inner_rects: Vec<Rect> = self
2434 .prev_scroll_rects
2435 .iter()
2436 .enumerate()
2437 .filter(|&(j, sr)| {
2438 j != index
2439 && sr.width > 0
2440 && sr.height > 0
2441 && sr.x >= rect.x
2442 && sr.right() <= rect.right()
2443 && sr.y >= rect.y
2444 && sr.bottom() <= rect.bottom()
2445 })
2446 .map(|(_, sr)| *sr)
2447 .collect();
2448 self.auto_scroll_nested(&rect, state, &inner_rects);
2449 }
2450
2451 self.container().scroll_offset(state.offset as u32)
2452 }
2453
2454 pub fn scrollbar(&mut self, state: &ScrollState) {
2474 let vh = state.viewport_height();
2475 let ch = state.content_height();
2476 if vh == 0 || ch <= vh {
2477 return;
2478 }
2479
2480 let track_height = vh;
2481 let thumb_height = ((vh as f64 * vh as f64 / ch as f64).ceil() as u32).max(1);
2482 let max_offset = ch.saturating_sub(vh);
2483 let thumb_pos = if max_offset == 0 {
2484 0
2485 } else {
2486 ((state.offset as f64 / max_offset as f64) * (track_height - thumb_height) as f64)
2487 .round() as u32
2488 };
2489
2490 let theme = self.theme;
2491 let track_char = '│';
2492 let thumb_char = '█';
2493
2494 self.container().w(1).h(track_height).col(|ui| {
2495 for i in 0..track_height {
2496 if i >= thumb_pos && i < thumb_pos + thumb_height {
2497 ui.styled(thumb_char.to_string(), Style::new().fg(theme.primary));
2498 } else {
2499 ui.styled(
2500 track_char.to_string(),
2501 Style::new().fg(theme.text_dim).dim(),
2502 );
2503 }
2504 }
2505 });
2506 }
2507
2508 fn auto_scroll_nested(
2509 &mut self,
2510 rect: &Rect,
2511 state: &mut ScrollState,
2512 inner_scroll_rects: &[Rect],
2513 ) {
2514 let mut to_consume: Vec<usize> = Vec::new();
2515
2516 for (i, event) in self.events.iter().enumerate() {
2517 if self.consumed[i] {
2518 continue;
2519 }
2520 if let Event::Mouse(mouse) = event {
2521 let in_bounds = mouse.x >= rect.x
2522 && mouse.x < rect.right()
2523 && mouse.y >= rect.y
2524 && mouse.y < rect.bottom();
2525 if !in_bounds {
2526 continue;
2527 }
2528 let in_inner = inner_scroll_rects.iter().any(|sr| {
2529 mouse.x >= sr.x
2530 && mouse.x < sr.right()
2531 && mouse.y >= sr.y
2532 && mouse.y < sr.bottom()
2533 });
2534 if in_inner {
2535 continue;
2536 }
2537 match mouse.kind {
2538 MouseKind::ScrollUp => {
2539 state.scroll_up(1);
2540 to_consume.push(i);
2541 }
2542 MouseKind::ScrollDown => {
2543 state.scroll_down(1);
2544 to_consume.push(i);
2545 }
2546 MouseKind::Drag(MouseButton::Left) => {}
2547 _ => {}
2548 }
2549 }
2550 }
2551
2552 for i in to_consume {
2553 self.consumed[i] = true;
2554 }
2555 }
2556
2557 pub fn bordered(&mut self, border: Border) -> ContainerBuilder<'_> {
2561 self.container()
2562 .border(border)
2563 .border_sides(BorderSides::all())
2564 }
2565
2566 fn push_container(
2567 &mut self,
2568 direction: Direction,
2569 gap: u32,
2570 f: impl FnOnce(&mut Context),
2571 ) -> Response {
2572 let interaction_id = self.interaction_count;
2573 self.interaction_count += 1;
2574 let border = self.theme.border;
2575
2576 self.commands.push(Command::BeginContainer {
2577 direction,
2578 gap,
2579 align: Align::Start,
2580 justify: Justify::Start,
2581 border: None,
2582 border_sides: BorderSides::all(),
2583 border_style: Style::new().fg(border),
2584 bg_color: None,
2585 padding: Padding::default(),
2586 margin: Margin::default(),
2587 constraints: Constraints::default(),
2588 title: None,
2589 grow: 0,
2590 group_name: None,
2591 });
2592 f(self);
2593 self.commands.push(Command::EndContainer);
2594 self.last_text_idx = None;
2595
2596 self.response_for(interaction_id)
2597 }
2598
2599 fn response_for(&self, interaction_id: usize) -> Response {
2600 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
2601 return Response::default();
2602 }
2603 if let Some(rect) = self.prev_hit_map.get(interaction_id) {
2604 let clicked = self
2605 .click_pos
2606 .map(|(mx, my)| {
2607 mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom()
2608 })
2609 .unwrap_or(false);
2610 let hovered = self
2611 .mouse_pos
2612 .map(|(mx, my)| {
2613 mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom()
2614 })
2615 .unwrap_or(false);
2616 Response { clicked, hovered }
2617 } else {
2618 Response::default()
2619 }
2620 }
2621
2622 pub fn is_group_hovered(&self, name: &str) -> bool {
2624 if let Some(pos) = self.mouse_pos {
2625 self.prev_group_rects.iter().any(|(n, rect)| {
2626 n == name
2627 && pos.0 >= rect.x
2628 && pos.0 < rect.x + rect.width
2629 && pos.1 >= rect.y
2630 && pos.1 < rect.y + rect.height
2631 })
2632 } else {
2633 false
2634 }
2635 }
2636
2637 pub fn is_group_focused(&self, name: &str) -> bool {
2639 if self.prev_focus_count == 0 {
2640 return false;
2641 }
2642 let focused_index = self.focus_index % self.prev_focus_count;
2643 self.prev_focus_groups
2644 .get(focused_index)
2645 .and_then(|group| group.as_deref())
2646 .map(|group| group == name)
2647 .unwrap_or(false)
2648 }
2649
2650 pub fn grow(&mut self, value: u16) -> &mut Self {
2655 if let Some(idx) = self.last_text_idx {
2656 if let Command::Text { grow, .. } = &mut self.commands[idx] {
2657 *grow = value;
2658 }
2659 }
2660 self
2661 }
2662
2663 pub fn align(&mut self, align: Align) -> &mut Self {
2665 if let Some(idx) = self.last_text_idx {
2666 if let Command::Text {
2667 align: text_align, ..
2668 } = &mut self.commands[idx]
2669 {
2670 *text_align = align;
2671 }
2672 }
2673 self
2674 }
2675
2676 pub fn spacer(&mut self) -> &mut Self {
2680 self.commands.push(Command::Spacer { grow: 1 });
2681 self.last_text_idx = None;
2682 self
2683 }
2684
2685 pub fn form(
2689 &mut self,
2690 state: &mut FormState,
2691 f: impl FnOnce(&mut Context, &mut FormState),
2692 ) -> &mut Self {
2693 self.col(|ui| {
2694 f(ui, state);
2695 });
2696 self
2697 }
2698
2699 pub fn form_field(&mut self, field: &mut FormField) -> &mut Self {
2703 self.col(|ui| {
2704 ui.styled(field.label.clone(), Style::new().bold().fg(ui.theme.text));
2705 ui.text_input(&mut field.input);
2706 if let Some(error) = field.error.as_deref() {
2707 ui.styled(error.to_string(), Style::new().dim().fg(ui.theme.error));
2708 }
2709 });
2710 self
2711 }
2712
2713 pub fn form_submit(&mut self, label: impl Into<String>) -> bool {
2717 self.button(label)
2718 }
2719
2720 pub fn text_input(&mut self, state: &mut TextInputState) -> &mut Self {
2736 slt_assert(
2737 !state.value.contains('\n'),
2738 "text_input got a newline — use textarea instead",
2739 );
2740 let focused = self.register_focusable();
2741 state.cursor = state.cursor.min(state.value.chars().count());
2742
2743 if focused {
2744 let mut consumed_indices = Vec::new();
2745 for (i, event) in self.events.iter().enumerate() {
2746 if let Event::Key(key) = event {
2747 if key.kind != KeyEventKind::Press {
2748 continue;
2749 }
2750 match key.code {
2751 KeyCode::Char(ch) => {
2752 if let Some(max) = state.max_length {
2753 if state.value.chars().count() >= max {
2754 continue;
2755 }
2756 }
2757 let index = byte_index_for_char(&state.value, state.cursor);
2758 state.value.insert(index, ch);
2759 state.cursor += 1;
2760 consumed_indices.push(i);
2761 }
2762 KeyCode::Backspace => {
2763 if state.cursor > 0 {
2764 let start = byte_index_for_char(&state.value, state.cursor - 1);
2765 let end = byte_index_for_char(&state.value, state.cursor);
2766 state.value.replace_range(start..end, "");
2767 state.cursor -= 1;
2768 }
2769 consumed_indices.push(i);
2770 }
2771 KeyCode::Left => {
2772 state.cursor = state.cursor.saturating_sub(1);
2773 consumed_indices.push(i);
2774 }
2775 KeyCode::Right => {
2776 state.cursor = (state.cursor + 1).min(state.value.chars().count());
2777 consumed_indices.push(i);
2778 }
2779 KeyCode::Home => {
2780 state.cursor = 0;
2781 consumed_indices.push(i);
2782 }
2783 KeyCode::Delete => {
2784 let len = state.value.chars().count();
2785 if state.cursor < len {
2786 let start = byte_index_for_char(&state.value, state.cursor);
2787 let end = byte_index_for_char(&state.value, state.cursor + 1);
2788 state.value.replace_range(start..end, "");
2789 }
2790 consumed_indices.push(i);
2791 }
2792 KeyCode::End => {
2793 state.cursor = state.value.chars().count();
2794 consumed_indices.push(i);
2795 }
2796 _ => {}
2797 }
2798 }
2799 if let Event::Paste(ref text) = event {
2800 for ch in text.chars() {
2801 if let Some(max) = state.max_length {
2802 if state.value.chars().count() >= max {
2803 break;
2804 }
2805 }
2806 let index = byte_index_for_char(&state.value, state.cursor);
2807 state.value.insert(index, ch);
2808 state.cursor += 1;
2809 }
2810 consumed_indices.push(i);
2811 }
2812 }
2813
2814 for index in consumed_indices {
2815 self.consumed[index] = true;
2816 }
2817 }
2818
2819 let show_cursor = focused && (self.tick / 30) % 2 == 0;
2820
2821 let input_text = if state.value.is_empty() {
2822 if state.placeholder.len() > 100 {
2823 slt_warn(
2824 "text_input placeholder is very long (>100 chars) — consider shortening it",
2825 );
2826 }
2827 state.placeholder.clone()
2828 } else {
2829 let mut rendered = String::new();
2830 for (idx, ch) in state.value.chars().enumerate() {
2831 if show_cursor && idx == state.cursor {
2832 rendered.push('▎');
2833 }
2834 rendered.push(if state.masked { '•' } else { ch });
2835 }
2836 if show_cursor && state.cursor >= state.value.chars().count() {
2837 rendered.push('▎');
2838 }
2839 rendered
2840 };
2841 let input_style = if state.value.is_empty() {
2842 Style::new().dim().fg(self.theme.text_dim)
2843 } else {
2844 Style::new().fg(self.theme.text)
2845 };
2846
2847 let border_color = if focused {
2848 self.theme.primary
2849 } else if state.validation_error.is_some() {
2850 self.theme.error
2851 } else {
2852 self.theme.border
2853 };
2854
2855 self.bordered(Border::Rounded)
2856 .border_style(Style::new().fg(border_color))
2857 .px(1)
2858 .col(|ui| {
2859 ui.styled(input_text, input_style);
2860 });
2861
2862 if let Some(error) = state.validation_error.clone() {
2863 self.styled(
2864 format!("⚠ {error}"),
2865 Style::new().dim().fg(self.theme.error),
2866 );
2867 }
2868 self
2869 }
2870
2871 pub fn spinner(&mut self, state: &SpinnerState) -> &mut Self {
2877 self.styled(
2878 state.frame(self.tick).to_string(),
2879 Style::new().fg(self.theme.primary),
2880 )
2881 }
2882
2883 pub fn toast(&mut self, state: &mut ToastState) -> &mut Self {
2888 state.cleanup(self.tick);
2889 if state.messages.is_empty() {
2890 return self;
2891 }
2892
2893 self.interaction_count += 1;
2894 self.commands.push(Command::BeginContainer {
2895 direction: Direction::Column,
2896 gap: 0,
2897 align: Align::Start,
2898 justify: Justify::Start,
2899 border: None,
2900 border_sides: BorderSides::all(),
2901 border_style: Style::new().fg(self.theme.border),
2902 bg_color: None,
2903 padding: Padding::default(),
2904 margin: Margin::default(),
2905 constraints: Constraints::default(),
2906 title: None,
2907 grow: 0,
2908 group_name: None,
2909 });
2910 for message in state.messages.iter().rev() {
2911 let color = match message.level {
2912 ToastLevel::Info => self.theme.primary,
2913 ToastLevel::Success => self.theme.success,
2914 ToastLevel::Warning => self.theme.warning,
2915 ToastLevel::Error => self.theme.error,
2916 };
2917 self.styled(format!(" ● {}", message.text), Style::new().fg(color));
2918 }
2919 self.commands.push(Command::EndContainer);
2920 self.last_text_idx = None;
2921
2922 self
2923 }
2924
2925 pub fn textarea(&mut self, state: &mut TextareaState, visible_rows: u32) -> &mut Self {
2933 if state.lines.is_empty() {
2934 state.lines.push(String::new());
2935 }
2936 state.cursor_row = state.cursor_row.min(state.lines.len().saturating_sub(1));
2937 state.cursor_col = state
2938 .cursor_col
2939 .min(state.lines[state.cursor_row].chars().count());
2940
2941 let focused = self.register_focusable();
2942 let wrap_w = state.wrap_width.unwrap_or(u32::MAX);
2943 let wrapping = state.wrap_width.is_some();
2944
2945 let pre_vlines = textarea_build_visual_lines(&state.lines, wrap_w);
2946
2947 if focused {
2948 let mut consumed_indices = Vec::new();
2949 for (i, event) in self.events.iter().enumerate() {
2950 if let Event::Key(key) = event {
2951 if key.kind != KeyEventKind::Press {
2952 continue;
2953 }
2954 match key.code {
2955 KeyCode::Char(ch) => {
2956 if let Some(max) = state.max_length {
2957 let total: usize =
2958 state.lines.iter().map(|line| line.chars().count()).sum();
2959 if total >= max {
2960 continue;
2961 }
2962 }
2963 let index = byte_index_for_char(
2964 &state.lines[state.cursor_row],
2965 state.cursor_col,
2966 );
2967 state.lines[state.cursor_row].insert(index, ch);
2968 state.cursor_col += 1;
2969 consumed_indices.push(i);
2970 }
2971 KeyCode::Enter => {
2972 let split_index = byte_index_for_char(
2973 &state.lines[state.cursor_row],
2974 state.cursor_col,
2975 );
2976 let remainder = state.lines[state.cursor_row].split_off(split_index);
2977 state.cursor_row += 1;
2978 state.lines.insert(state.cursor_row, remainder);
2979 state.cursor_col = 0;
2980 consumed_indices.push(i);
2981 }
2982 KeyCode::Backspace => {
2983 if state.cursor_col > 0 {
2984 let start = byte_index_for_char(
2985 &state.lines[state.cursor_row],
2986 state.cursor_col - 1,
2987 );
2988 let end = byte_index_for_char(
2989 &state.lines[state.cursor_row],
2990 state.cursor_col,
2991 );
2992 state.lines[state.cursor_row].replace_range(start..end, "");
2993 state.cursor_col -= 1;
2994 } else if state.cursor_row > 0 {
2995 let current = state.lines.remove(state.cursor_row);
2996 state.cursor_row -= 1;
2997 state.cursor_col = state.lines[state.cursor_row].chars().count();
2998 state.lines[state.cursor_row].push_str(¤t);
2999 }
3000 consumed_indices.push(i);
3001 }
3002 KeyCode::Left => {
3003 if state.cursor_col > 0 {
3004 state.cursor_col -= 1;
3005 } else if state.cursor_row > 0 {
3006 state.cursor_row -= 1;
3007 state.cursor_col = state.lines[state.cursor_row].chars().count();
3008 }
3009 consumed_indices.push(i);
3010 }
3011 KeyCode::Right => {
3012 let line_len = state.lines[state.cursor_row].chars().count();
3013 if state.cursor_col < line_len {
3014 state.cursor_col += 1;
3015 } else if state.cursor_row + 1 < state.lines.len() {
3016 state.cursor_row += 1;
3017 state.cursor_col = 0;
3018 }
3019 consumed_indices.push(i);
3020 }
3021 KeyCode::Up => {
3022 if wrapping {
3023 let (vrow, vcol) = textarea_logical_to_visual(
3024 &pre_vlines,
3025 state.cursor_row,
3026 state.cursor_col,
3027 );
3028 if vrow > 0 {
3029 let (lr, lc) =
3030 textarea_visual_to_logical(&pre_vlines, vrow - 1, vcol);
3031 state.cursor_row = lr;
3032 state.cursor_col = lc;
3033 }
3034 } else if state.cursor_row > 0 {
3035 state.cursor_row -= 1;
3036 state.cursor_col = state
3037 .cursor_col
3038 .min(state.lines[state.cursor_row].chars().count());
3039 }
3040 consumed_indices.push(i);
3041 }
3042 KeyCode::Down => {
3043 if wrapping {
3044 let (vrow, vcol) = textarea_logical_to_visual(
3045 &pre_vlines,
3046 state.cursor_row,
3047 state.cursor_col,
3048 );
3049 if vrow + 1 < pre_vlines.len() {
3050 let (lr, lc) =
3051 textarea_visual_to_logical(&pre_vlines, vrow + 1, vcol);
3052 state.cursor_row = lr;
3053 state.cursor_col = lc;
3054 }
3055 } else if state.cursor_row + 1 < state.lines.len() {
3056 state.cursor_row += 1;
3057 state.cursor_col = state
3058 .cursor_col
3059 .min(state.lines[state.cursor_row].chars().count());
3060 }
3061 consumed_indices.push(i);
3062 }
3063 KeyCode::Home => {
3064 state.cursor_col = 0;
3065 consumed_indices.push(i);
3066 }
3067 KeyCode::Delete => {
3068 let line_len = state.lines[state.cursor_row].chars().count();
3069 if state.cursor_col < line_len {
3070 let start = byte_index_for_char(
3071 &state.lines[state.cursor_row],
3072 state.cursor_col,
3073 );
3074 let end = byte_index_for_char(
3075 &state.lines[state.cursor_row],
3076 state.cursor_col + 1,
3077 );
3078 state.lines[state.cursor_row].replace_range(start..end, "");
3079 } else if state.cursor_row + 1 < state.lines.len() {
3080 let next = state.lines.remove(state.cursor_row + 1);
3081 state.lines[state.cursor_row].push_str(&next);
3082 }
3083 consumed_indices.push(i);
3084 }
3085 KeyCode::End => {
3086 state.cursor_col = state.lines[state.cursor_row].chars().count();
3087 consumed_indices.push(i);
3088 }
3089 _ => {}
3090 }
3091 }
3092 if let Event::Paste(ref text) = event {
3093 for ch in text.chars() {
3094 if ch == '\n' || ch == '\r' {
3095 let split_index = byte_index_for_char(
3096 &state.lines[state.cursor_row],
3097 state.cursor_col,
3098 );
3099 let remainder = state.lines[state.cursor_row].split_off(split_index);
3100 state.cursor_row += 1;
3101 state.lines.insert(state.cursor_row, remainder);
3102 state.cursor_col = 0;
3103 } else {
3104 if let Some(max) = state.max_length {
3105 let total: usize =
3106 state.lines.iter().map(|l| l.chars().count()).sum();
3107 if total >= max {
3108 break;
3109 }
3110 }
3111 let index = byte_index_for_char(
3112 &state.lines[state.cursor_row],
3113 state.cursor_col,
3114 );
3115 state.lines[state.cursor_row].insert(index, ch);
3116 state.cursor_col += 1;
3117 }
3118 }
3119 consumed_indices.push(i);
3120 }
3121 }
3122
3123 for index in consumed_indices {
3124 self.consumed[index] = true;
3125 }
3126 }
3127
3128 let vlines = textarea_build_visual_lines(&state.lines, wrap_w);
3129 let (cursor_vrow, cursor_vcol) =
3130 textarea_logical_to_visual(&vlines, state.cursor_row, state.cursor_col);
3131
3132 if cursor_vrow < state.scroll_offset {
3133 state.scroll_offset = cursor_vrow;
3134 }
3135 if cursor_vrow >= state.scroll_offset + visible_rows as usize {
3136 state.scroll_offset = cursor_vrow + 1 - visible_rows as usize;
3137 }
3138
3139 self.interaction_count += 1;
3140 self.commands.push(Command::BeginContainer {
3141 direction: Direction::Column,
3142 gap: 0,
3143 align: Align::Start,
3144 justify: Justify::Start,
3145 border: None,
3146 border_sides: BorderSides::all(),
3147 border_style: Style::new().fg(self.theme.border),
3148 bg_color: None,
3149 padding: Padding::default(),
3150 margin: Margin::default(),
3151 constraints: Constraints::default(),
3152 title: None,
3153 grow: 0,
3154 group_name: None,
3155 });
3156
3157 let show_cursor = focused && (self.tick / 30) % 2 == 0;
3158 for vi in 0..visible_rows as usize {
3159 let actual_vi = state.scroll_offset + vi;
3160 let (seg_text, is_cursor_line) = if let Some(vl) = vlines.get(actual_vi) {
3161 let line = &state.lines[vl.logical_row];
3162 let text: String = line
3163 .chars()
3164 .skip(vl.char_start)
3165 .take(vl.char_count)
3166 .collect();
3167 (text, actual_vi == cursor_vrow)
3168 } else {
3169 (String::new(), false)
3170 };
3171
3172 let mut rendered = seg_text.clone();
3173 let mut style = if seg_text.is_empty() {
3174 Style::new().fg(self.theme.text_dim)
3175 } else {
3176 Style::new().fg(self.theme.text)
3177 };
3178
3179 if is_cursor_line {
3180 rendered.clear();
3181 for (idx, ch) in seg_text.chars().enumerate() {
3182 if show_cursor && idx == cursor_vcol {
3183 rendered.push('▎');
3184 }
3185 rendered.push(ch);
3186 }
3187 if show_cursor && cursor_vcol >= seg_text.chars().count() {
3188 rendered.push('▎');
3189 }
3190 style = Style::new().fg(self.theme.text);
3191 }
3192
3193 self.styled(rendered, style);
3194 }
3195 self.commands.push(Command::EndContainer);
3196 self.last_text_idx = None;
3197
3198 self
3199 }
3200
3201 pub fn progress(&mut self, ratio: f64) -> &mut Self {
3206 self.progress_bar(ratio, 20)
3207 }
3208
3209 pub fn progress_bar(&mut self, ratio: f64, width: u32) -> &mut Self {
3214 let clamped = ratio.clamp(0.0, 1.0);
3215 let filled = (clamped * width as f64).round() as u32;
3216 let empty = width.saturating_sub(filled);
3217 let mut bar = String::new();
3218 for _ in 0..filled {
3219 bar.push('█');
3220 }
3221 for _ in 0..empty {
3222 bar.push('░');
3223 }
3224 self.text(bar)
3225 }
3226
3227 pub fn bar_chart(&mut self, data: &[(&str, f64)], max_width: u32) -> &mut Self {
3248 if data.is_empty() {
3249 return self;
3250 }
3251
3252 let max_label_width = data
3253 .iter()
3254 .map(|(label, _)| UnicodeWidthStr::width(*label))
3255 .max()
3256 .unwrap_or(0);
3257 let max_value = data
3258 .iter()
3259 .map(|(_, value)| *value)
3260 .fold(f64::NEG_INFINITY, f64::max);
3261 let denom = if max_value > 0.0 { max_value } else { 1.0 };
3262
3263 self.interaction_count += 1;
3264 self.commands.push(Command::BeginContainer {
3265 direction: Direction::Column,
3266 gap: 0,
3267 align: Align::Start,
3268 justify: Justify::Start,
3269 border: None,
3270 border_sides: BorderSides::all(),
3271 border_style: Style::new().fg(self.theme.border),
3272 bg_color: None,
3273 padding: Padding::default(),
3274 margin: Margin::default(),
3275 constraints: Constraints::default(),
3276 title: None,
3277 grow: 0,
3278 group_name: None,
3279 });
3280
3281 for (label, value) in data {
3282 let label_width = UnicodeWidthStr::width(*label);
3283 let label_padding = " ".repeat(max_label_width.saturating_sub(label_width));
3284 let normalized = (*value / denom).clamp(0.0, 1.0);
3285 let bar_len = (normalized * max_width as f64).round() as usize;
3286 let bar = "█".repeat(bar_len);
3287
3288 self.interaction_count += 1;
3289 self.commands.push(Command::BeginContainer {
3290 direction: Direction::Row,
3291 gap: 1,
3292 align: Align::Start,
3293 justify: Justify::Start,
3294 border: None,
3295 border_sides: BorderSides::all(),
3296 border_style: Style::new().fg(self.theme.border),
3297 bg_color: None,
3298 padding: Padding::default(),
3299 margin: Margin::default(),
3300 constraints: Constraints::default(),
3301 title: None,
3302 grow: 0,
3303 group_name: None,
3304 });
3305 self.styled(
3306 format!("{label}{label_padding}"),
3307 Style::new().fg(self.theme.text),
3308 );
3309 self.styled(bar, Style::new().fg(self.theme.primary));
3310 self.styled(
3311 format_compact_number(*value),
3312 Style::new().fg(self.theme.text_dim),
3313 );
3314 self.commands.push(Command::EndContainer);
3315 self.last_text_idx = None;
3316 }
3317
3318 self.commands.push(Command::EndContainer);
3319 self.last_text_idx = None;
3320
3321 self
3322 }
3323
3324 pub fn bar_chart_styled(
3340 &mut self,
3341 bars: &[Bar],
3342 max_width: u32,
3343 direction: BarDirection,
3344 ) -> &mut Self {
3345 if bars.is_empty() {
3346 return self;
3347 }
3348
3349 let max_value = bars
3350 .iter()
3351 .map(|bar| bar.value)
3352 .fold(f64::NEG_INFINITY, f64::max);
3353 let denom = if max_value > 0.0 { max_value } else { 1.0 };
3354
3355 match direction {
3356 BarDirection::Horizontal => {
3357 let max_label_width = bars
3358 .iter()
3359 .map(|bar| UnicodeWidthStr::width(bar.label.as_str()))
3360 .max()
3361 .unwrap_or(0);
3362
3363 self.interaction_count += 1;
3364 self.commands.push(Command::BeginContainer {
3365 direction: Direction::Column,
3366 gap: 0,
3367 align: Align::Start,
3368 justify: Justify::Start,
3369 border: None,
3370 border_sides: BorderSides::all(),
3371 border_style: Style::new().fg(self.theme.border),
3372 bg_color: None,
3373 padding: Padding::default(),
3374 margin: Margin::default(),
3375 constraints: Constraints::default(),
3376 title: None,
3377 grow: 0,
3378 group_name: None,
3379 });
3380
3381 for bar in bars {
3382 let label_width = UnicodeWidthStr::width(bar.label.as_str());
3383 let label_padding = " ".repeat(max_label_width.saturating_sub(label_width));
3384 let normalized = (bar.value / denom).clamp(0.0, 1.0);
3385 let bar_len = (normalized * max_width as f64).round() as usize;
3386 let bar_text = "█".repeat(bar_len);
3387 let color = bar.color.unwrap_or(self.theme.primary);
3388
3389 self.interaction_count += 1;
3390 self.commands.push(Command::BeginContainer {
3391 direction: Direction::Row,
3392 gap: 1,
3393 align: Align::Start,
3394 justify: Justify::Start,
3395 border: None,
3396 border_sides: BorderSides::all(),
3397 border_style: Style::new().fg(self.theme.border),
3398 bg_color: None,
3399 padding: Padding::default(),
3400 margin: Margin::default(),
3401 constraints: Constraints::default(),
3402 title: None,
3403 grow: 0,
3404 group_name: None,
3405 });
3406 self.styled(
3407 format!("{}{label_padding}", bar.label),
3408 Style::new().fg(self.theme.text),
3409 );
3410 self.styled(bar_text, Style::new().fg(color));
3411 self.styled(
3412 format_compact_number(bar.value),
3413 Style::new().fg(self.theme.text_dim),
3414 );
3415 self.commands.push(Command::EndContainer);
3416 self.last_text_idx = None;
3417 }
3418
3419 self.commands.push(Command::EndContainer);
3420 self.last_text_idx = None;
3421 }
3422 BarDirection::Vertical => {
3423 const FRACTION_BLOCKS: [char; 8] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇'];
3424
3425 let chart_height = max_width.max(1) as usize;
3426 let value_labels: Vec<String> = bars
3427 .iter()
3428 .map(|bar| format_compact_number(bar.value))
3429 .collect();
3430 let col_width = bars
3431 .iter()
3432 .zip(value_labels.iter())
3433 .map(|(bar, value)| {
3434 UnicodeWidthStr::width(bar.label.as_str())
3435 .max(UnicodeWidthStr::width(value.as_str()))
3436 .max(1)
3437 })
3438 .max()
3439 .unwrap_or(1);
3440
3441 let bar_units: Vec<usize> = bars
3442 .iter()
3443 .map(|bar| {
3444 let normalized = (bar.value / denom).clamp(0.0, 1.0);
3445 (normalized * chart_height as f64 * 8.0).round() as usize
3446 })
3447 .collect();
3448
3449 self.interaction_count += 1;
3450 self.commands.push(Command::BeginContainer {
3451 direction: Direction::Column,
3452 gap: 0,
3453 align: Align::Start,
3454 justify: Justify::Start,
3455 border: None,
3456 border_sides: BorderSides::all(),
3457 border_style: Style::new().fg(self.theme.border),
3458 bg_color: None,
3459 padding: Padding::default(),
3460 margin: Margin::default(),
3461 constraints: Constraints::default(),
3462 title: None,
3463 grow: 0,
3464 group_name: None,
3465 });
3466
3467 self.interaction_count += 1;
3468 self.commands.push(Command::BeginContainer {
3469 direction: Direction::Row,
3470 gap: 1,
3471 align: Align::Start,
3472 justify: Justify::Start,
3473 border: None,
3474 border_sides: BorderSides::all(),
3475 border_style: Style::new().fg(self.theme.border),
3476 bg_color: None,
3477 padding: Padding::default(),
3478 margin: Margin::default(),
3479 constraints: Constraints::default(),
3480 title: None,
3481 grow: 0,
3482 group_name: None,
3483 });
3484 for value in &value_labels {
3485 self.styled(
3486 center_text(value, col_width),
3487 Style::new().fg(self.theme.text_dim),
3488 );
3489 }
3490 self.commands.push(Command::EndContainer);
3491 self.last_text_idx = None;
3492
3493 for row in (0..chart_height).rev() {
3494 self.interaction_count += 1;
3495 self.commands.push(Command::BeginContainer {
3496 direction: Direction::Row,
3497 gap: 1,
3498 align: Align::Start,
3499 justify: Justify::Start,
3500 border: None,
3501 border_sides: BorderSides::all(),
3502 border_style: Style::new().fg(self.theme.border),
3503 bg_color: None,
3504 padding: Padding::default(),
3505 margin: Margin::default(),
3506 constraints: Constraints::default(),
3507 title: None,
3508 grow: 0,
3509 group_name: None,
3510 });
3511
3512 let row_base = row * 8;
3513 for (bar, units) in bars.iter().zip(bar_units.iter()) {
3514 let fill = if *units <= row_base {
3515 ' '
3516 } else {
3517 let delta = *units - row_base;
3518 if delta >= 8 {
3519 '█'
3520 } else {
3521 FRACTION_BLOCKS[delta]
3522 }
3523 };
3524
3525 self.styled(
3526 center_text(&fill.to_string(), col_width),
3527 Style::new().fg(bar.color.unwrap_or(self.theme.primary)),
3528 );
3529 }
3530
3531 self.commands.push(Command::EndContainer);
3532 self.last_text_idx = None;
3533 }
3534
3535 self.interaction_count += 1;
3536 self.commands.push(Command::BeginContainer {
3537 direction: Direction::Row,
3538 gap: 1,
3539 align: Align::Start,
3540 justify: Justify::Start,
3541 border: None,
3542 border_sides: BorderSides::all(),
3543 border_style: Style::new().fg(self.theme.border),
3544 bg_color: None,
3545 padding: Padding::default(),
3546 margin: Margin::default(),
3547 constraints: Constraints::default(),
3548 title: None,
3549 grow: 0,
3550 group_name: None,
3551 });
3552 for bar in bars {
3553 self.styled(
3554 center_text(&bar.label, col_width),
3555 Style::new().fg(self.theme.text),
3556 );
3557 }
3558 self.commands.push(Command::EndContainer);
3559 self.last_text_idx = None;
3560
3561 self.commands.push(Command::EndContainer);
3562 self.last_text_idx = None;
3563 }
3564 }
3565
3566 self
3567 }
3568
3569 pub fn bar_chart_grouped(&mut self, groups: &[BarGroup], max_width: u32) -> &mut Self {
3586 if groups.is_empty() {
3587 return self;
3588 }
3589
3590 let all_bars: Vec<&Bar> = groups.iter().flat_map(|group| group.bars.iter()).collect();
3591 if all_bars.is_empty() {
3592 return self;
3593 }
3594
3595 let max_label_width = all_bars
3596 .iter()
3597 .map(|bar| UnicodeWidthStr::width(bar.label.as_str()))
3598 .max()
3599 .unwrap_or(0);
3600 let max_value = all_bars
3601 .iter()
3602 .map(|bar| bar.value)
3603 .fold(f64::NEG_INFINITY, f64::max);
3604 let denom = if max_value > 0.0 { max_value } else { 1.0 };
3605
3606 self.interaction_count += 1;
3607 self.commands.push(Command::BeginContainer {
3608 direction: Direction::Column,
3609 gap: 1,
3610 align: Align::Start,
3611 justify: Justify::Start,
3612 border: None,
3613 border_sides: BorderSides::all(),
3614 border_style: Style::new().fg(self.theme.border),
3615 bg_color: None,
3616 padding: Padding::default(),
3617 margin: Margin::default(),
3618 constraints: Constraints::default(),
3619 title: None,
3620 grow: 0,
3621 group_name: None,
3622 });
3623
3624 for group in groups {
3625 self.styled(group.label.clone(), Style::new().bold().fg(self.theme.text));
3626
3627 for bar in &group.bars {
3628 let label_width = UnicodeWidthStr::width(bar.label.as_str());
3629 let label_padding = " ".repeat(max_label_width.saturating_sub(label_width));
3630 let normalized = (bar.value / denom).clamp(0.0, 1.0);
3631 let bar_len = (normalized * max_width as f64).round() as usize;
3632 let bar_text = "█".repeat(bar_len);
3633
3634 self.interaction_count += 1;
3635 self.commands.push(Command::BeginContainer {
3636 direction: Direction::Row,
3637 gap: 1,
3638 align: Align::Start,
3639 justify: Justify::Start,
3640 border: None,
3641 border_sides: BorderSides::all(),
3642 border_style: Style::new().fg(self.theme.border),
3643 bg_color: None,
3644 padding: Padding::default(),
3645 margin: Margin::default(),
3646 constraints: Constraints::default(),
3647 title: None,
3648 grow: 0,
3649 group_name: None,
3650 });
3651 self.styled(
3652 format!(" {}{label_padding}", bar.label),
3653 Style::new().fg(self.theme.text),
3654 );
3655 self.styled(
3656 bar_text,
3657 Style::new().fg(bar.color.unwrap_or(self.theme.primary)),
3658 );
3659 self.styled(
3660 format_compact_number(bar.value),
3661 Style::new().fg(self.theme.text_dim),
3662 );
3663 self.commands.push(Command::EndContainer);
3664 self.last_text_idx = None;
3665 }
3666 }
3667
3668 self.commands.push(Command::EndContainer);
3669 self.last_text_idx = None;
3670
3671 self
3672 }
3673
3674 pub fn sparkline(&mut self, data: &[f64], width: u32) -> &mut Self {
3690 const BLOCKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
3691
3692 let w = width as usize;
3693 let window = if data.len() > w {
3694 &data[data.len() - w..]
3695 } else {
3696 data
3697 };
3698
3699 if window.is_empty() {
3700 return self;
3701 }
3702
3703 let min = window.iter().copied().fold(f64::INFINITY, f64::min);
3704 let max = window.iter().copied().fold(f64::NEG_INFINITY, f64::max);
3705 let range = max - min;
3706
3707 let line: String = window
3708 .iter()
3709 .map(|&value| {
3710 let normalized = if range == 0.0 {
3711 0.5
3712 } else {
3713 (value - min) / range
3714 };
3715 let idx = (normalized * 7.0).round() as usize;
3716 BLOCKS[idx.min(7)]
3717 })
3718 .collect();
3719
3720 self.styled(line, Style::new().fg(self.theme.primary))
3721 }
3722
3723 pub fn sparkline_styled(&mut self, data: &[(f64, Option<Color>)], width: u32) -> &mut Self {
3743 const BLOCKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
3744
3745 let w = width as usize;
3746 let window = if data.len() > w {
3747 &data[data.len() - w..]
3748 } else {
3749 data
3750 };
3751
3752 if window.is_empty() {
3753 return self;
3754 }
3755
3756 let mut finite_values = window
3757 .iter()
3758 .map(|(value, _)| *value)
3759 .filter(|value| !value.is_nan());
3760 let Some(first) = finite_values.next() else {
3761 return self.styled(
3762 " ".repeat(window.len()),
3763 Style::new().fg(self.theme.text_dim),
3764 );
3765 };
3766
3767 let mut min = first;
3768 let mut max = first;
3769 for value in finite_values {
3770 min = f64::min(min, value);
3771 max = f64::max(max, value);
3772 }
3773 let range = max - min;
3774
3775 let mut cells: Vec<(char, Color)> = Vec::with_capacity(window.len());
3776 for (value, color) in window {
3777 if value.is_nan() {
3778 cells.push((' ', self.theme.text_dim));
3779 continue;
3780 }
3781
3782 let normalized = if range == 0.0 {
3783 0.5
3784 } else {
3785 ((*value - min) / range).clamp(0.0, 1.0)
3786 };
3787 let idx = (normalized * 7.0).round() as usize;
3788 cells.push((BLOCKS[idx.min(7)], color.unwrap_or(self.theme.primary)));
3789 }
3790
3791 self.interaction_count += 1;
3792 self.commands.push(Command::BeginContainer {
3793 direction: Direction::Row,
3794 gap: 0,
3795 align: Align::Start,
3796 justify: Justify::Start,
3797 border: None,
3798 border_sides: BorderSides::all(),
3799 border_style: Style::new().fg(self.theme.border),
3800 bg_color: None,
3801 padding: Padding::default(),
3802 margin: Margin::default(),
3803 constraints: Constraints::default(),
3804 title: None,
3805 grow: 0,
3806 group_name: None,
3807 });
3808
3809 let mut seg = String::new();
3810 let mut seg_color = cells[0].1;
3811 for (ch, color) in cells {
3812 if color != seg_color {
3813 self.styled(seg, Style::new().fg(seg_color));
3814 seg = String::new();
3815 seg_color = color;
3816 }
3817 seg.push(ch);
3818 }
3819 if !seg.is_empty() {
3820 self.styled(seg, Style::new().fg(seg_color));
3821 }
3822
3823 self.commands.push(Command::EndContainer);
3824 self.last_text_idx = None;
3825
3826 self
3827 }
3828
3829 pub fn line_chart(&mut self, data: &[f64], width: u32, height: u32) -> &mut Self {
3843 if data.is_empty() || width == 0 || height == 0 {
3844 return self;
3845 }
3846
3847 let cols = width as usize;
3848 let rows = height as usize;
3849 let px_w = cols * 2;
3850 let px_h = rows * 4;
3851
3852 let min = data.iter().copied().fold(f64::INFINITY, f64::min);
3853 let max = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
3854 let range = if (max - min).abs() < f64::EPSILON {
3855 1.0
3856 } else {
3857 max - min
3858 };
3859
3860 let points: Vec<usize> = (0..px_w)
3861 .map(|px| {
3862 let data_idx = if px_w <= 1 {
3863 0.0
3864 } else {
3865 px as f64 * (data.len() - 1) as f64 / (px_w - 1) as f64
3866 };
3867 let idx = data_idx.floor() as usize;
3868 let frac = data_idx - idx as f64;
3869 let value = if idx + 1 < data.len() {
3870 data[idx] * (1.0 - frac) + data[idx + 1] * frac
3871 } else {
3872 data[idx.min(data.len() - 1)]
3873 };
3874
3875 let normalized = (value - min) / range;
3876 let py = ((1.0 - normalized) * (px_h - 1) as f64).round() as usize;
3877 py.min(px_h - 1)
3878 })
3879 .collect();
3880
3881 const LEFT_BITS: [u32; 4] = [0x01, 0x02, 0x04, 0x40];
3882 const RIGHT_BITS: [u32; 4] = [0x08, 0x10, 0x20, 0x80];
3883
3884 let mut grid = vec![vec![0u32; cols]; rows];
3885
3886 for i in 0..points.len() {
3887 let px = i;
3888 let py = points[i];
3889 let char_col = px / 2;
3890 let char_row = py / 4;
3891 let sub_col = px % 2;
3892 let sub_row = py % 4;
3893
3894 if char_col < cols && char_row < rows {
3895 grid[char_row][char_col] |= if sub_col == 0 {
3896 LEFT_BITS[sub_row]
3897 } else {
3898 RIGHT_BITS[sub_row]
3899 };
3900 }
3901
3902 if i + 1 < points.len() {
3903 let py_next = points[i + 1];
3904 let (y_start, y_end) = if py <= py_next {
3905 (py, py_next)
3906 } else {
3907 (py_next, py)
3908 };
3909 for y in y_start..=y_end {
3910 let cell_row = y / 4;
3911 let sub_y = y % 4;
3912 if char_col < cols && cell_row < rows {
3913 grid[cell_row][char_col] |= if sub_col == 0 {
3914 LEFT_BITS[sub_y]
3915 } else {
3916 RIGHT_BITS[sub_y]
3917 };
3918 }
3919 }
3920 }
3921 }
3922
3923 let style = Style::new().fg(self.theme.primary);
3924 for row in grid {
3925 let line: String = row
3926 .iter()
3927 .map(|&bits| char::from_u32(0x2800 + bits).unwrap_or(' '))
3928 .collect();
3929 self.styled(line, style);
3930 }
3931
3932 self
3933 }
3934
3935 pub fn canvas(
3952 &mut self,
3953 width: u32,
3954 height: u32,
3955 draw: impl FnOnce(&mut CanvasContext),
3956 ) -> &mut Self {
3957 if width == 0 || height == 0 {
3958 return self;
3959 }
3960
3961 let mut canvas = CanvasContext::new(width as usize, height as usize);
3962 draw(&mut canvas);
3963
3964 for segments in canvas.render() {
3965 self.interaction_count += 1;
3966 self.commands.push(Command::BeginContainer {
3967 direction: Direction::Row,
3968 gap: 0,
3969 align: Align::Start,
3970 justify: Justify::Start,
3971 border: None,
3972 border_sides: BorderSides::all(),
3973 border_style: Style::new(),
3974 bg_color: None,
3975 padding: Padding::default(),
3976 margin: Margin::default(),
3977 constraints: Constraints::default(),
3978 title: None,
3979 grow: 0,
3980 group_name: None,
3981 });
3982 for (text, color) in segments {
3983 let c = if color == Color::Reset {
3984 self.theme.primary
3985 } else {
3986 color
3987 };
3988 self.styled(text, Style::new().fg(c));
3989 }
3990 self.commands.push(Command::EndContainer);
3991 self.last_text_idx = None;
3992 }
3993
3994 self
3995 }
3996
3997 pub fn chart(
3999 &mut self,
4000 configure: impl FnOnce(&mut ChartBuilder),
4001 width: u32,
4002 height: u32,
4003 ) -> &mut Self {
4004 if width == 0 || height == 0 {
4005 return self;
4006 }
4007
4008 let axis_style = Style::new().fg(self.theme.text_dim);
4009 let mut builder = ChartBuilder::new(width, height, axis_style, axis_style);
4010 configure(&mut builder);
4011
4012 let config = builder.build();
4013 let rows = render_chart(&config);
4014
4015 for row in rows {
4016 self.interaction_count += 1;
4017 self.commands.push(Command::BeginContainer {
4018 direction: Direction::Row,
4019 gap: 0,
4020 align: Align::Start,
4021 justify: Justify::Start,
4022 border: None,
4023 border_sides: BorderSides::all(),
4024 border_style: Style::new().fg(self.theme.border),
4025 bg_color: None,
4026 padding: Padding::default(),
4027 margin: Margin::default(),
4028 constraints: Constraints::default(),
4029 title: None,
4030 grow: 0,
4031 group_name: None,
4032 });
4033 for (text, style) in row.segments {
4034 self.styled(text, style);
4035 }
4036 self.commands.push(Command::EndContainer);
4037 self.last_text_idx = None;
4038 }
4039
4040 self
4041 }
4042
4043 pub fn scatter(&mut self, data: &[(f64, f64)], width: u32, height: u32) -> &mut Self {
4047 self.chart(
4048 |c| {
4049 c.scatter(data);
4050 c.grid(true);
4051 },
4052 width,
4053 height,
4054 )
4055 }
4056
4057 pub fn histogram(&mut self, data: &[f64], width: u32, height: u32) -> &mut Self {
4059 self.histogram_with(data, |_| {}, width, height)
4060 }
4061
4062 pub fn histogram_with(
4064 &mut self,
4065 data: &[f64],
4066 configure: impl FnOnce(&mut HistogramBuilder),
4067 width: u32,
4068 height: u32,
4069 ) -> &mut Self {
4070 if width == 0 || height == 0 {
4071 return self;
4072 }
4073
4074 let mut options = HistogramBuilder::default();
4075 configure(&mut options);
4076 let axis_style = Style::new().fg(self.theme.text_dim);
4077 let config = build_histogram_config(data, &options, width, height, axis_style);
4078 let rows = render_chart(&config);
4079
4080 for row in rows {
4081 self.interaction_count += 1;
4082 self.commands.push(Command::BeginContainer {
4083 direction: Direction::Row,
4084 gap: 0,
4085 align: Align::Start,
4086 justify: Justify::Start,
4087 border: None,
4088 border_sides: BorderSides::all(),
4089 border_style: Style::new().fg(self.theme.border),
4090 bg_color: None,
4091 padding: Padding::default(),
4092 margin: Margin::default(),
4093 constraints: Constraints::default(),
4094 title: None,
4095 grow: 0,
4096 group_name: None,
4097 });
4098 for (text, style) in row.segments {
4099 self.styled(text, style);
4100 }
4101 self.commands.push(Command::EndContainer);
4102 self.last_text_idx = None;
4103 }
4104
4105 self
4106 }
4107
4108 pub fn grid(&mut self, cols: u32, f: impl FnOnce(&mut Context)) -> Response {
4125 slt_assert(cols > 0, "grid() requires at least 1 column");
4126 let interaction_id = self.interaction_count;
4127 self.interaction_count += 1;
4128 let border = self.theme.border;
4129
4130 self.commands.push(Command::BeginContainer {
4131 direction: Direction::Column,
4132 gap: 0,
4133 align: Align::Start,
4134 justify: Justify::Start,
4135 border: None,
4136 border_sides: BorderSides::all(),
4137 border_style: Style::new().fg(border),
4138 bg_color: None,
4139 padding: Padding::default(),
4140 margin: Margin::default(),
4141 constraints: Constraints::default(),
4142 title: None,
4143 grow: 0,
4144 group_name: None,
4145 });
4146
4147 let children_start = self.commands.len();
4148 f(self);
4149 let child_commands: Vec<Command> = self.commands.drain(children_start..).collect();
4150
4151 let mut elements: Vec<Vec<Command>> = Vec::new();
4152 let mut iter = child_commands.into_iter().peekable();
4153 while let Some(cmd) = iter.next() {
4154 match cmd {
4155 Command::BeginContainer { .. } | Command::BeginScrollable { .. } => {
4156 let mut depth = 1_u32;
4157 let mut element = vec![cmd];
4158 for next in iter.by_ref() {
4159 match next {
4160 Command::BeginContainer { .. } | Command::BeginScrollable { .. } => {
4161 depth += 1;
4162 }
4163 Command::EndContainer => {
4164 depth = depth.saturating_sub(1);
4165 }
4166 _ => {}
4167 }
4168 let at_end = matches!(next, Command::EndContainer) && depth == 0;
4169 element.push(next);
4170 if at_end {
4171 break;
4172 }
4173 }
4174 elements.push(element);
4175 }
4176 Command::EndContainer => {}
4177 _ => elements.push(vec![cmd]),
4178 }
4179 }
4180
4181 let cols = cols.max(1) as usize;
4182 for row in elements.chunks(cols) {
4183 self.interaction_count += 1;
4184 self.commands.push(Command::BeginContainer {
4185 direction: Direction::Row,
4186 gap: 0,
4187 align: Align::Start,
4188 justify: Justify::Start,
4189 border: None,
4190 border_sides: BorderSides::all(),
4191 border_style: Style::new().fg(border),
4192 bg_color: None,
4193 padding: Padding::default(),
4194 margin: Margin::default(),
4195 constraints: Constraints::default(),
4196 title: None,
4197 grow: 0,
4198 group_name: None,
4199 });
4200
4201 for element in row {
4202 self.interaction_count += 1;
4203 self.commands.push(Command::BeginContainer {
4204 direction: Direction::Column,
4205 gap: 0,
4206 align: Align::Start,
4207 justify: Justify::Start,
4208 border: None,
4209 border_sides: BorderSides::all(),
4210 border_style: Style::new().fg(border),
4211 bg_color: None,
4212 padding: Padding::default(),
4213 margin: Margin::default(),
4214 constraints: Constraints::default(),
4215 title: None,
4216 grow: 1,
4217 group_name: None,
4218 });
4219 self.commands.extend(element.iter().cloned());
4220 self.commands.push(Command::EndContainer);
4221 }
4222
4223 self.commands.push(Command::EndContainer);
4224 }
4225
4226 self.commands.push(Command::EndContainer);
4227 self.last_text_idx = None;
4228
4229 self.response_for(interaction_id)
4230 }
4231
4232 pub fn list(&mut self, state: &mut ListState) -> &mut Self {
4237 let visible = state.visible_indices().to_vec();
4238 if visible.is_empty() && state.items.is_empty() {
4239 state.selected = 0;
4240 return self;
4241 }
4242
4243 if !visible.is_empty() {
4244 state.selected = state.selected.min(visible.len().saturating_sub(1));
4245 }
4246
4247 let focused = self.register_focusable();
4248 let interaction_id = self.interaction_count;
4249 self.interaction_count += 1;
4250
4251 if focused {
4252 let mut consumed_indices = Vec::new();
4253 for (i, event) in self.events.iter().enumerate() {
4254 if let Event::Key(key) = event {
4255 if key.kind != KeyEventKind::Press {
4256 continue;
4257 }
4258 match key.code {
4259 KeyCode::Up | KeyCode::Char('k') => {
4260 state.selected = state.selected.saturating_sub(1);
4261 consumed_indices.push(i);
4262 }
4263 KeyCode::Down | KeyCode::Char('j') => {
4264 state.selected =
4265 (state.selected + 1).min(visible.len().saturating_sub(1));
4266 consumed_indices.push(i);
4267 }
4268 _ => {}
4269 }
4270 }
4271 }
4272
4273 for index in consumed_indices {
4274 self.consumed[index] = true;
4275 }
4276 }
4277
4278 if let Some(rect) = self.prev_hit_map.get(interaction_id).copied() {
4279 for (i, event) in self.events.iter().enumerate() {
4280 if self.consumed[i] {
4281 continue;
4282 }
4283 if let Event::Mouse(mouse) = event {
4284 if !matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
4285 continue;
4286 }
4287 let in_bounds = mouse.x >= rect.x
4288 && mouse.x < rect.right()
4289 && mouse.y >= rect.y
4290 && mouse.y < rect.bottom();
4291 if !in_bounds {
4292 continue;
4293 }
4294 let clicked_idx = (mouse.y - rect.y) as usize;
4295 if clicked_idx < visible.len() {
4296 state.selected = clicked_idx;
4297 self.consumed[i] = true;
4298 }
4299 }
4300 }
4301 }
4302
4303 self.commands.push(Command::BeginContainer {
4304 direction: Direction::Column,
4305 gap: 0,
4306 align: Align::Start,
4307 justify: Justify::Start,
4308 border: None,
4309 border_sides: BorderSides::all(),
4310 border_style: Style::new().fg(self.theme.border),
4311 bg_color: None,
4312 padding: Padding::default(),
4313 margin: Margin::default(),
4314 constraints: Constraints::default(),
4315 title: None,
4316 grow: 0,
4317 group_name: None,
4318 });
4319
4320 for (view_idx, &item_idx) in visible.iter().enumerate() {
4321 let item = &state.items[item_idx];
4322 if view_idx == state.selected {
4323 if focused {
4324 self.styled(
4325 format!("▸ {item}"),
4326 Style::new().bold().fg(self.theme.primary),
4327 );
4328 } else {
4329 self.styled(format!("▸ {item}"), Style::new().fg(self.theme.primary));
4330 }
4331 } else {
4332 self.styled(format!(" {item}"), Style::new().fg(self.theme.text));
4333 }
4334 }
4335
4336 self.commands.push(Command::EndContainer);
4337 self.last_text_idx = None;
4338
4339 self
4340 }
4341
4342 pub fn table(&mut self, state: &mut TableState) -> &mut Self {
4347 if state.is_dirty() {
4348 state.recompute_widths();
4349 }
4350
4351 let focused = self.register_focusable();
4352 let interaction_id = self.interaction_count;
4353 self.interaction_count += 1;
4354
4355 if focused && !state.visible_indices().is_empty() {
4356 let mut consumed_indices = Vec::new();
4357 for (i, event) in self.events.iter().enumerate() {
4358 if let Event::Key(key) = event {
4359 if key.kind != KeyEventKind::Press {
4360 continue;
4361 }
4362 match key.code {
4363 KeyCode::Up | KeyCode::Char('k') => {
4364 let visible_len = if state.page_size > 0 {
4365 let start = state
4366 .page
4367 .saturating_mul(state.page_size)
4368 .min(state.visible_indices().len());
4369 let end =
4370 (start + state.page_size).min(state.visible_indices().len());
4371 end.saturating_sub(start)
4372 } else {
4373 state.visible_indices().len()
4374 };
4375 state.selected = state.selected.min(visible_len.saturating_sub(1));
4376 state.selected = state.selected.saturating_sub(1);
4377 consumed_indices.push(i);
4378 }
4379 KeyCode::Down | KeyCode::Char('j') => {
4380 let visible_len = if state.page_size > 0 {
4381 let start = state
4382 .page
4383 .saturating_mul(state.page_size)
4384 .min(state.visible_indices().len());
4385 let end =
4386 (start + state.page_size).min(state.visible_indices().len());
4387 end.saturating_sub(start)
4388 } else {
4389 state.visible_indices().len()
4390 };
4391 state.selected =
4392 (state.selected + 1).min(visible_len.saturating_sub(1));
4393 consumed_indices.push(i);
4394 }
4395 KeyCode::PageUp => {
4396 let old_page = state.page;
4397 state.prev_page();
4398 if state.page != old_page {
4399 state.selected = 0;
4400 }
4401 consumed_indices.push(i);
4402 }
4403 KeyCode::PageDown => {
4404 let old_page = state.page;
4405 state.next_page();
4406 if state.page != old_page {
4407 state.selected = 0;
4408 }
4409 consumed_indices.push(i);
4410 }
4411 _ => {}
4412 }
4413 }
4414 }
4415 for index in consumed_indices {
4416 self.consumed[index] = true;
4417 }
4418 }
4419
4420 if !state.visible_indices().is_empty() || !state.headers.is_empty() {
4421 if let Some(rect) = self.prev_hit_map.get(interaction_id).copied() {
4422 for (i, event) in self.events.iter().enumerate() {
4423 if self.consumed[i] {
4424 continue;
4425 }
4426 if let Event::Mouse(mouse) = event {
4427 if !matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
4428 continue;
4429 }
4430 let in_bounds = mouse.x >= rect.x
4431 && mouse.x < rect.right()
4432 && mouse.y >= rect.y
4433 && mouse.y < rect.bottom();
4434 if !in_bounds {
4435 continue;
4436 }
4437
4438 if mouse.y == rect.y {
4439 let rel_x = mouse.x.saturating_sub(rect.x);
4440 let mut x_offset = 0u32;
4441 for (col_idx, width) in state.column_widths().iter().enumerate() {
4442 if rel_x >= x_offset && rel_x < x_offset + *width {
4443 state.toggle_sort(col_idx);
4444 state.selected = 0;
4445 self.consumed[i] = true;
4446 break;
4447 }
4448 x_offset += *width;
4449 if col_idx + 1 < state.column_widths().len() {
4450 x_offset += 3;
4451 }
4452 }
4453 continue;
4454 }
4455
4456 if mouse.y < rect.y + 2 {
4457 continue;
4458 }
4459
4460 let visible_len = if state.page_size > 0 {
4461 let start = state
4462 .page
4463 .saturating_mul(state.page_size)
4464 .min(state.visible_indices().len());
4465 let end = (start + state.page_size).min(state.visible_indices().len());
4466 end.saturating_sub(start)
4467 } else {
4468 state.visible_indices().len()
4469 };
4470 let clicked_idx = (mouse.y - rect.y - 2) as usize;
4471 if clicked_idx < visible_len {
4472 state.selected = clicked_idx;
4473 self.consumed[i] = true;
4474 }
4475 }
4476 }
4477 }
4478 }
4479
4480 if state.is_dirty() {
4481 state.recompute_widths();
4482 }
4483
4484 let total_visible = state.visible_indices().len();
4485 let page_start = if state.page_size > 0 {
4486 state
4487 .page
4488 .saturating_mul(state.page_size)
4489 .min(total_visible)
4490 } else {
4491 0
4492 };
4493 let page_end = if state.page_size > 0 {
4494 (page_start + state.page_size).min(total_visible)
4495 } else {
4496 total_visible
4497 };
4498 let visible_len = page_end.saturating_sub(page_start);
4499 state.selected = state.selected.min(visible_len.saturating_sub(1));
4500
4501 self.commands.push(Command::BeginContainer {
4502 direction: Direction::Column,
4503 gap: 0,
4504 align: Align::Start,
4505 justify: Justify::Start,
4506 border: None,
4507 border_sides: BorderSides::all(),
4508 border_style: Style::new().fg(self.theme.border),
4509 bg_color: None,
4510 padding: Padding::default(),
4511 margin: Margin::default(),
4512 constraints: Constraints::default(),
4513 title: None,
4514 grow: 0,
4515 group_name: None,
4516 });
4517
4518 let header_cells = state
4519 .headers
4520 .iter()
4521 .enumerate()
4522 .map(|(i, header)| {
4523 if state.sort_column == Some(i) {
4524 if state.sort_ascending {
4525 format!("{header} ▲")
4526 } else {
4527 format!("{header} ▼")
4528 }
4529 } else {
4530 header.clone()
4531 }
4532 })
4533 .collect::<Vec<_>>();
4534 let header_line = format_table_row(&header_cells, state.column_widths(), " │ ");
4535 self.styled(header_line, Style::new().bold().fg(self.theme.text));
4536
4537 let separator = state
4538 .column_widths()
4539 .iter()
4540 .map(|w| "─".repeat(*w as usize))
4541 .collect::<Vec<_>>()
4542 .join("─┼─");
4543 self.text(separator);
4544
4545 for idx in 0..visible_len {
4546 let data_idx = state.visible_indices()[page_start + idx];
4547 let Some(row) = state.rows.get(data_idx) else {
4548 continue;
4549 };
4550 let line = format_table_row(row, state.column_widths(), " │ ");
4551 if idx == state.selected {
4552 let mut style = Style::new()
4553 .bg(self.theme.selected_bg)
4554 .fg(self.theme.selected_fg);
4555 if focused {
4556 style = style.bold();
4557 }
4558 self.styled(line, style);
4559 } else {
4560 self.styled(line, Style::new().fg(self.theme.text));
4561 }
4562 }
4563
4564 if state.page_size > 0 && state.total_pages() > 1 {
4565 self.styled(
4566 format!("Page {}/{}", state.page + 1, state.total_pages()),
4567 Style::new().dim().fg(self.theme.text_dim),
4568 );
4569 }
4570
4571 self.commands.push(Command::EndContainer);
4572 self.last_text_idx = None;
4573
4574 self
4575 }
4576
4577 pub fn tabs(&mut self, state: &mut TabsState) -> &mut Self {
4582 if state.labels.is_empty() {
4583 state.selected = 0;
4584 return self;
4585 }
4586
4587 state.selected = state.selected.min(state.labels.len().saturating_sub(1));
4588 let focused = self.register_focusable();
4589 let interaction_id = self.interaction_count;
4590
4591 if focused {
4592 let mut consumed_indices = Vec::new();
4593 for (i, event) in self.events.iter().enumerate() {
4594 if let Event::Key(key) = event {
4595 if key.kind != KeyEventKind::Press {
4596 continue;
4597 }
4598 match key.code {
4599 KeyCode::Left => {
4600 state.selected = if state.selected == 0 {
4601 state.labels.len().saturating_sub(1)
4602 } else {
4603 state.selected - 1
4604 };
4605 consumed_indices.push(i);
4606 }
4607 KeyCode::Right => {
4608 state.selected = (state.selected + 1) % state.labels.len();
4609 consumed_indices.push(i);
4610 }
4611 _ => {}
4612 }
4613 }
4614 }
4615
4616 for index in consumed_indices {
4617 self.consumed[index] = true;
4618 }
4619 }
4620
4621 if let Some(rect) = self.prev_hit_map.get(interaction_id).copied() {
4622 for (i, event) in self.events.iter().enumerate() {
4623 if self.consumed[i] {
4624 continue;
4625 }
4626 if let Event::Mouse(mouse) = event {
4627 if !matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
4628 continue;
4629 }
4630 let in_bounds = mouse.x >= rect.x
4631 && mouse.x < rect.right()
4632 && mouse.y >= rect.y
4633 && mouse.y < rect.bottom();
4634 if !in_bounds {
4635 continue;
4636 }
4637
4638 let mut x_offset = 0u32;
4639 let rel_x = mouse.x - rect.x;
4640 for (idx, label) in state.labels.iter().enumerate() {
4641 let tab_width = UnicodeWidthStr::width(label.as_str()) as u32 + 4;
4642 if rel_x >= x_offset && rel_x < x_offset + tab_width {
4643 state.selected = idx;
4644 self.consumed[i] = true;
4645 break;
4646 }
4647 x_offset += tab_width + 1;
4648 }
4649 }
4650 }
4651 }
4652
4653 self.interaction_count += 1;
4654 self.commands.push(Command::BeginContainer {
4655 direction: Direction::Row,
4656 gap: 1,
4657 align: Align::Start,
4658 justify: Justify::Start,
4659 border: None,
4660 border_sides: BorderSides::all(),
4661 border_style: Style::new().fg(self.theme.border),
4662 bg_color: None,
4663 padding: Padding::default(),
4664 margin: Margin::default(),
4665 constraints: Constraints::default(),
4666 title: None,
4667 grow: 0,
4668 group_name: None,
4669 });
4670 for (idx, label) in state.labels.iter().enumerate() {
4671 let style = if idx == state.selected {
4672 let s = Style::new().fg(self.theme.primary).bold();
4673 if focused {
4674 s.underline()
4675 } else {
4676 s
4677 }
4678 } else {
4679 Style::new().fg(self.theme.text_dim)
4680 };
4681 self.styled(format!("[ {label} ]"), style);
4682 }
4683 self.commands.push(Command::EndContainer);
4684 self.last_text_idx = None;
4685
4686 self
4687 }
4688
4689 pub fn button(&mut self, label: impl Into<String>) -> bool {
4694 let focused = self.register_focusable();
4695 let interaction_id = self.interaction_count;
4696 self.interaction_count += 1;
4697 let response = self.response_for(interaction_id);
4698
4699 let mut activated = response.clicked;
4700 if focused {
4701 let mut consumed_indices = Vec::new();
4702 for (i, event) in self.events.iter().enumerate() {
4703 if let Event::Key(key) = event {
4704 if key.kind != KeyEventKind::Press {
4705 continue;
4706 }
4707 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
4708 activated = true;
4709 consumed_indices.push(i);
4710 }
4711 }
4712 }
4713
4714 for index in consumed_indices {
4715 self.consumed[index] = true;
4716 }
4717 }
4718
4719 let hovered = response.hovered;
4720 let style = if focused {
4721 Style::new().fg(self.theme.primary).bold()
4722 } else if hovered {
4723 Style::new().fg(self.theme.accent)
4724 } else {
4725 Style::new().fg(self.theme.text)
4726 };
4727 let hover_bg = if hovered || focused {
4728 Some(self.theme.surface_hover)
4729 } else {
4730 None
4731 };
4732
4733 self.commands.push(Command::BeginContainer {
4734 direction: Direction::Row,
4735 gap: 0,
4736 align: Align::Start,
4737 justify: Justify::Start,
4738 border: None,
4739 border_sides: BorderSides::all(),
4740 border_style: Style::new().fg(self.theme.border),
4741 bg_color: hover_bg,
4742 padding: Padding::default(),
4743 margin: Margin::default(),
4744 constraints: Constraints::default(),
4745 title: None,
4746 grow: 0,
4747 group_name: None,
4748 });
4749 self.styled(format!("[ {} ]", label.into()), style);
4750 self.commands.push(Command::EndContainer);
4751 self.last_text_idx = None;
4752
4753 activated
4754 }
4755
4756 pub fn button_with(&mut self, label: impl Into<String>, variant: ButtonVariant) -> bool {
4761 let focused = self.register_focusable();
4762 let interaction_id = self.interaction_count;
4763 self.interaction_count += 1;
4764 let response = self.response_for(interaction_id);
4765
4766 let mut activated = response.clicked;
4767 if focused {
4768 let mut consumed_indices = Vec::new();
4769 for (i, event) in self.events.iter().enumerate() {
4770 if let Event::Key(key) = event {
4771 if key.kind != KeyEventKind::Press {
4772 continue;
4773 }
4774 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
4775 activated = true;
4776 consumed_indices.push(i);
4777 }
4778 }
4779 }
4780 for index in consumed_indices {
4781 self.consumed[index] = true;
4782 }
4783 }
4784
4785 let label = label.into();
4786 let hover_bg = if response.hovered || focused {
4787 Some(self.theme.surface_hover)
4788 } else {
4789 None
4790 };
4791 let (text, style, bg_color, border) = match variant {
4792 ButtonVariant::Default => {
4793 let style = if focused {
4794 Style::new().fg(self.theme.primary).bold()
4795 } else if response.hovered {
4796 Style::new().fg(self.theme.accent)
4797 } else {
4798 Style::new().fg(self.theme.text)
4799 };
4800 (format!("[ {label} ]"), style, hover_bg, None)
4801 }
4802 ButtonVariant::Primary => {
4803 let style = if focused {
4804 Style::new().fg(self.theme.bg).bg(self.theme.primary).bold()
4805 } else if response.hovered {
4806 Style::new().fg(self.theme.bg).bg(self.theme.accent)
4807 } else {
4808 Style::new().fg(self.theme.bg).bg(self.theme.primary)
4809 };
4810 (format!(" {label} "), style, hover_bg, None)
4811 }
4812 ButtonVariant::Danger => {
4813 let style = if focused {
4814 Style::new().fg(self.theme.bg).bg(self.theme.error).bold()
4815 } else if response.hovered {
4816 Style::new().fg(self.theme.bg).bg(self.theme.warning)
4817 } else {
4818 Style::new().fg(self.theme.bg).bg(self.theme.error)
4819 };
4820 (format!(" {label} "), style, hover_bg, None)
4821 }
4822 ButtonVariant::Outline => {
4823 let border_color = if focused {
4824 self.theme.primary
4825 } else if response.hovered {
4826 self.theme.accent
4827 } else {
4828 self.theme.border
4829 };
4830 let style = if focused {
4831 Style::new().fg(self.theme.primary).bold()
4832 } else if response.hovered {
4833 Style::new().fg(self.theme.accent)
4834 } else {
4835 Style::new().fg(self.theme.text)
4836 };
4837 (
4838 format!(" {label} "),
4839 style,
4840 hover_bg,
4841 Some((Border::Rounded, Style::new().fg(border_color))),
4842 )
4843 }
4844 };
4845
4846 let (btn_border, btn_border_style) = border.unwrap_or((Border::Rounded, Style::new()));
4847 self.commands.push(Command::BeginContainer {
4848 direction: Direction::Row,
4849 gap: 0,
4850 align: Align::Center,
4851 justify: Justify::Center,
4852 border: if border.is_some() {
4853 Some(btn_border)
4854 } else {
4855 None
4856 },
4857 border_sides: BorderSides::all(),
4858 border_style: btn_border_style,
4859 bg_color,
4860 padding: Padding::default(),
4861 margin: Margin::default(),
4862 constraints: Constraints::default(),
4863 title: None,
4864 grow: 0,
4865 group_name: None,
4866 });
4867 self.styled(text, style);
4868 self.commands.push(Command::EndContainer);
4869 self.last_text_idx = None;
4870
4871 activated
4872 }
4873
4874 pub fn checkbox(&mut self, label: impl Into<String>, checked: &mut bool) -> &mut Self {
4879 let focused = self.register_focusable();
4880 let interaction_id = self.interaction_count;
4881 self.interaction_count += 1;
4882 let response = self.response_for(interaction_id);
4883 let mut should_toggle = response.clicked;
4884
4885 if focused {
4886 let mut consumed_indices = Vec::new();
4887 for (i, event) in self.events.iter().enumerate() {
4888 if let Event::Key(key) = event {
4889 if key.kind != KeyEventKind::Press {
4890 continue;
4891 }
4892 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
4893 should_toggle = true;
4894 consumed_indices.push(i);
4895 }
4896 }
4897 }
4898
4899 for index in consumed_indices {
4900 self.consumed[index] = true;
4901 }
4902 }
4903
4904 if should_toggle {
4905 *checked = !*checked;
4906 }
4907
4908 let hover_bg = if response.hovered || focused {
4909 Some(self.theme.surface_hover)
4910 } else {
4911 None
4912 };
4913 self.commands.push(Command::BeginContainer {
4914 direction: Direction::Row,
4915 gap: 1,
4916 align: Align::Start,
4917 justify: Justify::Start,
4918 border: None,
4919 border_sides: BorderSides::all(),
4920 border_style: Style::new().fg(self.theme.border),
4921 bg_color: hover_bg,
4922 padding: Padding::default(),
4923 margin: Margin::default(),
4924 constraints: Constraints::default(),
4925 title: None,
4926 grow: 0,
4927 group_name: None,
4928 });
4929 let marker_style = if *checked {
4930 Style::new().fg(self.theme.success)
4931 } else {
4932 Style::new().fg(self.theme.text_dim)
4933 };
4934 let marker = if *checked { "[x]" } else { "[ ]" };
4935 let label_text = label.into();
4936 if focused {
4937 self.styled(format!("▸ {marker}"), marker_style.bold());
4938 self.styled(label_text, Style::new().fg(self.theme.text).bold());
4939 } else {
4940 self.styled(marker, marker_style);
4941 self.styled(label_text, Style::new().fg(self.theme.text));
4942 }
4943 self.commands.push(Command::EndContainer);
4944 self.last_text_idx = None;
4945
4946 self
4947 }
4948
4949 pub fn toggle(&mut self, label: impl Into<String>, on: &mut bool) -> &mut Self {
4955 let focused = self.register_focusable();
4956 let interaction_id = self.interaction_count;
4957 self.interaction_count += 1;
4958 let response = self.response_for(interaction_id);
4959 let mut should_toggle = response.clicked;
4960
4961 if focused {
4962 let mut consumed_indices = Vec::new();
4963 for (i, event) in self.events.iter().enumerate() {
4964 if let Event::Key(key) = event {
4965 if key.kind != KeyEventKind::Press {
4966 continue;
4967 }
4968 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
4969 should_toggle = true;
4970 consumed_indices.push(i);
4971 }
4972 }
4973 }
4974
4975 for index in consumed_indices {
4976 self.consumed[index] = true;
4977 }
4978 }
4979
4980 if should_toggle {
4981 *on = !*on;
4982 }
4983
4984 let hover_bg = if response.hovered || focused {
4985 Some(self.theme.surface_hover)
4986 } else {
4987 None
4988 };
4989 self.commands.push(Command::BeginContainer {
4990 direction: Direction::Row,
4991 gap: 2,
4992 align: Align::Start,
4993 justify: Justify::Start,
4994 border: None,
4995 border_sides: BorderSides::all(),
4996 border_style: Style::new().fg(self.theme.border),
4997 bg_color: hover_bg,
4998 padding: Padding::default(),
4999 margin: Margin::default(),
5000 constraints: Constraints::default(),
5001 title: None,
5002 grow: 0,
5003 group_name: None,
5004 });
5005 let label_text = label.into();
5006 let switch = if *on { "●━━ ON" } else { "━━● OFF" };
5007 let switch_style = if *on {
5008 Style::new().fg(self.theme.success)
5009 } else {
5010 Style::new().fg(self.theme.text_dim)
5011 };
5012 if focused {
5013 self.styled(
5014 format!("▸ {label_text}"),
5015 Style::new().fg(self.theme.text).bold(),
5016 );
5017 self.styled(switch, switch_style.bold());
5018 } else {
5019 self.styled(label_text, Style::new().fg(self.theme.text));
5020 self.styled(switch, switch_style);
5021 }
5022 self.commands.push(Command::EndContainer);
5023 self.last_text_idx = None;
5024
5025 self
5026 }
5027
5028 pub fn select(&mut self, state: &mut SelectState) -> bool {
5034 if state.items.is_empty() {
5035 return false;
5036 }
5037 state.selected = state.selected.min(state.items.len().saturating_sub(1));
5038
5039 let focused = self.register_focusable();
5040 let interaction_id = self.interaction_count;
5041 self.interaction_count += 1;
5042 let response = self.response_for(interaction_id);
5043 let old_selected = state.selected;
5044
5045 if response.clicked {
5046 state.open = !state.open;
5047 if state.open {
5048 state.set_cursor(state.selected);
5049 }
5050 }
5051
5052 if focused {
5053 let mut consumed_indices = Vec::new();
5054 for (i, event) in self.events.iter().enumerate() {
5055 if self.consumed[i] {
5056 continue;
5057 }
5058 if let Event::Key(key) = event {
5059 if key.kind != KeyEventKind::Press {
5060 continue;
5061 }
5062 if state.open {
5063 match key.code {
5064 KeyCode::Up | KeyCode::Char('k') => {
5065 let c = state.cursor();
5066 state.set_cursor(c.saturating_sub(1));
5067 consumed_indices.push(i);
5068 }
5069 KeyCode::Down | KeyCode::Char('j') => {
5070 let c = state.cursor();
5071 state.set_cursor((c + 1).min(state.items.len().saturating_sub(1)));
5072 consumed_indices.push(i);
5073 }
5074 KeyCode::Enter | KeyCode::Char(' ') => {
5075 state.selected = state.cursor();
5076 state.open = false;
5077 consumed_indices.push(i);
5078 }
5079 KeyCode::Esc => {
5080 state.open = false;
5081 consumed_indices.push(i);
5082 }
5083 _ => {}
5084 }
5085 } else if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
5086 state.open = true;
5087 state.set_cursor(state.selected);
5088 consumed_indices.push(i);
5089 }
5090 }
5091 }
5092 for idx in consumed_indices {
5093 self.consumed[idx] = true;
5094 }
5095 }
5096
5097 let changed = state.selected != old_selected;
5098
5099 let border_color = if focused {
5100 self.theme.primary
5101 } else {
5102 self.theme.border
5103 };
5104 let display_text = state
5105 .items
5106 .get(state.selected)
5107 .cloned()
5108 .unwrap_or_else(|| state.placeholder.clone());
5109 let arrow = if state.open { "▲" } else { "▼" };
5110
5111 self.commands.push(Command::BeginContainer {
5112 direction: Direction::Column,
5113 gap: 0,
5114 align: Align::Start,
5115 justify: Justify::Start,
5116 border: None,
5117 border_sides: BorderSides::all(),
5118 border_style: Style::new().fg(self.theme.border),
5119 bg_color: None,
5120 padding: Padding::default(),
5121 margin: Margin::default(),
5122 constraints: Constraints::default(),
5123 title: None,
5124 grow: 0,
5125 group_name: None,
5126 });
5127
5128 self.commands.push(Command::BeginContainer {
5129 direction: Direction::Row,
5130 gap: 1,
5131 align: Align::Start,
5132 justify: Justify::Start,
5133 border: Some(Border::Rounded),
5134 border_sides: BorderSides::all(),
5135 border_style: Style::new().fg(border_color),
5136 bg_color: None,
5137 padding: Padding {
5138 left: 1,
5139 right: 1,
5140 top: 0,
5141 bottom: 0,
5142 },
5143 margin: Margin::default(),
5144 constraints: Constraints::default(),
5145 title: None,
5146 grow: 0,
5147 group_name: None,
5148 });
5149 self.interaction_count += 1;
5150 self.styled(&display_text, Style::new().fg(self.theme.text));
5151 self.styled(arrow, Style::new().fg(self.theme.text_dim));
5152 self.commands.push(Command::EndContainer);
5153 self.last_text_idx = None;
5154
5155 if state.open {
5156 for (idx, item) in state.items.iter().enumerate() {
5157 let is_cursor = idx == state.cursor();
5158 let style = if is_cursor {
5159 Style::new().bold().fg(self.theme.primary)
5160 } else {
5161 Style::new().fg(self.theme.text)
5162 };
5163 let prefix = if is_cursor { "▸ " } else { " " };
5164 self.styled(format!("{prefix}{item}"), style);
5165 }
5166 }
5167
5168 self.commands.push(Command::EndContainer);
5169 self.last_text_idx = None;
5170 changed
5171 }
5172
5173 pub fn radio(&mut self, state: &mut RadioState) -> bool {
5177 if state.items.is_empty() {
5178 return false;
5179 }
5180 state.selected = state.selected.min(state.items.len().saturating_sub(1));
5181 let focused = self.register_focusable();
5182 let old_selected = state.selected;
5183
5184 if focused {
5185 let mut consumed_indices = Vec::new();
5186 for (i, event) in self.events.iter().enumerate() {
5187 if self.consumed[i] {
5188 continue;
5189 }
5190 if let Event::Key(key) = event {
5191 if key.kind != KeyEventKind::Press {
5192 continue;
5193 }
5194 match key.code {
5195 KeyCode::Up | KeyCode::Char('k') => {
5196 state.selected = state.selected.saturating_sub(1);
5197 consumed_indices.push(i);
5198 }
5199 KeyCode::Down | KeyCode::Char('j') => {
5200 state.selected =
5201 (state.selected + 1).min(state.items.len().saturating_sub(1));
5202 consumed_indices.push(i);
5203 }
5204 KeyCode::Enter | KeyCode::Char(' ') => {
5205 consumed_indices.push(i);
5206 }
5207 _ => {}
5208 }
5209 }
5210 }
5211 for idx in consumed_indices {
5212 self.consumed[idx] = true;
5213 }
5214 }
5215
5216 let interaction_id = self.interaction_count;
5217 self.interaction_count += 1;
5218
5219 if let Some(rect) = self.prev_hit_map.get(interaction_id).copied() {
5220 for (i, event) in self.events.iter().enumerate() {
5221 if self.consumed[i] {
5222 continue;
5223 }
5224 if let Event::Mouse(mouse) = event {
5225 if !matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
5226 continue;
5227 }
5228 let in_bounds = mouse.x >= rect.x
5229 && mouse.x < rect.right()
5230 && mouse.y >= rect.y
5231 && mouse.y < rect.bottom();
5232 if !in_bounds {
5233 continue;
5234 }
5235 let clicked_idx = (mouse.y - rect.y) as usize;
5236 if clicked_idx < state.items.len() {
5237 state.selected = clicked_idx;
5238 self.consumed[i] = true;
5239 }
5240 }
5241 }
5242 }
5243
5244 self.commands.push(Command::BeginContainer {
5245 direction: Direction::Column,
5246 gap: 0,
5247 align: Align::Start,
5248 justify: Justify::Start,
5249 border: None,
5250 border_sides: BorderSides::all(),
5251 border_style: Style::new().fg(self.theme.border),
5252 bg_color: None,
5253 padding: Padding::default(),
5254 margin: Margin::default(),
5255 constraints: Constraints::default(),
5256 title: None,
5257 grow: 0,
5258 group_name: None,
5259 });
5260
5261 for (idx, item) in state.items.iter().enumerate() {
5262 let is_selected = idx == state.selected;
5263 let marker = if is_selected { "●" } else { "○" };
5264 let style = if is_selected {
5265 if focused {
5266 Style::new().bold().fg(self.theme.primary)
5267 } else {
5268 Style::new().fg(self.theme.primary)
5269 }
5270 } else {
5271 Style::new().fg(self.theme.text)
5272 };
5273 let prefix = if focused && idx == state.selected {
5274 "▸ "
5275 } else {
5276 " "
5277 };
5278 self.styled(format!("{prefix}{marker} {item}"), style);
5279 }
5280
5281 self.commands.push(Command::EndContainer);
5282 self.last_text_idx = None;
5283 state.selected != old_selected
5284 }
5285
5286 pub fn multi_select(&mut self, state: &mut MultiSelectState) -> &mut Self {
5290 if state.items.is_empty() {
5291 return self;
5292 }
5293 state.cursor = state.cursor.min(state.items.len().saturating_sub(1));
5294 let focused = self.register_focusable();
5295
5296 if focused {
5297 let mut consumed_indices = Vec::new();
5298 for (i, event) in self.events.iter().enumerate() {
5299 if self.consumed[i] {
5300 continue;
5301 }
5302 if let Event::Key(key) = event {
5303 if key.kind != KeyEventKind::Press {
5304 continue;
5305 }
5306 match key.code {
5307 KeyCode::Up | KeyCode::Char('k') => {
5308 state.cursor = state.cursor.saturating_sub(1);
5309 consumed_indices.push(i);
5310 }
5311 KeyCode::Down | KeyCode::Char('j') => {
5312 state.cursor =
5313 (state.cursor + 1).min(state.items.len().saturating_sub(1));
5314 consumed_indices.push(i);
5315 }
5316 KeyCode::Char(' ') | KeyCode::Enter => {
5317 state.toggle(state.cursor);
5318 consumed_indices.push(i);
5319 }
5320 _ => {}
5321 }
5322 }
5323 }
5324 for idx in consumed_indices {
5325 self.consumed[idx] = true;
5326 }
5327 }
5328
5329 let interaction_id = self.interaction_count;
5330 self.interaction_count += 1;
5331
5332 if let Some(rect) = self.prev_hit_map.get(interaction_id).copied() {
5333 for (i, event) in self.events.iter().enumerate() {
5334 if self.consumed[i] {
5335 continue;
5336 }
5337 if let Event::Mouse(mouse) = event {
5338 if !matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
5339 continue;
5340 }
5341 let in_bounds = mouse.x >= rect.x
5342 && mouse.x < rect.right()
5343 && mouse.y >= rect.y
5344 && mouse.y < rect.bottom();
5345 if !in_bounds {
5346 continue;
5347 }
5348 let clicked_idx = (mouse.y - rect.y) as usize;
5349 if clicked_idx < state.items.len() {
5350 state.toggle(clicked_idx);
5351 state.cursor = clicked_idx;
5352 self.consumed[i] = true;
5353 }
5354 }
5355 }
5356 }
5357
5358 self.commands.push(Command::BeginContainer {
5359 direction: Direction::Column,
5360 gap: 0,
5361 align: Align::Start,
5362 justify: Justify::Start,
5363 border: None,
5364 border_sides: BorderSides::all(),
5365 border_style: Style::new().fg(self.theme.border),
5366 bg_color: None,
5367 padding: Padding::default(),
5368 margin: Margin::default(),
5369 constraints: Constraints::default(),
5370 title: None,
5371 grow: 0,
5372 group_name: None,
5373 });
5374
5375 for (idx, item) in state.items.iter().enumerate() {
5376 let checked = state.selected.contains(&idx);
5377 let marker = if checked { "[x]" } else { "[ ]" };
5378 let is_cursor = idx == state.cursor;
5379 let style = if is_cursor && focused {
5380 Style::new().bold().fg(self.theme.primary)
5381 } else if checked {
5382 Style::new().fg(self.theme.success)
5383 } else {
5384 Style::new().fg(self.theme.text)
5385 };
5386 let prefix = if is_cursor && focused { "▸ " } else { " " };
5387 self.styled(format!("{prefix}{marker} {item}"), style);
5388 }
5389
5390 self.commands.push(Command::EndContainer);
5391 self.last_text_idx = None;
5392 self
5393 }
5394
5395 pub fn tree(&mut self, state: &mut TreeState) -> &mut Self {
5399 let entries = state.flatten();
5400 if entries.is_empty() {
5401 return self;
5402 }
5403 state.selected = state.selected.min(entries.len().saturating_sub(1));
5404 let focused = self.register_focusable();
5405
5406 if focused {
5407 let mut consumed_indices = Vec::new();
5408 for (i, event) in self.events.iter().enumerate() {
5409 if self.consumed[i] {
5410 continue;
5411 }
5412 if let Event::Key(key) = event {
5413 if key.kind != KeyEventKind::Press {
5414 continue;
5415 }
5416 match key.code {
5417 KeyCode::Up | KeyCode::Char('k') => {
5418 state.selected = state.selected.saturating_sub(1);
5419 consumed_indices.push(i);
5420 }
5421 KeyCode::Down | KeyCode::Char('j') => {
5422 let max = state.flatten().len().saturating_sub(1);
5423 state.selected = (state.selected + 1).min(max);
5424 consumed_indices.push(i);
5425 }
5426 KeyCode::Right | KeyCode::Enter | KeyCode::Char(' ') => {
5427 state.toggle_at(state.selected);
5428 consumed_indices.push(i);
5429 }
5430 KeyCode::Left => {
5431 let entry = &entries[state.selected.min(entries.len() - 1)];
5432 if entry.expanded {
5433 state.toggle_at(state.selected);
5434 }
5435 consumed_indices.push(i);
5436 }
5437 _ => {}
5438 }
5439 }
5440 }
5441 for idx in consumed_indices {
5442 self.consumed[idx] = true;
5443 }
5444 }
5445
5446 self.interaction_count += 1;
5447 self.commands.push(Command::BeginContainer {
5448 direction: Direction::Column,
5449 gap: 0,
5450 align: Align::Start,
5451 justify: Justify::Start,
5452 border: None,
5453 border_sides: BorderSides::all(),
5454 border_style: Style::new().fg(self.theme.border),
5455 bg_color: None,
5456 padding: Padding::default(),
5457 margin: Margin::default(),
5458 constraints: Constraints::default(),
5459 title: None,
5460 grow: 0,
5461 group_name: None,
5462 });
5463
5464 let entries = state.flatten();
5465 for (idx, entry) in entries.iter().enumerate() {
5466 let indent = " ".repeat(entry.depth);
5467 let icon = if entry.is_leaf {
5468 " "
5469 } else if entry.expanded {
5470 "▾ "
5471 } else {
5472 "▸ "
5473 };
5474 let is_selected = idx == state.selected;
5475 let style = if is_selected && focused {
5476 Style::new().bold().fg(self.theme.primary)
5477 } else if is_selected {
5478 Style::new().fg(self.theme.primary)
5479 } else {
5480 Style::new().fg(self.theme.text)
5481 };
5482 let cursor = if is_selected && focused { "▸" } else { " " };
5483 self.styled(format!("{cursor}{indent}{icon}{}", entry.label), style);
5484 }
5485
5486 self.commands.push(Command::EndContainer);
5487 self.last_text_idx = None;
5488 self
5489 }
5490
5491 pub fn virtual_list(
5498 &mut self,
5499 state: &mut ListState,
5500 visible_height: usize,
5501 f: impl Fn(&mut Context, usize),
5502 ) -> &mut Self {
5503 if state.items.is_empty() {
5504 return self;
5505 }
5506 state.selected = state.selected.min(state.items.len().saturating_sub(1));
5507 let focused = self.register_focusable();
5508
5509 if focused {
5510 let mut consumed_indices = Vec::new();
5511 for (i, event) in self.events.iter().enumerate() {
5512 if self.consumed[i] {
5513 continue;
5514 }
5515 if let Event::Key(key) = event {
5516 if key.kind != KeyEventKind::Press {
5517 continue;
5518 }
5519 match key.code {
5520 KeyCode::Up | KeyCode::Char('k') => {
5521 state.selected = state.selected.saturating_sub(1);
5522 consumed_indices.push(i);
5523 }
5524 KeyCode::Down | KeyCode::Char('j') => {
5525 state.selected =
5526 (state.selected + 1).min(state.items.len().saturating_sub(1));
5527 consumed_indices.push(i);
5528 }
5529 KeyCode::PageUp => {
5530 state.selected = state.selected.saturating_sub(visible_height);
5531 consumed_indices.push(i);
5532 }
5533 KeyCode::PageDown => {
5534 state.selected = (state.selected + visible_height)
5535 .min(state.items.len().saturating_sub(1));
5536 consumed_indices.push(i);
5537 }
5538 KeyCode::Home => {
5539 state.selected = 0;
5540 consumed_indices.push(i);
5541 }
5542 KeyCode::End => {
5543 state.selected = state.items.len().saturating_sub(1);
5544 consumed_indices.push(i);
5545 }
5546 _ => {}
5547 }
5548 }
5549 }
5550 for idx in consumed_indices {
5551 self.consumed[idx] = true;
5552 }
5553 }
5554
5555 let start = if state.selected >= visible_height {
5556 state.selected - visible_height + 1
5557 } else {
5558 0
5559 };
5560 let end = (start + visible_height).min(state.items.len());
5561
5562 self.interaction_count += 1;
5563 self.commands.push(Command::BeginContainer {
5564 direction: Direction::Column,
5565 gap: 0,
5566 align: Align::Start,
5567 justify: Justify::Start,
5568 border: None,
5569 border_sides: BorderSides::all(),
5570 border_style: Style::new().fg(self.theme.border),
5571 bg_color: None,
5572 padding: Padding::default(),
5573 margin: Margin::default(),
5574 constraints: Constraints::default(),
5575 title: None,
5576 grow: 0,
5577 group_name: None,
5578 });
5579
5580 if start > 0 {
5581 self.styled(
5582 format!(" ↑ {} more", start),
5583 Style::new().fg(self.theme.text_dim).dim(),
5584 );
5585 }
5586
5587 for idx in start..end {
5588 f(self, idx);
5589 }
5590
5591 let remaining = state.items.len().saturating_sub(end);
5592 if remaining > 0 {
5593 self.styled(
5594 format!(" ↓ {} more", remaining),
5595 Style::new().fg(self.theme.text_dim).dim(),
5596 );
5597 }
5598
5599 self.commands.push(Command::EndContainer);
5600 self.last_text_idx = None;
5601 self
5602 }
5603
5604 pub fn command_palette(&mut self, state: &mut CommandPaletteState) -> Option<usize> {
5608 if !state.open {
5609 return None;
5610 }
5611
5612 let filtered = state.filtered_indices();
5613 let sel = state.selected().min(filtered.len().saturating_sub(1));
5614 state.set_selected(sel);
5615
5616 let mut consumed_indices = Vec::new();
5617 let mut result: Option<usize> = None;
5618
5619 for (i, event) in self.events.iter().enumerate() {
5620 if self.consumed[i] {
5621 continue;
5622 }
5623 if let Event::Key(key) = event {
5624 if key.kind != KeyEventKind::Press {
5625 continue;
5626 }
5627 match key.code {
5628 KeyCode::Esc => {
5629 state.open = false;
5630 consumed_indices.push(i);
5631 }
5632 KeyCode::Up => {
5633 let s = state.selected();
5634 state.set_selected(s.saturating_sub(1));
5635 consumed_indices.push(i);
5636 }
5637 KeyCode::Down => {
5638 let s = state.selected();
5639 state.set_selected((s + 1).min(filtered.len().saturating_sub(1)));
5640 consumed_indices.push(i);
5641 }
5642 KeyCode::Enter => {
5643 if let Some(&cmd_idx) = filtered.get(state.selected()) {
5644 result = Some(cmd_idx);
5645 state.open = false;
5646 }
5647 consumed_indices.push(i);
5648 }
5649 KeyCode::Backspace => {
5650 if state.cursor > 0 {
5651 let byte_idx = byte_index_for_char(&state.input, state.cursor - 1);
5652 let end_idx = byte_index_for_char(&state.input, state.cursor);
5653 state.input.replace_range(byte_idx..end_idx, "");
5654 state.cursor -= 1;
5655 state.set_selected(0);
5656 }
5657 consumed_indices.push(i);
5658 }
5659 KeyCode::Char(ch) => {
5660 let byte_idx = byte_index_for_char(&state.input, state.cursor);
5661 state.input.insert(byte_idx, ch);
5662 state.cursor += 1;
5663 state.set_selected(0);
5664 consumed_indices.push(i);
5665 }
5666 _ => {}
5667 }
5668 }
5669 }
5670 for idx in consumed_indices {
5671 self.consumed[idx] = true;
5672 }
5673
5674 let filtered = state.filtered_indices();
5675
5676 self.modal(|ui| {
5677 let primary = ui.theme.primary;
5678 ui.container()
5679 .border(Border::Rounded)
5680 .border_style(Style::new().fg(primary))
5681 .pad(1)
5682 .max_w(60)
5683 .col(|ui| {
5684 let border_color = ui.theme.primary;
5685 ui.bordered(Border::Rounded)
5686 .border_style(Style::new().fg(border_color))
5687 .px(1)
5688 .col(|ui| {
5689 let display = if state.input.is_empty() {
5690 "Type to search...".to_string()
5691 } else {
5692 state.input.clone()
5693 };
5694 let style = if state.input.is_empty() {
5695 Style::new().dim().fg(ui.theme.text_dim)
5696 } else {
5697 Style::new().fg(ui.theme.text)
5698 };
5699 ui.styled(display, style);
5700 });
5701
5702 for (list_idx, &cmd_idx) in filtered.iter().enumerate() {
5703 let cmd = &state.commands[cmd_idx];
5704 let is_selected = list_idx == state.selected();
5705 let style = if is_selected {
5706 Style::new().bold().fg(ui.theme.primary)
5707 } else {
5708 Style::new().fg(ui.theme.text)
5709 };
5710 let prefix = if is_selected { "▸ " } else { " " };
5711 let shortcut_text = cmd
5712 .shortcut
5713 .as_deref()
5714 .map(|s| format!(" ({s})"))
5715 .unwrap_or_default();
5716 ui.styled(format!("{prefix}{}{shortcut_text}", cmd.label), style);
5717 if is_selected && !cmd.description.is_empty() {
5718 ui.styled(
5719 format!(" {}", cmd.description),
5720 Style::new().dim().fg(ui.theme.text_dim),
5721 );
5722 }
5723 }
5724
5725 if filtered.is_empty() {
5726 ui.styled(
5727 " No matching commands",
5728 Style::new().dim().fg(ui.theme.text_dim),
5729 );
5730 }
5731 });
5732 });
5733
5734 result
5735 }
5736
5737 pub fn markdown(&mut self, text: &str) -> &mut Self {
5744 self.commands.push(Command::BeginContainer {
5745 direction: Direction::Column,
5746 gap: 0,
5747 align: Align::Start,
5748 justify: Justify::Start,
5749 border: None,
5750 border_sides: BorderSides::all(),
5751 border_style: Style::new().fg(self.theme.border),
5752 bg_color: None,
5753 padding: Padding::default(),
5754 margin: Margin::default(),
5755 constraints: Constraints::default(),
5756 title: None,
5757 grow: 0,
5758 group_name: None,
5759 });
5760 self.interaction_count += 1;
5761
5762 let text_style = Style::new().fg(self.theme.text);
5763 let bold_style = Style::new().fg(self.theme.text).bold();
5764 let code_style = Style::new().fg(self.theme.accent);
5765
5766 for line in text.lines() {
5767 let trimmed = line.trim();
5768 if trimmed.is_empty() {
5769 self.text(" ");
5770 continue;
5771 }
5772 if trimmed == "---" || trimmed == "***" || trimmed == "___" {
5773 self.styled("─".repeat(40), Style::new().fg(self.theme.border).dim());
5774 continue;
5775 }
5776 if let Some(heading) = trimmed.strip_prefix("### ") {
5777 self.styled(heading, Style::new().bold().fg(self.theme.accent));
5778 } else if let Some(heading) = trimmed.strip_prefix("## ") {
5779 self.styled(heading, Style::new().bold().fg(self.theme.secondary));
5780 } else if let Some(heading) = trimmed.strip_prefix("# ") {
5781 self.styled(heading, Style::new().bold().fg(self.theme.primary));
5782 } else if let Some(item) = trimmed
5783 .strip_prefix("- ")
5784 .or_else(|| trimmed.strip_prefix("* "))
5785 {
5786 let segs = Self::parse_inline_segments(item, text_style, bold_style, code_style);
5787 if segs.len() <= 1 {
5788 self.styled(format!(" • {item}"), text_style);
5789 } else {
5790 self.line(|ui| {
5791 ui.styled(" • ", text_style);
5792 for (s, st) in segs {
5793 ui.styled(s, st);
5794 }
5795 });
5796 }
5797 } else if trimmed.starts_with(|c: char| c.is_ascii_digit()) && trimmed.contains(". ") {
5798 let parts: Vec<&str> = trimmed.splitn(2, ". ").collect();
5799 if parts.len() == 2 {
5800 let segs =
5801 Self::parse_inline_segments(parts[1], text_style, bold_style, code_style);
5802 if segs.len() <= 1 {
5803 self.styled(format!(" {}. {}", parts[0], parts[1]), text_style);
5804 } else {
5805 self.line(|ui| {
5806 ui.styled(format!(" {}. ", parts[0]), text_style);
5807 for (s, st) in segs {
5808 ui.styled(s, st);
5809 }
5810 });
5811 }
5812 } else {
5813 self.text(trimmed);
5814 }
5815 } else if let Some(code) = trimmed.strip_prefix("```") {
5816 let _ = code;
5817 self.styled(" ┌─code─", Style::new().fg(self.theme.border).dim());
5818 } else {
5819 let segs = Self::parse_inline_segments(trimmed, text_style, bold_style, code_style);
5820 if segs.len() <= 1 {
5821 self.styled(trimmed, text_style);
5822 } else {
5823 self.line(|ui| {
5824 for (s, st) in segs {
5825 ui.styled(s, st);
5826 }
5827 });
5828 }
5829 }
5830 }
5831
5832 self.commands.push(Command::EndContainer);
5833 self.last_text_idx = None;
5834 self
5835 }
5836
5837 fn parse_inline_segments(
5838 text: &str,
5839 base: Style,
5840 bold: Style,
5841 code: Style,
5842 ) -> Vec<(String, Style)> {
5843 let mut segments: Vec<(String, Style)> = Vec::new();
5844 let mut current = String::new();
5845 let chars: Vec<char> = text.chars().collect();
5846 let mut i = 0;
5847 while i < chars.len() {
5848 if i + 1 < chars.len() && chars[i] == '*' && chars[i + 1] == '*' {
5849 if let Some(end) = text[i + 2..].find("**") {
5850 if !current.is_empty() {
5851 segments.push((std::mem::take(&mut current), base));
5852 }
5853 segments.push((text[i + 2..i + 2 + end].to_string(), bold));
5854 i += 4 + end;
5855 continue;
5856 }
5857 }
5858 if chars[i] == '*'
5859 && (i + 1 >= chars.len() || chars[i + 1] != '*')
5860 && (i == 0 || chars[i - 1] != '*')
5861 {
5862 if let Some(end) = text[i + 1..].find('*') {
5863 if !current.is_empty() {
5864 segments.push((std::mem::take(&mut current), base));
5865 }
5866 segments.push((text[i + 1..i + 1 + end].to_string(), base.italic()));
5867 i += 2 + end;
5868 continue;
5869 }
5870 }
5871 if chars[i] == '`' {
5872 if let Some(end) = text[i + 1..].find('`') {
5873 if !current.is_empty() {
5874 segments.push((std::mem::take(&mut current), base));
5875 }
5876 segments.push((text[i + 1..i + 1 + end].to_string(), code));
5877 i += 2 + end;
5878 continue;
5879 }
5880 }
5881 current.push(chars[i]);
5882 i += 1;
5883 }
5884 if !current.is_empty() {
5885 segments.push((current, base));
5886 }
5887 segments
5888 }
5889
5890 pub fn key_seq(&self, seq: &str) -> bool {
5897 if seq.is_empty() {
5898 return false;
5899 }
5900 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
5901 return false;
5902 }
5903 let target: Vec<char> = seq.chars().collect();
5904 let mut matched = 0;
5905 for (i, event) in self.events.iter().enumerate() {
5906 if self.consumed[i] {
5907 continue;
5908 }
5909 if let Event::Key(key) = event {
5910 if key.kind != KeyEventKind::Press {
5911 continue;
5912 }
5913 if let KeyCode::Char(c) = key.code {
5914 if c == target[matched] {
5915 matched += 1;
5916 if matched == target.len() {
5917 return true;
5918 }
5919 } else {
5920 matched = 0;
5921 if c == target[0] {
5922 matched = 1;
5923 }
5924 }
5925 }
5926 }
5927 }
5928 false
5929 }
5930
5931 pub fn separator(&mut self) -> &mut Self {
5936 self.commands.push(Command::Text {
5937 content: "─".repeat(200),
5938 style: Style::new().fg(self.theme.border).dim(),
5939 grow: 0,
5940 align: Align::Start,
5941 wrap: false,
5942 margin: Margin::default(),
5943 constraints: Constraints::default(),
5944 });
5945 self.last_text_idx = Some(self.commands.len() - 1);
5946 self
5947 }
5948
5949 pub fn help(&mut self, bindings: &[(&str, &str)]) -> &mut Self {
5955 if bindings.is_empty() {
5956 return self;
5957 }
5958
5959 self.interaction_count += 1;
5960 self.commands.push(Command::BeginContainer {
5961 direction: Direction::Row,
5962 gap: 2,
5963 align: Align::Start,
5964 justify: Justify::Start,
5965 border: None,
5966 border_sides: BorderSides::all(),
5967 border_style: Style::new().fg(self.theme.border),
5968 bg_color: None,
5969 padding: Padding::default(),
5970 margin: Margin::default(),
5971 constraints: Constraints::default(),
5972 title: None,
5973 grow: 0,
5974 group_name: None,
5975 });
5976 for (idx, (key, action)) in bindings.iter().enumerate() {
5977 if idx > 0 {
5978 self.styled("·", Style::new().fg(self.theme.text_dim));
5979 }
5980 self.styled(*key, Style::new().bold().fg(self.theme.primary));
5981 self.styled(*action, Style::new().fg(self.theme.text_dim));
5982 }
5983 self.commands.push(Command::EndContainer);
5984 self.last_text_idx = None;
5985
5986 self
5987 }
5988
5989 pub fn key(&self, c: char) -> bool {
5995 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
5996 return false;
5997 }
5998 self.events.iter().enumerate().any(|(i, e)| {
5999 !self.consumed[i]
6000 && matches!(e, Event::Key(k) if k.kind == KeyEventKind::Press && k.code == KeyCode::Char(c))
6001 })
6002 }
6003
6004 pub fn key_code(&self, code: KeyCode) -> bool {
6008 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6009 return false;
6010 }
6011 self.events.iter().enumerate().any(|(i, e)| {
6012 !self.consumed[i]
6013 && matches!(e, Event::Key(k) if k.kind == KeyEventKind::Press && k.code == code)
6014 })
6015 }
6016
6017 pub fn key_release(&self, c: char) -> bool {
6021 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6022 return false;
6023 }
6024 self.events.iter().enumerate().any(|(i, e)| {
6025 !self.consumed[i]
6026 && matches!(e, Event::Key(k) if k.kind == KeyEventKind::Release && k.code == KeyCode::Char(c))
6027 })
6028 }
6029
6030 pub fn key_code_release(&self, code: KeyCode) -> bool {
6034 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6035 return false;
6036 }
6037 self.events.iter().enumerate().any(|(i, e)| {
6038 !self.consumed[i]
6039 && matches!(e, Event::Key(k) if k.kind == KeyEventKind::Release && k.code == code)
6040 })
6041 }
6042
6043 pub fn key_mod(&self, c: char, modifiers: KeyModifiers) -> bool {
6047 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6048 return false;
6049 }
6050 self.events.iter().enumerate().any(|(i, e)| {
6051 !self.consumed[i]
6052 && matches!(e, Event::Key(k) if k.kind == KeyEventKind::Press && k.code == KeyCode::Char(c) && k.modifiers.contains(modifiers))
6053 })
6054 }
6055
6056 pub fn mouse_down(&self) -> Option<(u32, u32)> {
6060 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6061 return None;
6062 }
6063 self.events.iter().enumerate().find_map(|(i, event)| {
6064 if self.consumed[i] {
6065 return None;
6066 }
6067 if let Event::Mouse(mouse) = event {
6068 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
6069 return Some((mouse.x, mouse.y));
6070 }
6071 }
6072 None
6073 })
6074 }
6075
6076 pub fn mouse_pos(&self) -> Option<(u32, u32)> {
6081 self.mouse_pos
6082 }
6083
6084 pub fn paste(&self) -> Option<&str> {
6086 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6087 return None;
6088 }
6089 self.events.iter().enumerate().find_map(|(i, event)| {
6090 if self.consumed[i] {
6091 return None;
6092 }
6093 if let Event::Paste(ref text) = event {
6094 return Some(text.as_str());
6095 }
6096 None
6097 })
6098 }
6099
6100 pub fn scroll_up(&self) -> bool {
6102 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6103 return false;
6104 }
6105 self.events.iter().enumerate().any(|(i, event)| {
6106 !self.consumed[i]
6107 && matches!(event, Event::Mouse(mouse) if matches!(mouse.kind, MouseKind::ScrollUp))
6108 })
6109 }
6110
6111 pub fn scroll_down(&self) -> bool {
6113 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
6114 return false;
6115 }
6116 self.events.iter().enumerate().any(|(i, event)| {
6117 !self.consumed[i]
6118 && matches!(event, Event::Mouse(mouse) if matches!(mouse.kind, MouseKind::ScrollDown))
6119 })
6120 }
6121
6122 pub fn quit(&mut self) {
6124 self.should_quit = true;
6125 }
6126
6127 pub fn copy_to_clipboard(&mut self, text: impl Into<String>) {
6135 self.clipboard_text = Some(text.into());
6136 }
6137
6138 pub fn theme(&self) -> &Theme {
6140 &self.theme
6141 }
6142
6143 pub fn set_theme(&mut self, theme: Theme) {
6147 self.theme = theme;
6148 }
6149
6150 pub fn is_dark_mode(&self) -> bool {
6152 self.dark_mode
6153 }
6154
6155 pub fn set_dark_mode(&mut self, dark: bool) {
6157 self.dark_mode = dark;
6158 }
6159
6160 pub fn width(&self) -> u32 {
6164 self.area_width
6165 }
6166
6167 pub fn breakpoint(&self) -> Breakpoint {
6191 let w = self.area_width;
6192 if w < 40 {
6193 Breakpoint::Xs
6194 } else if w < 80 {
6195 Breakpoint::Sm
6196 } else if w < 120 {
6197 Breakpoint::Md
6198 } else if w < 160 {
6199 Breakpoint::Lg
6200 } else {
6201 Breakpoint::Xl
6202 }
6203 }
6204
6205 pub fn height(&self) -> u32 {
6207 self.area_height
6208 }
6209
6210 pub fn tick(&self) -> u64 {
6215 self.tick
6216 }
6217
6218 pub fn debug_enabled(&self) -> bool {
6222 self.debug
6223 }
6224}
6225
6226#[inline]
6227fn byte_index_for_char(value: &str, char_index: usize) -> usize {
6228 if char_index == 0 {
6229 return 0;
6230 }
6231 value
6232 .char_indices()
6233 .nth(char_index)
6234 .map_or(value.len(), |(idx, _)| idx)
6235}
6236
6237fn format_token_count(count: usize) -> String {
6238 if count >= 1_000_000 {
6239 format!("{:.1}M", count as f64 / 1_000_000.0)
6240 } else if count >= 1_000 {
6241 format!("{:.1}k", count as f64 / 1_000.0)
6242 } else {
6243 format!("{count}")
6244 }
6245}
6246
6247fn format_table_row(cells: &[String], widths: &[u32], separator: &str) -> String {
6248 let mut parts: Vec<String> = Vec::new();
6249 for (i, width) in widths.iter().enumerate() {
6250 let cell = cells.get(i).map(String::as_str).unwrap_or("");
6251 let cell_width = UnicodeWidthStr::width(cell) as u32;
6252 let padding = (*width).saturating_sub(cell_width) as usize;
6253 parts.push(format!("{cell}{}", " ".repeat(padding)));
6254 }
6255 parts.join(separator)
6256}
6257
6258fn format_compact_number(value: f64) -> String {
6259 if value.fract().abs() < f64::EPSILON {
6260 return format!("{value:.0}");
6261 }
6262
6263 let mut s = format!("{value:.2}");
6264 while s.contains('.') && s.ends_with('0') {
6265 s.pop();
6266 }
6267 if s.ends_with('.') {
6268 s.pop();
6269 }
6270 s
6271}
6272
6273fn center_text(text: &str, width: usize) -> String {
6274 let text_width = UnicodeWidthStr::width(text);
6275 if text_width >= width {
6276 return text.to_string();
6277 }
6278
6279 let total = width - text_width;
6280 let left = total / 2;
6281 let right = total - left;
6282 format!("{}{}{}", " ".repeat(left), text, " ".repeat(right))
6283}
6284
6285struct TextareaVLine {
6286 logical_row: usize,
6287 char_start: usize,
6288 char_count: usize,
6289}
6290
6291fn textarea_build_visual_lines(lines: &[String], wrap_width: u32) -> Vec<TextareaVLine> {
6292 let mut out = Vec::new();
6293 for (row, line) in lines.iter().enumerate() {
6294 if line.is_empty() || wrap_width == u32::MAX {
6295 out.push(TextareaVLine {
6296 logical_row: row,
6297 char_start: 0,
6298 char_count: line.chars().count(),
6299 });
6300 continue;
6301 }
6302 let mut seg_start = 0usize;
6303 let mut seg_chars = 0usize;
6304 let mut seg_width = 0u32;
6305 for (idx, ch) in line.chars().enumerate() {
6306 let cw = UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
6307 if seg_width + cw > wrap_width && seg_chars > 0 {
6308 out.push(TextareaVLine {
6309 logical_row: row,
6310 char_start: seg_start,
6311 char_count: seg_chars,
6312 });
6313 seg_start = idx;
6314 seg_chars = 0;
6315 seg_width = 0;
6316 }
6317 seg_chars += 1;
6318 seg_width += cw;
6319 }
6320 out.push(TextareaVLine {
6321 logical_row: row,
6322 char_start: seg_start,
6323 char_count: seg_chars,
6324 });
6325 }
6326 out
6327}
6328
6329fn textarea_logical_to_visual(
6330 vlines: &[TextareaVLine],
6331 logical_row: usize,
6332 logical_col: usize,
6333) -> (usize, usize) {
6334 for (i, vl) in vlines.iter().enumerate() {
6335 if vl.logical_row != logical_row {
6336 continue;
6337 }
6338 let seg_end = vl.char_start + vl.char_count;
6339 if logical_col >= vl.char_start && logical_col < seg_end {
6340 return (i, logical_col - vl.char_start);
6341 }
6342 if logical_col == seg_end {
6343 let is_last_seg = vlines
6344 .get(i + 1)
6345 .map_or(true, |next| next.logical_row != logical_row);
6346 if is_last_seg {
6347 return (i, logical_col - vl.char_start);
6348 }
6349 }
6350 }
6351 (vlines.len().saturating_sub(1), 0)
6352}
6353
6354fn textarea_visual_to_logical(
6355 vlines: &[TextareaVLine],
6356 visual_row: usize,
6357 visual_col: usize,
6358) -> (usize, usize) {
6359 if let Some(vl) = vlines.get(visual_row) {
6360 let logical_col = vl.char_start + visual_col.min(vl.char_count);
6361 (vl.logical_row, logical_col)
6362 } else {
6363 (0, 0)
6364 }
6365}
6366
6367fn open_url(url: &str) -> std::io::Result<()> {
6368 #[cfg(target_os = "macos")]
6369 {
6370 std::process::Command::new("open").arg(url).spawn()?;
6371 }
6372 #[cfg(target_os = "linux")]
6373 {
6374 std::process::Command::new("xdg-open").arg(url).spawn()?;
6375 }
6376 #[cfg(target_os = "windows")]
6377 {
6378 std::process::Command::new("cmd")
6379 .args(["/c", "start", "", url])
6380 .spawn()?;
6381 }
6382 Ok(())
6383}