1use ratatui::buffer::Buffer;
18use ratatui::layout::{Constraint, Layout, Rect};
19use ratatui::style::{Color, Modifier, Style, Stylize};
20use ratatui::text::{Line as TLine, Span};
21use ratatui::widgets::{
22 Cell, Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Table,
23 Widget,
24};
25use yaml_rust2::Yaml;
26
27use super::{clip, dur, hms, i64_of, kind, pairs, service, stamp};
28use crate::term;
29
30fn paint(w: usize, h: usize, f: impl FnOnce(Rect, &mut Buffer)) -> Vec<String> {
32 let area = Rect::new(0, 0, w as u16, h as u16);
33 let mut buf = Buffer::empty(area);
34 f(area, &mut buf);
35 flatten(&buf, area)
36}
37
38fn flatten(buf: &Buffer, area: Rect) -> Vec<String> {
44 let mut out = Vec::with_capacity(area.height as usize);
45 for y in area.top()..area.bottom() {
46 let mut line = String::new();
47 let mut open: Option<(Color, Modifier)> = None;
48 for x in area.left()..area.right() {
49 let Some(c) = buf.cell((x, y)) else { continue };
50 let key = (c.fg, c.modifier);
51 if open != Some(key) {
52 line.push_str(term::RESET);
53 line.push_str(&sgr(c.fg, c.modifier));
54 open = Some(key);
55 }
56 line.push_str(c.symbol());
57 }
58 line.push_str(term::RESET);
59 out.push(line);
60 }
61 out
62}
63
64fn sgr(fg: Color, m: Modifier) -> String {
72 let mut s = String::new();
73 if m.contains(Modifier::BOLD) {
74 s.push_str(term::BOLD);
75 }
76 if m.contains(Modifier::DIM) {
77 s.push_str(term::DIM);
78 }
79 if m.contains(Modifier::REVERSED) {
80 s.push_str(term::REV);
81 }
82 s.push_str(match fg {
83 Color::Red => term::RED,
84 Color::Green => term::GREEN,
85 Color::Yellow => term::YELLOW,
86 Color::Blue => term::BLUE,
87 Color::Magenta => term::MAGENTA,
88 Color::Cyan => term::CYAN,
89 _ => "",
90 });
91 s
92}
93
94pub fn sev(n: i64) -> Style {
97 match n {
98 17.. => Style::default().fg(Color::Red),
99 13..=16 => Style::default().fg(Color::Yellow),
100 9..=12 => Style::default().fg(Color::Green),
101 _ => Style::default().add_modifier(Modifier::DIM),
102 }
103}
104
105pub fn row(w: usize, spans: Vec<Span<'_>>) -> String {
113 row_styled(w, Style::default(), spans)
114}
115
116pub fn row_styled(w: usize, base: Style, spans: Vec<Span<'_>>) -> String {
123 paint(w, 1, |area, buf| {
124 Paragraph::new(TLine::from(spans))
125 .style(base)
126 .render(area, buf);
127 })
128 .pop()
129 .unwrap_or_default()
130}
131
132pub fn hl(on: bool) -> Style {
134 match on {
135 true => Style::default().add_modifier(Modifier::REVERSED),
136 false => Style::default(),
137 }
138}
139
140pub fn columns(w: usize, base: Style, cells: Vec<(u16, Vec<Span<'_>>)>) -> String {
147 paint(w, 1, |area, buf| {
148 buf.set_style(area, base);
149 let widths: Vec<Constraint> = cells.iter().map(|(n, _)| Constraint::Length(*n)).collect();
150 let areas = Layout::horizontal(widths).split(area);
151 for (a, (_, spans)) in areas.iter().zip(cells) {
152 Paragraph::new(TLine::from(spans)).render(*a, buf);
153 }
154 })
155 .pop()
156 .unwrap_or_default()
157}
158
159pub fn bar(w: usize, left: Vec<Span<'_>>, right: Vec<Span<'_>>) -> String {
166 let rw = right.iter().map(Span::width).sum::<usize>() as u16;
167 paint(w, 1, |area, buf| {
168 let [l, r] = Layout::horizontal([Constraint::Min(0), Constraint::Length(rw)]).areas(area);
169 Paragraph::new(TLine::from(left)).render(l, buf);
170 Paragraph::new(TLine::from(right)).render(r, buf);
171 })
172 .pop()
173 .unwrap_or_default()
174}
175
176pub fn rule(w: usize, title: &str) -> String {
178 let used = 2 + title.chars().count();
179 row(
180 w,
181 vec![
182 "──".dim(),
183 title.to_string().dim(),
184 "─".repeat(w.saturating_sub(used)).dim(),
185 ],
186 )
187}
188
189pub fn log_list(rows: &[Yaml], w: usize, h: usize, sel: usize, start: usize) -> Vec<String> {
196 let visible: Vec<Row> = rows
197 .iter()
198 .skip(start)
199 .take(h)
200 .enumerate()
201 .map(|(i, row)| {
202 let picked = start + i == sel;
206 let dim = match picked {
207 true => Style::default(),
208 false => Style::default().add_modifier(Modifier::DIM),
209 };
210 let n = row["severity_number"].as_i64().unwrap_or(0);
211 Row::new(vec![
212 Cell::from(format!(" {}", hms(i64_of(&row["time_unix_nano"])))),
213 Cell::from(clip(row["severity_text"].as_str().unwrap_or("-"), 6))
214 .style(if picked { Style::default() } else { sev(n) }),
215 Cell::from(clip(service(row), 16)).style(dim),
216 Cell::from(row["body"].as_str().unwrap_or("").to_owned()),
217 ])
218 .style(hl(picked))
219 })
220 .collect();
221
222 paint(w, h, |area, buf| {
223 let body = Rect {
225 width: area.width.saturating_sub(1),
226 ..area
227 };
228 let table = Table::new(
229 visible,
230 [
231 Constraint::Length(13),
232 Constraint::Length(6),
233 Constraint::Length(16),
234 Constraint::Min(0),
235 ],
236 )
237 .column_spacing(1);
238 Widget::render(table, body, buf);
239
240 let mut state = ScrollbarState::new(rows.len()).position(sel);
241 Scrollbar::new(ScrollbarOrientation::VerticalRight)
242 .begin_symbol(None)
243 .end_symbol(None)
244 .render(area, buf, &mut state);
245 })
246}
247
248pub fn detail(row: &Yaml, w: usize) -> Vec<String> {
257 let mut fields: Vec<(String, String, Color)> = Vec::new();
258 for (k, v) in pairs(row) {
259 if matches!(k.as_str(), "attributes" | "events" | "links" | "points") {
260 continue;
261 }
262 let pretty = match k.as_str() {
263 "time_unix_nano" | "observed_time_unix_nano" | "start_time_unix_nano" => {
264 v.parse::<i64>().map(stamp).unwrap_or_else(|_| v.clone())
265 }
266 "duration_nano" => v.parse::<i64>().map(dur).unwrap_or_else(|_| v.clone()),
267 "kind" => v
268 .parse::<i64>()
269 .map(|k| kind(k).to_owned())
270 .unwrap_or_else(|_| v.clone()),
271 _ => v.clone(),
272 };
273 fields.push((k, pretty, Color::Reset));
274 }
275
276 let mut groups = vec![("", fields)];
277 let attrs = pairs(&row["attributes"]);
278 if !attrs.is_empty() {
279 groups.push((
280 " attributes ",
281 attrs
282 .into_iter()
283 .map(|(k, v)| (k, v, Color::Cyan))
284 .collect(),
285 ));
286 }
287 for (label, key) in [(" events ", "events"), (" links ", "links")] {
291 let items = row[key].as_vec().map_or(&[][..], |v| v.as_slice());
292 if items.is_empty() {
293 continue;
294 }
295 let mut rows = Vec::new();
296 for it in items {
297 for (k, v) in pairs(it) {
298 if k == "attributes" {
299 continue;
300 }
301 rows.push((k, v, Color::Reset));
302 }
303 for (k, v) in pairs(&it["attributes"]) {
304 rows.push((format!(" {k}"), v, Color::Cyan));
305 }
306 }
307 groups.push((label, rows));
308 }
309
310 let keyw = groups
313 .iter()
314 .flat_map(|(_, rows)| rows.iter())
315 .map(|(k, _, _)| k.chars().count())
316 .max()
317 .unwrap_or(0)
318 .min(w / 3) as u16;
319
320 let mut out = Vec::new();
321 for (label, rows) in groups {
322 if rows.is_empty() {
326 continue;
327 }
328 if !label.is_empty() {
329 out.push(rule(w, label));
330 }
331 let table: Vec<Row> = rows
332 .iter()
333 .map(|(k, v, c)| {
334 Row::new(vec![
335 Cell::from(k.clone()).style(Style::default().add_modifier(Modifier::DIM)),
336 Cell::from(v.clone()).style(Style::default().fg(*c)),
337 ])
338 })
339 .collect();
340 out.extend(paint(w, rows.len(), |area, buf| {
341 let body = Rect {
344 x: 2,
345 width: area.width.saturating_sub(2),
346 ..area
347 };
348 let t =
349 Table::new(table, [Constraint::Length(keyw), Constraint::Min(0)]).column_spacing(2);
350 Widget::render(t, body, buf);
351 }));
352 }
353 out
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use crate::tui::tests::strip;
360
361 #[test]
365 fn a_long_attribute_key_does_not_abut_its_value() {
366 let y = yaml_rust2::YamlLoader::load_from_str(
367 "body: hi\nattributes:\n deployment.environment.name: prod\n",
368 )
369 .unwrap()
370 .remove(0);
371 let out = detail(&y, 100);
372 let line = out
373 .iter()
374 .map(|l| strip(l))
375 .find(|l| l.contains("prod"))
376 .expect("the attribute is rendered");
377 assert!(
378 line.contains("name prod") || line.contains("name prod"),
379 "key and value must not run together: {line:?}"
380 );
381 }
382
383 #[test]
389 fn an_empty_section_is_not_a_heading_over_nothing() {
390 let y = yaml_rust2::YamlLoader::load_from_str(
391 "attributes:\n service.name: api\npoints:\n - 1\nevents:\n - attributes: {}\n",
392 )
393 .unwrap()
394 .remove(0);
395 let out: Vec<String> = detail(&y, 80).iter().map(|l| strip(l)).collect();
396 assert!(out[0].contains("attributes"), "{out:?}");
397 assert!(out.iter().any(|l| l.contains("api")), "{out:?}");
398 assert!(!out.iter().any(|l| l.contains("events")), "{out:?}");
399 }
400}