1 use std::borrow::ToOwned;
2 use std::collections::HashMap;
5 use std::iter::Iterator;
8 pub column_threshold: usize,
11 const HEADER: &str = r#"<!DOCTYPE html>
14 <meta charset="utf-8">
15 <meta name="viewport" content="width=device-width, initial-scale=1">
17 td { text-align: center; }
18 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
19 th, td { white-space: nowrap; }
20 th { text-align: left; font-weight: normal; }
21 th.spacer_row { height: .3em; }
22 table { border-collapse: collapse }
23 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
24 tr.key > th > div { width: 1em; }
25 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
26 td { border: thin solid gray; }
27 td.leftover { text-align: left; border: none; padding-left: .4em; }
28 td.yes { border: thin solid gray; background-color: #ddd; }
29 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
30 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
33 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
34 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
35 function h2(a, b) { highlight(a); highlight(b); }
36 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
43 const FOOTER: &str = " </tbody>
48 #[derive(PartialEq, Eq, Debug)]
49 pub struct HTML(String);
51 fn escape(value: &str) -> HTML {
52 let mut escaped: String = String::new();
53 for c in value.chars() {
55 '>' => escaped.push_str(">"),
56 '<' => escaped.push_str("<"),
57 '\'' => escaped.push_str("'"),
58 '"' => escaped.push_str("""),
59 '&' => escaped.push_str("&"),
60 ok_c => escaped.push(ok_c),
66 impl From<&str> for HTML {
67 fn from(value: &str) -> HTML {
68 HTML(String::from(value))
71 impl FromIterator<HTML> for HTML {
72 fn from_iter<T>(iter: T) -> HTML
74 T: IntoIterator<Item = HTML>,
76 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
79 impl std::fmt::Display for HTML {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 write!(f, "{}", self.0)
85 #[derive(Debug, PartialEq, Eq)]
89 Entry(&'a str, Option<&'a str>),
91 impl<'a> From<&'a str> for InputLine<'a> {
92 fn from(value: &'a str) -> InputLine<'a> {
93 let trimmed = value.trim_end();
94 if trimmed.is_empty() {
96 } else if !trimmed.starts_with(' ') {
97 InputLine::RowHeader(value.trim())
99 match value.split_once(':') {
100 None => InputLine::Entry(value.trim(), None),
101 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
107 #[derive(Debug, PartialEq, Eq)]
110 entries: HashMap<String, Vec<Option<String>>>,
113 #[derive(Debug, PartialEq, Eq)]
119 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
120 input: std::iter::Enumerate<Input>,
123 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
124 fn new(input: Input) -> Self {
126 input: input.enumerate(),
131 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
132 type Item = Result<Rowlike, std::io::Error>;
133 fn next(&mut self) -> Option<Self::Item> {
135 match self.input.next() {
136 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
137 Some((_, Err(e))) => return Some(Err(e)),
138 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
139 InputLine::Blank if self.row.is_some() => {
140 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
142 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
143 InputLine::Entry(col, instance) => match &mut self.row {
145 return Some(Err(std::io::Error::other(format!(
146 "{}: Entry with no header",
150 Some(ref mut row) => {
152 .entry(col.to_owned())
153 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
154 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
157 InputLine::RowHeader(row) => {
158 let prev = std::mem::take(&mut self.row);
159 self.row = Some(Row {
160 label: row.to_owned(),
161 entries: HashMap::new(),
164 return Ok(prev.map(Rowlike::Row)).transpose();
173 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
174 let default_config = Config {
177 Reader::new(std::io::BufReader::new(input).lines())
178 .collect::<Result<Vec<_>, _>>()
179 .map(|rows| (rows, default_config))
182 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
183 let empty = HashMap::new();
184 let mut counts: Vec<_> = rows
186 .flat_map(|rl| match rl {
187 Rowlike::Row(r) => r.entries.keys(),
188 Rowlike::Spacer => empty.keys(),
190 .fold(HashMap::new(), |mut cs, col| {
191 cs.entry(col.to_owned())
192 .and_modify(|n| *n += 1)
197 .map(|(col, n)| (n, col))
199 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
202 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
205 .filter_map(|(n, col)| (n >= config.column_threshold).then_some(col))
209 fn render_one_instance(instance: &Option<String>) -> HTML {
211 None => HTML::from("✓"),
212 Some(instance) => HTML::escape(instance.as_ref()),
216 fn render_instances(instances: &[Option<String>]) -> HTML {
217 let all_empty = instances.iter().all(Option::is_none);
218 if all_empty && instances.len() == 1 {
220 } else if all_empty {
221 HTML(format!("{}", instances.len()))
226 .map(render_one_instance)
227 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
234 fn render_cell(col: &str, row: &mut Row) -> HTML {
235 let row_label = HTML::escape(row.label.as_ref());
236 let col_label = HTML::escape(col);
237 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
238 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
239 let contents = match instances {
240 None => HTML::from(""),
241 Some(is) => render_instances(is),
243 row.entries.remove(col);
245 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
249 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
250 let label = HTML::escape(notcol);
251 let rest = render_instances(instances);
252 if rest == HTML::from("") {
253 HTML(format!("{label}"))
255 HTML(format!("{label}: {rest}"))
259 fn render_all_leftovers(row: &Row) -> HTML {
260 let mut order: Vec<_> = row.entries.keys().collect();
261 order.sort_unstable();
265 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
266 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
272 fn render_row(columns: &[String], rowlike: &mut Rowlike) -> HTML {
274 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
275 Rowlike::Row(row) => {
276 let row_label = HTML::escape(row.label.as_ref());
279 .map(|col| render_cell(col, row))
281 let leftovers = render_all_leftovers(row);
283 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
289 fn render_column_headers(columns: &[String]) -> HTML {
291 String::from(r#"<tr class="key"><th></th>"#)
292 + &columns.iter().fold(String::new(), |mut acc, col| {
293 let col_header = HTML::escape(col.as_ref());
296 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
307 /// Will return `Err` if
308 /// * there's an i/o error while reading `input`
309 /// * the log has invalid syntax:
310 /// * an indented line with no preceding non-indented line
311 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
312 let (rows, config) = read_input(input)?;
313 let columns = column_order(&config, &rows);
315 "{HEADER}{}{}{FOOTER}",
316 render_column_headers(&columns),
318 .map(|mut r| render_row(&columns, &mut r))
328 fn test_parse_line() {
329 assert_eq!(InputLine::from(""), InputLine::Blank);
330 assert_eq!(InputLine::from(" "), InputLine::Blank);
331 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
332 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
333 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
335 InputLine::from(" foo:bar"),
336 InputLine::Entry("foo", Some("bar"))
339 InputLine::from(" foo: bar"),
340 InputLine::Entry("foo", Some("bar"))
343 InputLine::from(" foo: bar "),
344 InputLine::Entry("foo", Some("bar"))
347 InputLine::from(" foo: bar "),
348 InputLine::Entry("foo", Some("bar"))
351 InputLine::from(" foo : bar "),
352 InputLine::Entry("foo", Some("bar"))
356 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
357 read_input(input).map(|(rows, _)| rows)
360 fn test_read_rows() {
362 read_rows(&b"foo"[..]).unwrap(),
363 vec![Rowlike::Row(Row {
364 label: "foo".to_owned(),
365 entries: HashMap::new(),
369 read_rows(&b"bar"[..]).unwrap(),
370 vec![Rowlike::Row(Row {
371 label: "bar".to_owned(),
372 entries: HashMap::new(),
376 read_rows(&b"foo\nbar\n"[..]).unwrap(),
379 label: "foo".to_owned(),
380 entries: HashMap::new(),
383 label: "bar".to_owned(),
384 entries: HashMap::new(),
389 read_rows(&b"foo\n bar\n"[..]).unwrap(),
390 vec![Rowlike::Row(Row {
391 label: "foo".to_owned(),
392 entries: HashMap::from([("bar".to_owned(), vec![None])]),
396 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
397 vec![Rowlike::Row(Row {
398 label: "foo".to_owned(),
399 entries: HashMap::from([
400 ("bar".to_owned(), vec![None]),
401 ("baz".to_owned(), vec![None])
406 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
409 label: "foo".to_owned(),
410 entries: HashMap::new(),
413 label: "bar".to_owned(),
414 entries: HashMap::new(),
419 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
422 label: "foo".to_owned(),
423 entries: HashMap::new(),
427 label: "bar".to_owned(),
428 entries: HashMap::new(),
433 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
436 label: "foo".to_owned(),
437 entries: HashMap::new(),
440 label: "bar".to_owned(),
441 entries: HashMap::new(),
446 read_rows(&b"foo \n bar \n"[..]).unwrap(),
447 vec![Rowlike::Row(Row {
448 label: "foo".to_owned(),
449 entries: HashMap::from([("bar".to_owned(), vec![None])]),
453 let bad = read_rows(&b" foo"[..]);
454 assert!(bad.is_err());
455 assert!(format!("{bad:?}").contains("1: Entry with no header"));
457 let bad2 = read_rows(&b"foo\n\n bar"[..]);
458 assert!(bad2.is_err());
459 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
463 fn test_column_counts() {
465 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
466 vec![(1, String::from("bar")), (1, String::from("baz"))]
469 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
470 vec![(2, String::from("baz")), (1, String::from("bar"))]
473 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
474 vec![(2, String::from("baz")), (1, String::from("bar"))]
478 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
480 vec![(2, String::from("baz")), (1, String::from("bar"))]
485 fn test_render_cell() {
490 label: "nope".to_owned(),
491 entries: HashMap::new(),
495 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
502 label: "nope".to_owned(),
503 entries: HashMap::from([("bar".to_owned(), vec![None])]),
507 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
514 label: "nope".to_owned(),
515 entries: HashMap::from([("foo".to_owned(), vec![None])]),
519 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
526 label: "nope".to_owned(),
527 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
531 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
538 label: "nope".to_owned(),
539 entries: HashMap::from([(
541 vec![Some("5".to_owned()), Some("10".to_owned())]
546 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
553 label: "nope".to_owned(),
554 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
558 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
565 label: "nope".to_owned(),
566 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
570 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
577 label: "bob's".to_owned(),
578 entries: HashMap::from([("foo".to_owned(), vec![None])]),
582 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
586 label: "nope".to_owned(),
587 entries: HashMap::from([
588 ("foo".to_owned(), vec![None]),
589 ("baz".to_owned(), vec![None]),
592 assert_eq!(r.entries.len(), 2);
593 render_cell("foo", &mut r);
594 assert_eq!(r.entries.len(), 1);
595 render_cell("bar", &mut r);
596 assert_eq!(r.entries.len(), 1);
597 render_cell("baz", &mut r);
598 assert_eq!(r.entries.len(), 0);
602 fn test_render_leftovers() {
604 render_all_leftovers(&Row {
605 label: "nope".to_owned(),
606 entries: HashMap::from([("foo".to_owned(), vec![None])]),
611 render_all_leftovers(&Row {
612 label: "nope".to_owned(),
613 entries: HashMap::from([
614 ("foo".to_owned(), vec![None]),
615 ("bar".to_owned(), vec![None])
618 HTML::from("bar, foo")
621 render_all_leftovers(&Row {
622 label: "nope".to_owned(),
623 entries: HashMap::from([
624 ("foo".to_owned(), vec![None]),
625 ("bar".to_owned(), vec![None, None])
628 HTML::from("bar: 2, foo")
633 fn test_render_row() {
637 &mut Rowlike::Row(Row {
638 label: "nope".to_owned(),
639 entries: HashMap::from([("bar".to_owned(), vec![None])]),
643 r#"<tr><th id="nope">nope</th><td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')">bar</td></tr>