1use ratatui::style::{Color, Modifier, Style};
22use ratatui::text::{Line, Span};
23
24pub fn code_fence_lang(line: &str) -> Option<String> {
36 let t = line.trim();
37 t.strip_prefix("```")
38 .map(|rest| rest.trim().to_ascii_lowercase())
39}
40
41pub fn is_executable_shell_lang(lang: &str) -> bool {
50 matches!(lang, "bash" | "sh" | "zsh" | "fish")
51}
52
53pub fn extract_last_shell_block(text: &str) -> Option<String> {
70 let mut last: Option<String> = None;
71 let mut current_body: Option<Vec<String>> = None;
72 let mut in_shell = false;
73 for line in text.lines() {
74 if let Some(lang) = code_fence_lang(line) {
75 if let Some(body) = current_body.take() {
76 if in_shell {
77 last = Some(body.join("\n"));
78 }
79 in_shell = false;
80 } else {
81 in_shell = is_executable_shell_lang(&lang);
82 current_body = Some(Vec::new());
83 }
84 } else if let Some(body) = current_body.as_mut() {
85 body.push(line.to_string());
86 }
87 }
88 last
89}
90
91pub fn is_md_table_row(line: &str) -> bool {
98 line.trim_start().starts_with('|')
99}
100
101pub fn is_md_table_separator(line: &str) -> bool {
110 if !is_md_table_row(line) {
111 return false;
112 }
113 let cells = parse_md_table_cells(line);
114 if cells.is_empty() {
115 return false;
116 }
117 let mut saw_dash = false;
118 for c in &cells {
119 for ch in c.chars() {
120 match ch {
121 '-' => saw_dash = true,
122 ':' | ' ' | '\t' => {}
123 _ => return false,
124 }
125 }
126 }
127 saw_dash
128}
129
130pub fn parse_md_table_cells(line: &str) -> Vec<String> {
138 let trimmed = line.trim();
139 let mut parts: Vec<String> = trimmed.split('|').map(|s| s.trim().to_string()).collect();
140 if parts.first().map(|s| s.is_empty()).unwrap_or(false) {
141 parts.remove(0);
142 }
143 if parts.last().map(|s| s.is_empty()).unwrap_or(false) {
144 parts.pop();
145 }
146 parts
147}
148
149pub fn truncate_cell(s: &str, max: usize) -> String {
157 if max == 0 {
158 return String::new();
159 }
160 let count = s.chars().count();
161 if count <= max {
162 return s.to_string();
163 }
164 let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
165 out.push('…');
166 out
167}
168
169pub fn render_markdown_table(
181 header: &[String],
182 body: &[Vec<String>],
183 available_width: usize,
184 indent: &str,
185 body_color: Option<Color>,
186) -> Vec<Line<'static>> {
187 let ncols = header
188 .len()
189 .max(body.iter().map(|r| r.len()).max().unwrap_or(0));
190 if ncols == 0 {
191 return Vec::new();
192 }
193
194 let header_n: Vec<String> = (0..ncols)
195 .map(|i| header.get(i).cloned().unwrap_or_default())
196 .collect();
197 let body_n: Vec<Vec<String>> = body
198 .iter()
199 .map(|r| {
200 (0..ncols)
201 .map(|i| r.get(i).cloned().unwrap_or_default())
202 .collect()
203 })
204 .collect();
205
206 let mut widths: Vec<usize> = (0..ncols)
207 .map(|i| {
208 let mut w = header_n[i].chars().count();
209 for r in &body_n {
210 w = w.max(r[i].chars().count());
211 }
212 w
213 })
214 .collect();
215
216 let indent_w = indent.chars().count();
217 let frame_overhead = 1 + ncols;
218 let padding_per_col = 2;
219 let mut total: usize =
220 indent_w + frame_overhead + widths.iter().map(|w| w + padding_per_col).sum::<usize>();
221
222 let limit = available_width.max(indent_w + frame_overhead + ncols * (padding_per_col + 1));
223 while total > available_width && available_width > 0 {
224 let widest = widths
225 .iter()
226 .enumerate()
227 .filter(|(_, w)| **w > 1)
228 .max_by_key(|(_, w)| **w)
229 .map(|(i, _)| i);
230 match widest {
231 Some(i) => {
232 widths[i] -= 1;
233 total -= 1;
234 }
235 None => break,
236 }
237 }
238 let _ = limit;
239
240 let border_style = Style::default()
241 .fg(Color::DarkGray)
242 .add_modifier(Modifier::DIM);
243 let cell_style = match body_color {
244 Some(c) => Style::default().fg(c),
245 None => Style::default(),
246 };
247
248 let make_border = |left: char, mid: char, right: char| -> String {
249 let mut s = String::new();
250 s.push_str(indent);
251 s.push(left);
252 for (i, w) in widths.iter().enumerate() {
253 for _ in 0..(w + padding_per_col) {
254 s.push('─');
255 }
256 if i + 1 < widths.len() {
257 s.push(mid);
258 }
259 }
260 s.push(right);
261 s
262 };
263
264 let make_data_row = |cells: &[String]| -> Line<'static> {
265 let mut spans: Vec<Span<'static>> = Vec::with_capacity(ncols * 2 + 2);
266 spans.push(Span::raw(indent.to_string()));
267 spans.push(Span::styled("│".to_string(), border_style));
268 for (i, w) in widths.iter().enumerate() {
269 let cell = truncate_cell(&cells[i], *w);
270 let pad_right = w.saturating_sub(cell.chars().count());
271 let mut content = String::with_capacity(2 + w);
272 content.push(' ');
273 content.push_str(&cell);
274 for _ in 0..pad_right {
275 content.push(' ');
276 }
277 content.push(' ');
278 spans.push(Span::styled(content, cell_style));
279 let _ = i;
280 spans.push(Span::styled("│".to_string(), border_style));
281 }
282 Line::from(spans)
283 };
284
285 let mut out: Vec<Line<'static>> = Vec::with_capacity(body_n.len() + 4);
286 out.push(Line::from(Span::styled(
287 make_border('┌', '┬', '┐'),
288 border_style,
289 )));
290 out.push(make_data_row(&header_n));
291 out.push(Line::from(Span::styled(
292 make_border('├', '┼', '┤'),
293 border_style,
294 )));
295 for row in &body_n {
296 out.push(make_data_row(row));
297 }
298 out.push(Line::from(Span::styled(
299 make_border('└', '┴', '┘'),
300 border_style,
301 )));
302 out
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 #[test]
310 fn code_fence_lang_recognizes_openers_and_closers() {
311 assert_eq!(code_fence_lang("```bash"), Some("bash".into()));
312 assert_eq!(code_fence_lang("```sh"), Some("sh".into()));
313 assert_eq!(code_fence_lang("```Rust"), Some("rust".into()));
314 assert_eq!(code_fence_lang("```"), Some("".into()));
315 assert_eq!(code_fence_lang(" ```bash "), Some("bash".into()));
316 assert_eq!(code_fence_lang("hello"), None);
317 assert_eq!(code_fence_lang("``"), None);
318 }
319
320 #[test]
321 fn is_executable_shell_lang_matches_shells() {
322 assert!(is_executable_shell_lang("bash"));
323 assert!(is_executable_shell_lang("sh"));
324 assert!(is_executable_shell_lang("zsh"));
325 assert!(is_executable_shell_lang("fish"));
326 assert!(!is_executable_shell_lang("rust"));
327 assert!(!is_executable_shell_lang("python"));
328 assert!(!is_executable_shell_lang(""));
329 }
330
331 #[test]
332 fn extract_last_shell_block_finds_bash() {
333 let text = "Run this:\n```bash\necho hello\nls -la\n```\nDone.";
334 assert_eq!(
335 extract_last_shell_block(text),
336 Some("echo hello\nls -la".into())
337 );
338 }
339
340 #[test]
341 fn extract_last_shell_block_returns_last_when_multiple() {
342 let text = "```bash\nfirst\n```\nstuff\n```sh\nsecond\nthird\n```\n";
343 assert_eq!(extract_last_shell_block(text), Some("second\nthird".into()));
344 }
345
346 #[test]
347 fn extract_last_shell_block_ignores_non_shell() {
348 let text = "```rust\nfn main() {}\n```";
349 assert_eq!(extract_last_shell_block(text), None);
350 }
351
352 #[test]
353 fn extract_last_shell_block_none_without_block() {
354 assert_eq!(extract_last_shell_block("plain prose only"), None);
355 }
356
357 #[test]
358 fn extract_last_shell_block_unclosed_fence_returns_none() {
359 let text = "Here's a script:\n```bash\necho hello\nls -la";
360 assert_eq!(extract_last_shell_block(text), None);
361 }
362
363 #[test]
364 fn extract_last_shell_block_closed_then_unclosed_returns_closed() {
365 let text = "```bash\necho first\n```\n```sh\nunclosed";
366 assert_eq!(
367 extract_last_shell_block(text),
368 Some("echo first".to_string())
369 );
370 }
371
372 #[test]
373 fn is_md_table_row_basic() {
374 assert!(is_md_table_row("| a | b |"));
375 assert!(is_md_table_row(" |x|"));
376 assert!(!is_md_table_row("hello"));
377 assert!(!is_md_table_row(""));
378 }
379
380 #[test]
381 fn is_md_table_separator_basic() {
382 assert!(is_md_table_separator("|---|---|"));
383 assert!(is_md_table_separator("| :--- | ---: |"));
384 assert!(is_md_table_separator("|:-:|:-:|"));
385 assert!(!is_md_table_separator("| a | b |"));
386 assert!(!is_md_table_separator("hello"));
387 assert!(!is_md_table_separator("| | |"));
388 }
389
390 #[test]
391 fn parse_md_table_cells_basic() {
392 assert_eq!(
393 parse_md_table_cells("| a | b |"),
394 vec!["a".to_string(), "b".to_string()]
395 );
396 assert_eq!(
397 parse_md_table_cells("|x|y|z|"),
398 vec!["x".to_string(), "y".to_string(), "z".to_string()]
399 );
400 assert_eq!(
401 parse_md_table_cells("| Technique | Impact | Effort |"),
402 vec![
403 "Technique".to_string(),
404 "Impact".to_string(),
405 "Effort".to_string()
406 ]
407 );
408 }
409
410 #[test]
411 fn truncate_cell_basic() {
412 assert_eq!(truncate_cell("abc", 5), "abc");
413 assert_eq!(truncate_cell("abcdef", 4), "abc…");
414 assert_eq!(truncate_cell("hello", 0), "");
415 assert_eq!(truncate_cell("hello", 5), "hello");
416 }
417
418 #[test]
419 fn render_markdown_table_emits_expected_lines() {
420 let header = vec![
421 "Technique".to_string(),
422 "Impact".to_string(),
423 "Effort".to_string(),
424 ];
425 let body = vec![
426 vec![
427 "Prompt constraints".to_string(),
428 "10–20%".to_string(),
429 "Low".to_string(),
430 ],
431 vec![
432 "max_tokens caps".to_string(),
433 "Prevents runaway".to_string(),
434 "Low".to_string(),
435 ],
436 ];
437 let out = render_markdown_table(&header, &body, 200, " ", None);
438 assert_eq!(out.len(), 6);
439 let first: String = out[0]
440 .spans
441 .iter()
442 .map(|s| s.content.as_ref())
443 .collect::<Vec<_>>()
444 .join("");
445 assert!(
446 first.contains('┌'),
447 "expected ┌ in top border, got: {first}"
448 );
449 assert!(first.contains('┬'));
450 assert!(first.contains('┐'));
451 let header_line: String = out[1]
452 .spans
453 .iter()
454 .map(|s| s.content.as_ref())
455 .collect::<Vec<_>>()
456 .join("");
457 assert!(header_line.contains("Technique"));
458 assert!(header_line.contains("Impact"));
459 assert!(header_line.contains("Effort"));
460 let sep_line: String = out[2]
461 .spans
462 .iter()
463 .map(|s| s.content.as_ref())
464 .collect::<Vec<_>>()
465 .join("");
466 assert!(sep_line.contains('├'));
467 assert!(sep_line.contains('┼'));
468 assert!(sep_line.contains('┤'));
469 let last: String = out[5]
470 .spans
471 .iter()
472 .map(|s| s.content.as_ref())
473 .collect::<Vec<_>>()
474 .join("");
475 assert!(last.contains('└'));
476 assert!(last.contains('┴'));
477 assert!(last.contains('┘'));
478 for l in &out {
479 let s: String = l
480 .spans
481 .iter()
482 .map(|sp| sp.content.as_ref())
483 .collect::<Vec<_>>()
484 .join("");
485 assert!(s.starts_with(" "), "line missing indent: {s:?}");
486 }
487 }
488
489 #[test]
490 fn render_markdown_table_truncates_when_too_wide() {
491 let header = vec!["AVeryLongHeaderName".to_string(), "B".to_string()];
492 let body = vec![vec!["X".to_string(), "Y".to_string()]];
493 let out = render_markdown_table(&header, &body, 18, "", None);
494 assert_eq!(out.len(), 5);
495 let header_line: String = out[1]
496 .spans
497 .iter()
498 .map(|s| s.content.as_ref())
499 .collect::<Vec<_>>()
500 .join("");
501 assert!(
502 header_line.chars().count() <= 18,
503 "row too wide: {header_line:?}"
504 );
505 }
506}