-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.rs
More file actions
384 lines (330 loc) · 12.2 KB
/
renderer.rs
File metadata and controls
384 lines (330 loc) · 12.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
//! Renderer for interactive selection in the input area.
use super::state::{InteractiveItem, InteractiveState};
use cortex_core::style::{CYAN_PRIMARY, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style},
symbols::border::Set as BorderSet,
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph, Widget},
};
/// Custom rounded border set using our Unicode characters.
const ROUNDED_BORDER: BorderSet = BorderSet {
top_left: "╭",
top_right: "╮",
bottom_left: "╰",
bottom_right: "╯",
horizontal_top: "─",
horizontal_bottom: "─",
vertical_left: "│",
vertical_right: "│",
};
/// Widget for rendering the interactive selection list.
pub struct InteractiveWidget<'a> {
state: &'a InteractiveState,
}
impl<'a> InteractiveWidget<'a> {
/// Create a new interactive widget.
pub fn new(state: &'a InteractiveState) -> Self {
Self { state }
}
/// Calculate the required height for this widget.
pub fn required_height(&self) -> u16 {
let items_count = self
.state
.filtered_indices
.len()
.min(self.state.max_visible);
let header_height = 1; // Title
let search_height = if self.state.searchable { 1 } else { 0 };
let hints_height = 1;
let border_height = 2;
(items_count as u16) + header_height + search_height + hints_height + border_height
}
}
impl<'a> Widget for InteractiveWidget<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
// Clear the area first
Clear.render(area, buf);
// Draw border with rounded corners
let block = Block::default()
.borders(Borders::ALL)
.border_set(ROUNDED_BORDER)
.border_style(Style::default().fg(CYAN_PRIMARY))
.title(Span::styled(
format!(" {} ", self.state.title),
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD),
));
let inner = block.inner(area);
block.render(area, buf);
if inner.height < 3 {
return;
}
// Layout: search (optional) + items + hints
let mut constraints = Vec::new();
if self.state.searchable {
constraints.push(Constraint::Length(1)); // Search bar
}
constraints.push(Constraint::Min(1)); // Items
constraints.push(Constraint::Length(1)); // Hints
let chunks = Layout::vertical(constraints).split(inner);
let mut chunk_idx = 0;
// Render search bar if enabled
if self.state.searchable {
let search_area = chunks[chunk_idx];
chunk_idx += 1;
let search_text = if self.state.search_query.is_empty() {
Span::styled("Type to search...", Style::default().fg(TEXT_MUTED))
} else {
Span::styled(
format!("Search: {}_", self.state.search_query),
Style::default().fg(TEXT),
)
};
let search_line = Line::from(vec![
Span::styled(" ", Style::default().fg(TEXT_DIM)),
search_text,
]);
Paragraph::new(search_line).render(search_area, buf);
}
// Render items
let items_area = chunks[chunk_idx];
chunk_idx += 1;
self.render_items(items_area, buf);
// Render hints
let hints_area = chunks[chunk_idx];
self.render_hints(hints_area, buf);
}
}
impl<'a> InteractiveWidget<'a> {
/// Render the list items.
fn render_items(&self, area: Rect, buf: &mut Buffer) {
let visible_items = self.state.visible_items();
let viewport_height = area.height as usize;
// Compute the effective scroll offset to ensure the selected item is visible.
// This handles cases where the actual viewport is smaller than max_visible,
// which can occur in small terminal windows.
let start = if self.state.selected >= self.state.scroll_offset + viewport_height {
// Selected item is below the visible area - scroll down
self.state.selected.saturating_sub(viewport_height - 1)
} else if self.state.selected < self.state.scroll_offset {
// Selected item is above the visible area - scroll up
self.state.selected
} else {
// Selected item is within view - use existing scroll offset
self.state.scroll_offset
};
let end = (start + viewport_height).min(visible_items.len());
for (i, (real_idx, item)) in visible_items
.iter()
.skip(start)
.take(end - start)
.enumerate()
{
let y = area.y + i as u16;
if y >= area.y + area.height {
break;
}
let is_selected = self.state.selected == start + i;
let is_checked = self.state.is_checked(*real_idx);
self.render_item(
Rect::new(area.x, y, area.width, 1),
buf,
item,
is_selected,
is_checked,
);
}
// Show scroll indicators if needed
if start > 0 {
buf.set_string(
area.x + area.width.saturating_sub(3),
area.y,
"▲",
Style::default().fg(TEXT_MUTED),
);
}
if end < visible_items.len() {
buf.set_string(
area.x + area.width.saturating_sub(3),
area.y + area.height.saturating_sub(1),
"▼",
Style::default().fg(TEXT_MUTED),
);
}
}
/// Render a single item.
fn render_item(
&self,
area: Rect,
buf: &mut Buffer,
item: &InteractiveItem,
is_selected: bool,
is_checked: bool,
) {
// No background color - keep it transparent
let fg = if item.disabled {
TEXT_MUTED
} else if is_selected {
CYAN_PRIMARY
} else {
TEXT
};
let mut x = area.x + 1;
// Selection indicator
let indicator = if is_selected { ">" } else { " " };
buf.set_string(
x,
area.y,
indicator,
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD),
);
x += 2;
// Checkbox (multi-select)
if self.state.multi_select {
let checkbox = if is_checked { "[x]" } else { "[ ]" };
let checkbox_style = if is_checked {
Style::default().fg(SUCCESS)
} else {
Style::default().fg(TEXT_DIM)
};
buf.set_string(x, area.y, checkbox, checkbox_style);
x += 4;
}
// Icon
if let Some(icon) = item.icon {
buf.set_string(x, area.y, icon.to_string(), Style::default().fg(fg));
x += 2;
}
// Shortcut - hidden (shortcuts still work via keyboard)
// Label
let label_style = if is_selected {
Style::default().fg(fg).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(fg)
};
let max_label_len = (area.width as usize).saturating_sub((x - area.x) as usize + 2);
let label = if item.label.len() > max_label_len {
format!("{}...", &item.label[..max_label_len.saturating_sub(3)])
} else {
item.label.clone()
};
buf.set_string(x, area.y, &label, label_style);
x += label.len() as u16;
// Current marker
if item.is_current {
let marker = " <- current";
if x + marker.len() as u16 + 2 < area.x + area.width {
buf.set_string(x + 1, area.y, marker, Style::default().fg(SUCCESS));
x += marker.len() as u16 + 1;
}
}
// Description (if room)
if let Some(ref desc) = item.description {
let desc_x = x + 2;
let remaining = (area.x + area.width).saturating_sub(desc_x);
if remaining > 10 {
let desc_text = if desc.len() > remaining as usize {
format!("({}...)", &desc[..remaining as usize - 5])
} else {
format!("({})", desc)
};
buf.set_string(desc_x, area.y, &desc_text, Style::default().fg(TEXT_DIM));
}
}
}
/// Render the key hints at the bottom.
fn render_hints(&self, area: Rect, buf: &mut Buffer) {
let mut hints = vec![("↑↓", "navigate"), ("Enter", "select")];
if self.state.multi_select {
hints.insert(1, ("Space", "toggle"));
}
if self.state.searchable {
hints.push(("Type", "search"));
}
hints.push(("Esc", "cancel"));
// Dark green color for hints
let dark_green = Color::Rgb(0, 100, 0);
let mut spans = Vec::new();
for (i, (key, action)) in hints.iter().enumerate() {
if i > 0 {
spans.push(Span::styled(" ", Style::default()));
}
spans.push(Span::styled(
format!("[{}]", key),
Style::default().fg(dark_green),
));
spans.push(Span::styled(
format!(" {}", action),
Style::default().fg(dark_green),
));
}
let hints_line = Line::from(spans);
Paragraph::new(hints_line).render(area, buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interactive::state::InteractiveAction;
#[test]
fn test_required_height() {
let items = vec![
InteractiveItem::new("1", "Item 1"),
InteractiveItem::new("2", "Item 2"),
InteractiveItem::new("3", "Item 3"),
];
let state = InteractiveState::new("Test", items, InteractiveAction::Custom("test".into()));
let widget = InteractiveWidget::new(&state);
// 3 items + 1 title + 1 hints + 2 border = 7
assert_eq!(widget.required_height(), 7);
}
#[test]
fn test_required_height_with_search() {
let items = vec![
InteractiveItem::new("1", "Item 1"),
InteractiveItem::new("2", "Item 2"),
];
let state = InteractiveState::new("Test", items, InteractiveAction::Custom("test".into()))
.with_search();
let widget = InteractiveWidget::new(&state);
// 2 items + 1 title + 1 search + 1 hints + 2 border = 7
assert_eq!(widget.required_height(), 7);
}
#[test]
fn test_scroll_offset_calculation_small_viewport() {
// Test that scroll offset is computed correctly when viewport is smaller than max_visible.
// This tests the fix for issue #1709 where items couldn't be scrolled to in small terminals.
let items: Vec<InteractiveItem> = (0..20)
.map(|i| InteractiveItem::new(format!("{}", i), format!("Item {}", i)))
.collect();
let mut state =
InteractiveState::new("Test", items, InteractiveAction::Custom("test".into()))
.with_max_visible(25); // max_visible is 25, but viewport will be smaller
// Select the last item (index 19)
for _ in 0..19 {
state.select_next();
}
assert_eq!(state.selected, 19);
// Simulate a small viewport of height 5
let viewport_height: usize = 5;
// Calculate start as the renderer would
let start = if state.selected >= state.scroll_offset + viewport_height {
state.selected.saturating_sub(viewport_height - 1)
} else if state.selected < state.scroll_offset {
state.selected
} else {
state.scroll_offset
};
// With selected=19 and viewport_height=5, start should be 15
// so items 15-19 are visible, including the selected item 19
assert_eq!(start, 15);
assert!(state.selected >= start);
assert!(state.selected < start + viewport_height);
}
}