-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.rs
More file actions
495 lines (427 loc) · 15.5 KB
/
renderer.rs
File metadata and controls
495 lines (427 loc) · 15.5 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
//! Renderer for interactive selection in the input area.
use super::state::{InlineFormState, InteractiveItem, InteractiveState};
use cortex_core::style::{CYAN_PRIMARY, SUCCESS, SURFACE_1, 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 {
// If inline form is active, calculate form height
if let Some(ref form) = self.state.inline_form {
let fields_count = form.fields.len() as u16;
let header_height = 1; // Title
let hints_height = 1;
let border_height = 2;
// Each field takes 2 lines (label + input)
return (fields_count * 2) + header_height + hints_height + border_height;
}
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);
// If inline form is active, render the form instead
if let Some(ref form) = self.state.inline_form {
self.render_form(form, area, buf);
return;
}
// 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 start = self.state.scroll_offset;
let end = (start + area.height as usize).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 (not shown for separators)
let indicator = if is_selected && !item.is_separator {
">"
} 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 - bold for separators (category headers)
let label_style = if item.is_separator {
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD)
} else 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;
// 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);
}
/// Render inline form for configuration within the panel.
fn render_form(&self, form: &InlineFormState, area: Rect, buf: &mut Buffer) {
// Draw border with form title
let block = Block::default()
.borders(Borders::ALL)
.border_set(ROUNDED_BORDER)
.border_style(Style::default().fg(CYAN_PRIMARY))
.title(Span::styled(
format!(" {} ", form.title),
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD),
));
let inner = block.inner(area);
block.render(area, buf);
if inner.height < 3 {
return;
}
// Calculate field layout: each field takes 1 line (label: value)
let fields_count = form.fields.len();
let mut constraints: Vec<Constraint> =
form.fields.iter().map(|_| Constraint::Length(1)).collect();
constraints.push(Constraint::Min(0)); // Spacer
constraints.push(Constraint::Length(1)); // Hints
let chunks = Layout::vertical(constraints).split(inner);
// Render each field
for (i, field) in form.fields.iter().enumerate() {
if i >= chunks.len().saturating_sub(2) {
break;
}
let field_area = chunks[i];
let is_focused = i == form.focused_field;
self.render_form_field(field_area, buf, field, is_focused);
}
// Render form hints
let hints_area = chunks[fields_count + 1];
self.render_form_hints(hints_area, buf);
}
/// Render a single form field.
fn render_form_field(
&self,
area: Rect,
buf: &mut Buffer,
field: &super::state::InlineFormField,
is_focused: bool,
) {
let x = area.x + 1;
// Label
let label_style = if is_focused {
Style::default()
.fg(CYAN_PRIMARY)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(TEXT_DIM)
};
let required_marker = if field.required { "*" } else { "" };
let label = format!("{}{}:", field.label, required_marker);
buf.set_string(x, area.y, &label, label_style);
// Value or placeholder
let value_x = x + label.len() as u16 + 1;
let remaining_width = area.width.saturating_sub(value_x - area.x + 1);
if field.value.is_empty() && !is_focused {
// Show placeholder
let placeholder = if field.placeholder.len() > remaining_width as usize {
format!("{}...", &field.placeholder[..remaining_width as usize - 3])
} else {
field.placeholder.clone()
};
buf.set_string(
value_x,
area.y,
&placeholder,
Style::default().fg(TEXT_MUTED),
);
} else {
// Show value with cursor if focused
let display_value = if field.value.len() > remaining_width as usize - 1 {
format!(
"...{}",
&field.value[field.value.len() - (remaining_width as usize - 4)..]
)
} else {
field.value.clone()
};
let value_style = if is_focused {
Style::default().fg(TEXT).bg(SURFACE_1)
} else {
Style::default().fg(TEXT)
};
// Draw input background if focused
if is_focused {
for xi in value_x..(value_x + remaining_width) {
buf[(xi, area.y)].set_bg(SURFACE_1);
}
}
buf.set_string(value_x, area.y, &display_value, value_style);
// Draw cursor
if is_focused {
let cursor_x = value_x + display_value.len() as u16;
if cursor_x < area.x + area.width - 1 {
buf[(cursor_x, area.y)].set_char('_');
buf[(cursor_x, area.y)].set_fg(CYAN_PRIMARY);
}
}
}
}
/// Render hints for the form.
fn render_form_hints(&self, area: Rect, buf: &mut Buffer) {
let hints = vec![("Tab", "next"), ("Enter", "submit"), ("Esc", "cancel")];
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);
}
}