-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelp_browser.rs
More file actions
1110 lines (991 loc) · 36.2 KB
/
help_browser.rs
File metadata and controls
1110 lines (991 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Help browser widget for displaying documentation.
//!
//! Provides a modal help browser with sidebar navigation and searchable content.
//! Displays keyboard shortcuts, commands, model info, and other documentation.
//!
//! ## Example
//!
//! ```rust,ignore
//! use cortex_tui::widgets::{HelpBrowser, HelpBrowserState};
//!
//! let mut state = HelpBrowserState::new();
//!
//! // Navigate with keyboard
//! state.select_next();
//! state.toggle_focus();
//! state.scroll_down();
//!
//! // Render
//! let widget = HelpBrowser::new(&state);
//! widget.render(area, buf);
//! ```
use cortex_core::style::{
BORDER, BORDER_FOCUS, CYAN_PRIMARY, ELECTRIC_BLUE, SURFACE_1, TEXT, TEXT_DIM, TEXT_MUTED, VOID,
};
use ratatui::prelude::*;
use ratatui::widgets::Widget;
use unicode_segmentation::UnicodeSegmentation;
// ============================================================
// HELP CONTENT TYPES
// ============================================================
/// Content type for help sections.
#[derive(Debug, Clone)]
pub enum HelpContent {
/// Section title (bold heading)
Title(String),
/// Paragraph of text (word-wrapped)
Paragraph(String),
/// Key binding: key -> description
KeyBinding { key: String, description: String },
/// Command: name, description, usage
Command {
name: String,
description: String,
usage: String,
},
/// Bullet list
List(Vec<String>),
/// Code snippet
Code(String),
/// Horizontal separator
Separator,
}
// ============================================================
// HELP SECTION
// ============================================================
/// A documentation section with id, title, and content.
#[derive(Debug, Clone)]
pub struct HelpSection {
/// Unique identifier for navigation
pub id: &'static str,
/// Display title in sidebar
pub title: &'static str,
/// Section content
pub content: Vec<HelpContent>,
}
impl HelpSection {
/// Creates a new help section.
///
/// # Arguments
/// * `id` - Unique section identifier
/// * `title` - Display title for sidebar
pub fn new(id: &'static str, title: &'static str) -> Self {
Self {
id,
title,
content: Vec::new(),
}
}
/// Sets the section content.
///
/// # Arguments
/// * `content` - Vector of help content items
pub fn with_content(mut self, content: Vec<HelpContent>) -> Self {
self.content = content;
self
}
}
// ============================================================
// DEFAULT HELP SECTIONS
// ============================================================
/// Returns the default help sections.
pub fn get_help_sections() -> Vec<HelpSection> {
vec![
HelpSection::new("getting-started", "Getting Started").with_content(vec![
HelpContent::Title("Welcome to Cortex".to_string()),
HelpContent::Paragraph(
"Cortex is an AI-powered coding assistant that helps you write, \
understand, and debug code through natural conversation."
.to_string(),
),
HelpContent::Separator,
HelpContent::Title("Quick Start".to_string()),
HelpContent::List(vec![
"Type a message and press Enter to send".to_string(),
"Use /help to see available commands".to_string(),
"Press ? for keyboard shortcuts".to_string(),
"Use Tab to cycle through UI panels".to_string(),
]),
HelpContent::Separator,
HelpContent::Title("Getting Help".to_string()),
HelpContent::Paragraph(
"Use the sidebar to navigate between help topics. Press Tab to \
switch between the sidebar and content pane."
.to_string(),
),
]),
HelpSection::new("keyboard", "Keyboard Shortcuts").with_content(vec![
HelpContent::Title("Navigation".to_string()),
HelpContent::KeyBinding {
key: "Tab".to_string(),
description: "Cycle focus".to_string(),
},
HelpContent::KeyBinding {
key: "Shift+Tab".to_string(),
description: "Cycle focus (reverse)".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+P".to_string(),
description: "Command palette".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+B".to_string(),
description: "Toggle sidebar".to_string(),
},
HelpContent::KeyBinding {
key: "?".to_string(),
description: "Show help".to_string(),
},
HelpContent::Separator,
HelpContent::Title("Session".to_string()),
HelpContent::KeyBinding {
key: "Ctrl+S".to_string(),
description: "Open sessions".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+N".to_string(),
description: "New session".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+Z".to_string(),
description: "Undo".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+Y".to_string(),
description: "Redo".to_string(),
},
HelpContent::Separator,
HelpContent::Title("Input".to_string()),
HelpContent::KeyBinding {
key: "Enter".to_string(),
description: "Send message".to_string(),
},
HelpContent::KeyBinding {
key: "Shift+Enter".to_string(),
description: "New line".to_string(),
},
HelpContent::KeyBinding {
key: "Up/Down".to_string(),
description: "History navigation".to_string(),
},
HelpContent::Separator,
HelpContent::Title("View".to_string()),
HelpContent::KeyBinding {
key: "j/k".to_string(),
description: "Scroll down/up".to_string(),
},
HelpContent::KeyBinding {
key: "g/G".to_string(),
description: "Go to top/bottom".to_string(),
},
HelpContent::KeyBinding {
key: "Ctrl+U/D".to_string(),
description: "Page up/down".to_string(),
},
]),
HelpSection::new("commands", "Slash Commands").with_content(vec![
HelpContent::Title("General Commands".to_string()),
HelpContent::Command {
name: "/help".to_string(),
description: "Show help".to_string(),
usage: "/help [topic]".to_string(),
},
HelpContent::Command {
name: "/quit".to_string(),
description: "Quit application".to_string(),
usage: "/quit".to_string(),
},
HelpContent::Command {
name: "/settings".to_string(),
description: "Open settings".to_string(),
usage: "/settings".to_string(),
},
HelpContent::Separator,
HelpContent::Title("Session Commands".to_string()),
HelpContent::Command {
name: "/new".to_string(),
description: "New session".to_string(),
usage: "/new".to_string(),
},
HelpContent::Command {
name: "/clear".to_string(),
description: "Clear messages".to_string(),
usage: "/clear".to_string(),
},
HelpContent::Command {
name: "/resume".to_string(),
description: "Resume session".to_string(),
usage: "/resume [id]".to_string(),
},
HelpContent::Command {
name: "/fork".to_string(),
description: "Fork session".to_string(),
usage: "/fork [name]".to_string(),
},
HelpContent::Separator,
HelpContent::Title("Model Commands".to_string()),
HelpContent::Command {
name: "/model".to_string(),
description: "Switch model".to_string(),
usage: "/model <name>".to_string(),
},
HelpContent::Command {
name: "/models".to_string(),
description: "List models".to_string(),
usage: "/models".to_string(),
},
]),
HelpSection::new("models", "Models").with_content(vec![
HelpContent::Title("Available Models".to_string()),
HelpContent::Paragraph(
"Use /models to see available models or /model <name> to switch.".to_string(),
),
HelpContent::Separator,
HelpContent::Title("Anthropic".to_string()),
HelpContent::List(vec![
"claude-sonnet-4-20250514 (default)".to_string(),
"claude-3-5-sonnet".to_string(),
"claude-3-opus".to_string(),
]),
HelpContent::Separator,
HelpContent::Title("OpenAI".to_string()),
HelpContent::List(vec![
"gpt-4o".to_string(),
"gpt-4-turbo".to_string(),
"gpt-3.5-turbo".to_string(),
]),
HelpContent::Separator,
HelpContent::Title("Configuration".to_string()),
HelpContent::Paragraph(
"Models can be configured in your cortex.toml config file or \
via environment variables."
.to_string(),
),
]),
HelpSection::new("tools", "Built-in Tools").with_content(vec![
HelpContent::Title("File Operations".to_string()),
HelpContent::List(vec![
"read - Read file contents".to_string(),
"write - Create or overwrite files".to_string(),
"edit - Make targeted edits".to_string(),
"glob - Find files by pattern".to_string(),
"grep - Search file contents".to_string(),
]),
HelpContent::Separator,
HelpContent::Title("System Operations".to_string()),
HelpContent::List(vec![
"bash - Execute shell commands".to_string(),
"task - Spawn subagent tasks".to_string(),
]),
HelpContent::Separator,
HelpContent::Title("Tool Usage".to_string()),
HelpContent::Paragraph(
"Tools are automatically invoked by the AI based on your requests. \
You can see tool activity in the status bar and inline tool displays."
.to_string(),
),
]),
HelpSection::new("mcp", "MCP Servers").with_content(vec![
HelpContent::Title("Model Context Protocol".to_string()),
HelpContent::Paragraph(
"MCP allows extending Cortex with external tools and context providers. \
Servers can provide additional tools, resources, and prompts."
.to_string(),
),
HelpContent::Separator,
HelpContent::Title("MCP Commands".to_string()),
HelpContent::Command {
name: "/mcp".to_string(),
description: "Open interactive MCP management panel".to_string(),
usage: "/mcp".to_string(),
},
HelpContent::Paragraph(
"The /mcp command opens an interactive panel where you can:\n\
• Add new servers (stdio, HTTP, or from registry)\n\
• View all available tools\n\
• Start, stop, or restart servers\n\
• Configure authentication\n\
• View server logs"
.to_string(),
),
HelpContent::Separator,
HelpContent::Title("Configuration".to_string()),
HelpContent::Paragraph(
"MCP servers are configured in your cortex.toml file under the \
[mcp] section."
.to_string(),
),
]),
HelpSection::new("faq", "FAQ").with_content(vec![
HelpContent::Title("Frequently Asked Questions".to_string()),
HelpContent::Separator,
HelpContent::Title("How do I switch models?".to_string()),
HelpContent::Paragraph(
"Use /model <name> or press Ctrl+M to open the model picker.".to_string(),
),
HelpContent::Separator,
HelpContent::Title("How do I save my session?".to_string()),
HelpContent::Paragraph(
"Sessions are automatically saved. Use /export to export to a file.".to_string(),
),
HelpContent::Separator,
HelpContent::Title("How do I undo changes?".to_string()),
HelpContent::Paragraph(
"Press Ctrl+Z to undo the last action. Cortex maintains a history \
of edits that can be undone."
.to_string(),
),
HelpContent::Separator,
HelpContent::Title("Where are settings stored?".to_string()),
HelpContent::Paragraph(
"Settings are stored in ~/.config/cortex/cortex.toml on Linux/macOS \
or %APPDATA%\\cortex\\cortex.toml on Windows."
.to_string(),
),
]),
]
}
// ============================================================
// HELP FOCUS STATE
// ============================================================
/// Focus state for the help browser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HelpFocus {
/// Sidebar is focused
#[default]
Sidebar,
/// Content pane is focused
Content,
/// Search input is focused
Search,
}
// ============================================================
// HELP BROWSER STATE
// ============================================================
/// State for the help browser widget.
#[derive(Debug, Clone)]
pub struct HelpBrowserState {
/// Available help sections
pub sections: Vec<HelpSection>,
/// Currently selected section index
pub selected_section: usize,
/// Content scroll offset
pub content_scroll: usize,
/// Search query string
pub search_query: String,
/// Whether search mode is active
pub search_mode: bool,
/// Current focus state
pub focus: HelpFocus,
}
impl Default for HelpBrowserState {
fn default() -> Self {
Self::new()
}
}
impl HelpBrowserState {
/// Creates a new help browser state with default sections.
pub fn new() -> Self {
Self {
sections: get_help_sections(),
selected_section: 0,
content_scroll: 0,
search_query: String::new(),
search_mode: false,
focus: HelpFocus::Sidebar,
}
}
/// Opens to a specific topic.
///
/// # Arguments
/// * `topic` - Optional topic id to navigate to
pub fn with_topic(mut self, topic: Option<&str>) -> Self {
if let Some(topic) = topic {
if let Some(idx) = self.sections.iter().position(|s| s.id == topic) {
self.selected_section = idx;
}
}
self
}
/// Selects the previous section with wrap-around.
pub fn select_prev(&mut self) {
if self.sections.is_empty() {
return;
}
if self.selected_section > 0 {
self.selected_section -= 1;
} else {
// Wrap to last item
self.selected_section = self.sections.len() - 1;
}
self.content_scroll = 0;
}
/// Selects the next section with wrap-around.
pub fn select_next(&mut self) {
if self.sections.is_empty() {
return;
}
if self.selected_section < self.sections.len().saturating_sub(1) {
self.selected_section += 1;
} else {
// Wrap to first item
self.selected_section = 0;
}
self.content_scroll = 0;
}
/// Scrolls content up by one line.
pub fn scroll_up(&mut self) {
self.content_scroll = self.content_scroll.saturating_sub(1);
}
/// Scrolls content down by one line.
pub fn scroll_down(&mut self) {
self.content_scroll = self.content_scroll.saturating_add(1);
}
/// Scrolls content up by a page.
///
/// # Arguments
/// * `page_size` - Number of lines in a page
pub fn page_up(&mut self, page_size: usize) {
self.content_scroll = self.content_scroll.saturating_sub(page_size);
}
/// Scrolls content down by a page.
///
/// # Arguments
/// * `page_size` - Number of lines in a page
pub fn page_down(&mut self, page_size: usize) {
self.content_scroll = self.content_scroll.saturating_add(page_size);
}
/// Toggles focus between sidebar and content.
pub fn toggle_focus(&mut self) {
self.focus = match self.focus {
HelpFocus::Sidebar => HelpFocus::Content,
HelpFocus::Content => HelpFocus::Sidebar,
HelpFocus::Search => HelpFocus::Sidebar,
};
}
/// Toggles search mode.
pub fn toggle_search(&mut self) {
self.search_mode = !self.search_mode;
if self.search_mode {
self.focus = HelpFocus::Search;
} else {
self.focus = HelpFocus::Sidebar;
self.search_query.clear();
}
}
/// Returns the currently selected section.
pub fn current_section(&self) -> &HelpSection {
&self.sections[self.selected_section]
}
/// Handles character input for search.
///
/// # Arguments
/// * `c` - Character to add to search query
pub fn search_input(&mut self, c: char) {
if self.search_mode {
self.search_query.push(c);
}
}
/// Handles backspace for search.
/// Uses grapheme-aware deletion for proper Unicode/emoji support.
pub fn search_backspace(&mut self) {
if self.search_mode {
// Pop the last grapheme cluster instead of last char
let graphemes: Vec<&str> = self.search_query.graphemes(true).collect();
if !graphemes.is_empty() {
self.search_query = graphemes[..graphemes.len() - 1].concat();
}
}
}
}
// ============================================================
// STYLED LINE HELPER
// ============================================================
/// A line of text with styling.
struct StyledLine {
text: String,
style: Style,
}
impl StyledLine {
fn new(text: String, style: Style) -> Self {
Self { text, style }
}
}
// ============================================================
// HELP BROWSER WIDGET
// ============================================================
/// Widget for displaying the help browser.
pub struct HelpBrowser<'a> {
state: &'a HelpBrowserState,
}
impl<'a> HelpBrowser<'a> {
/// Creates a new help browser widget.
///
/// # Arguments
/// * `state` - Reference to the help browser state
pub fn new(state: &'a HelpBrowserState) -> Self {
Self { state }
}
/// Renders the background and border.
fn render_background(&self, area: Rect, buf: &mut Buffer) {
// Fill background
for y in area.y..area.y + area.height {
for x in area.x..area.x + area.width {
if let Some(cell) = buf.cell_mut((x, y)) {
cell.set_char(' ').set_bg(VOID);
}
}
}
// Draw border
let border_style = Style::default().fg(BORDER_FOCUS);
// Corners
buf.set_string(area.x, area.y, "+", border_style);
buf.set_string(area.x + area.width - 1, area.y, "+", border_style);
buf.set_string(area.x, area.y + area.height - 1, "+", border_style);
buf.set_string(
area.x + area.width - 1,
area.y + area.height - 1,
"+",
border_style,
);
// Horizontal borders
for x in area.x + 1..area.x + area.width - 1 {
buf.set_string(x, area.y, "-", border_style);
buf.set_string(x, area.y + area.height - 1, "-", border_style);
}
// Vertical borders
for y in area.y + 1..area.y + area.height - 1 {
buf.set_string(area.x, y, "|", border_style);
buf.set_string(area.x + area.width - 1, y, "|", border_style);
}
}
/// Renders the header with title.
fn render_header(&self, area: Rect, buf: &mut Buffer) {
let title = " Help ";
let close = "[X]";
// Title
let title_x = area.x + 2;
buf.set_string(
title_x,
area.y,
title,
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD),
);
// Close button
let close_x = area.x + area.width - close.len() as u16 - 2;
buf.set_string(close_x, area.y, close, Style::default().fg(TEXT_MUTED));
// Separator below header
let sep_y = area.y + 1;
buf.set_string(area.x, sep_y, "+", Style::default().fg(BORDER));
for x in area.x + 1..area.x + area.width - 1 {
buf.set_string(x, sep_y, "-", Style::default().fg(BORDER));
}
buf.set_string(
area.x + area.width - 1,
sep_y,
"+",
Style::default().fg(BORDER),
);
}
/// Renders the sidebar with section navigation.
fn render_sidebar(&self, area: Rect, buf: &mut Buffer) {
let is_focused = self.state.focus == HelpFocus::Sidebar;
for (i, section) in self.state.sections.iter().enumerate() {
let y = area.y + i as u16;
if y >= area.y + area.height {
break;
}
let is_selected = i == self.state.selected_section;
let prefix = if is_selected { "> " } else { " " };
let style = if is_selected && is_focused {
Style::default().fg(VOID).bg(CYAN_PRIMARY)
} else if is_selected {
Style::default().fg(CYAN_PRIMARY)
} else {
Style::default().fg(TEXT_DIM)
};
// Clear line with style background
for x in area.x..area.x + area.width {
if let Some(cell) = buf.cell_mut((x, y)) {
cell.set_char(' ').set_style(style);
}
}
let text = format!("{}{}", prefix, section.title);
let truncated: String = text.chars().take(area.width as usize).collect();
buf.set_string(area.x, y, &truncated, style);
}
}
/// Renders the content pane.
fn render_content(&self, area: Rect, buf: &mut Buffer) {
let section = self.state.current_section();
let mut y = area.y;
let scroll = self.state.content_scroll;
let mut line_idx = 0;
for content in §ion.content {
if y >= area.y + area.height {
break;
}
let lines = self.render_content_item(content, area.width);
for line in lines {
if line_idx >= scroll {
if y >= area.y + area.height {
break;
}
let truncated: String = line.text.chars().take(area.width as usize).collect();
buf.set_string(area.x, y, &truncated, line.style);
y += 1;
}
line_idx += 1;
}
}
}
/// Renders a single content item into styled lines.
fn render_content_item(&self, content: &HelpContent, width: u16) -> Vec<StyledLine> {
match content {
HelpContent::Title(text) => {
vec![StyledLine::new(
text.clone(),
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD),
)]
}
HelpContent::Paragraph(text) => wrap_text(text, width as usize)
.into_iter()
.map(|s| StyledLine::new(s, Style::default().fg(TEXT)))
.collect(),
HelpContent::KeyBinding { key, description } => {
let line = format!("{:<20} {}", key, description);
vec![StyledLine::new(line, Style::default().fg(TEXT_DIM))]
}
HelpContent::Command {
name,
description,
usage,
} => {
vec![
StyledLine::new(
format!("{:<15} {}", name, description),
Style::default().fg(TEXT),
),
StyledLine::new(
format!(" Usage: {}", usage),
Style::default().fg(TEXT_MUTED),
),
]
}
HelpContent::List(items) => items
.iter()
.map(|item| StyledLine::new(format!(" * {}", item), Style::default().fg(TEXT_DIM)))
.collect(),
HelpContent::Code(code) => {
vec![StyledLine::new(
format!(" {}", code),
Style::default().fg(ELECTRIC_BLUE).bg(SURFACE_1),
)]
}
HelpContent::Separator => {
let line = "-".repeat(width as usize);
vec![StyledLine::new(line, Style::default().fg(BORDER))]
}
}
}
/// Renders the footer with key hints.
fn render_footer(&self, area: Rect, buf: &mut Buffer) {
let y = area.y + area.height - 2;
// Separator above footer
buf.set_string(area.x, y, "+", Style::default().fg(BORDER));
for x in area.x + 1..area.x + area.width - 1 {
buf.set_string(x, y, "-", Style::default().fg(BORDER));
}
buf.set_string(area.x + area.width - 1, y, "+", Style::default().fg(BORDER));
// Footer text
let footer_y = area.y + area.height - 1;
let hints = "[/] Search [Tab] Switch pane [Esc] Close";
// Clear footer line
for x in area.x + 1..area.x + area.width - 1 {
if let Some(cell) = buf.cell_mut((x, footer_y)) {
cell.set_char(' ').set_bg(VOID);
}
}
// Center the hints
let hint_x = area.x + (area.width.saturating_sub(hints.len() as u16)) / 2;
buf.set_string(hint_x, footer_y, hints, Style::default().fg(TEXT_MUTED));
}
/// Renders the vertical separator between sidebar and content.
fn render_separator(&self, x: u16, start_y: u16, end_y: u16, buf: &mut Buffer) {
for y in start_y..end_y {
buf.set_string(x, y, "|", Style::default().fg(BORDER));
}
}
}
impl Widget for HelpBrowser<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
if area.width < 20 || area.height < 10 {
return;
}
// Calculate centered modal area
let width = 70.min(area.width.saturating_sub(4));
let height = 30.min(area.height.saturating_sub(4));
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = area.y + (area.height.saturating_sub(height)) / 2;
let help_area = Rect::new(x, y, width, height);
// Render background and border
self.render_background(help_area, buf);
// Render header
self.render_header(help_area, buf);
// Calculate inner areas
let inner_y = help_area.y + 2;
let inner_height = help_area.height.saturating_sub(4);
// Sidebar width (20 chars or 1/3 of width, whichever is smaller)
let sidebar_width = 20.min(width / 3);
let sidebar_area = Rect::new(help_area.x + 1, inner_y, sidebar_width, inner_height);
// Content area
let content_x = help_area.x + sidebar_width + 2;
let content_width = width.saturating_sub(sidebar_width + 3);
let content_area = Rect::new(content_x, inner_y, content_width, inner_height);
// Render sidebar
self.render_sidebar(sidebar_area, buf);
// Render vertical separator
let sep_x = help_area.x + sidebar_width + 1;
self.render_separator(sep_x, inner_y, inner_y + inner_height, buf);
// Render content
self.render_content(content_area, buf);
// Render footer
self.render_footer(help_area, buf);
}
}
// ============================================================
// TEXT WRAPPING UTILITY
// ============================================================
/// Wraps text to fit within a given width.
///
/// # Arguments
/// * `text` - The text to wrap
/// * `width` - Maximum line width
fn wrap_text(text: &str, width: usize) -> Vec<String> {
if width == 0 {
return vec![];
}
let mut lines = Vec::new();
let mut current = String::new();
for word in text.split_whitespace() {
if current.len() + word.len() + 1 > width {
if !current.is_empty() {
lines.push(current);
current = String::new();
}
// Handle words longer than width
if word.len() > width {
let mut remaining = word;
while remaining.len() > width {
lines.push(remaining[..width].to_string());
remaining = &remaining[width..];
}
if !remaining.is_empty() {
current = remaining.to_string();
}
continue;
}
}
if !current.is_empty() {
current.push(' ');
}
current.push_str(word);
}
if !current.is_empty() {
lines.push(current);
}
lines
}
// ============================================================
// TESTS
// ============================================================
#[cfg(test)]
mod tests {
use super::*;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
fn create_test_buffer(width: u16, height: u16) -> Buffer {
Buffer::empty(Rect::new(0, 0, width, height))
}
#[test]
fn test_help_section_new() {
let section = HelpSection::new("test-id", "Test Title");
assert_eq!(section.id, "test-id");
assert_eq!(section.title, "Test Title");
assert!(section.content.is_empty());
}
#[test]
fn test_help_section_with_content() {
let section = HelpSection::new("test", "Test")
.with_content(vec![HelpContent::Title("Hello".to_string())]);
assert_eq!(section.content.len(), 1);
}
#[test]
fn test_help_browser_state_new() {
let state = HelpBrowserState::new();
assert!(!state.sections.is_empty());
assert_eq!(state.selected_section, 0);
assert_eq!(state.content_scroll, 0);
assert!(!state.search_mode);
assert_eq!(state.focus, HelpFocus::Sidebar);
}
#[test]
fn test_help_browser_state_with_topic() {
let state = HelpBrowserState::new().with_topic(Some("keyboard"));
assert_eq!(state.current_section().id, "keyboard");
}
#[test]
fn test_help_browser_state_with_invalid_topic() {
let state = HelpBrowserState::new().with_topic(Some("nonexistent"));
assert_eq!(state.selected_section, 0);
}
#[test]
fn test_select_navigation() {
let mut state = HelpBrowserState::new();
let initial = state.selected_section;
let total_sections = state.sections.len();
state.select_next();
assert_eq!(state.selected_section, initial + 1);
state.select_prev();
assert_eq!(state.selected_section, initial);
// Wrap around to last item when at 0
state.select_prev();
assert_eq!(state.selected_section, total_sections - 1);
}
#[test]
fn test_scroll() {
let mut state = HelpBrowserState::new();
state.scroll_down();
assert_eq!(state.content_scroll, 1);
state.scroll_down();
state.scroll_down();
assert_eq!(state.content_scroll, 3);
state.scroll_up();
assert_eq!(state.content_scroll, 2);
// Can't go below 0
state.content_scroll = 0;
state.scroll_up();
assert_eq!(state.content_scroll, 0);
}
#[test]
fn test_page_scroll() {
let mut state = HelpBrowserState::new();
state.page_down(10);
assert_eq!(state.content_scroll, 10);
state.page_up(5);
assert_eq!(state.content_scroll, 5);
state.page_up(10);
assert_eq!(state.content_scroll, 0);
}
#[test]
fn test_toggle_focus() {
let mut state = HelpBrowserState::new();
assert_eq!(state.focus, HelpFocus::Sidebar);
state.toggle_focus();
assert_eq!(state.focus, HelpFocus::Content);
state.toggle_focus();
assert_eq!(state.focus, HelpFocus::Sidebar);
}
#[test]
fn test_toggle_search() {
let mut state = HelpBrowserState::new();
assert!(!state.search_mode);
state.toggle_search();
assert!(state.search_mode);
assert_eq!(state.focus, HelpFocus::Search);