]> git.scottworley.com Git - tablify/blame - src/lib.rs
Tally marks
[tablify] / src / lib.rs
CommitLineData
88a08162 1use std::borrow::ToOwned;
a411a19d 2use std::collections::{HashMap, HashSet};
7067975b 3use std::fmt::Write;
9dfa98b7 4use std::io::BufRead;
75bb888a
SW
5use std::iter::Iterator;
6
f8c2cab2
SW
7fn tally_marks(n: usize) -> String {
8 let fives = { 0..n / 5 }.map(|_| '𝍸');
9 let ones = { 0..n % 5 }.map(|_| '𝍷');
10 fives.chain(ones).collect()
11}
12
e44de444
SW
13#[derive(PartialEq, Eq, Debug)]
14struct Config {
15 column_threshold: usize,
a0577201 16 static_columns: Vec<Option<String>>,
3135b2cd 17 hidden_columns: HashSet<String>,
d669f60d 18 substitute_labels: HashMap<String, String>,
e44de444
SW
19}
20impl Config {
f105c5bc 21 fn apply_command(&mut self, line_num: usize, cmd: &str) -> Result<(), std::io::Error> {
e44de444 22 if let Some(threshold) = cmd.strip_prefix("col_threshold ") {
f105c5bc
SW
23 self.column_threshold = threshold.parse().map_err(|e| {
24 std::io::Error::new(
25 std::io::ErrorKind::InvalidInput,
26 format!("line {line_num}: col_threshold must be numeric: {e}"),
27 )
28 })?;
3135b2cd
SW
29 } else if let Some(col) = cmd.strip_prefix("hide ") {
30 self.hidden_columns.insert(col.to_owned());
a411a19d 31 } else if let Some(col) = cmd.strip_prefix("col ") {
a0577201
SW
32 self.static_columns.push(Some(col.to_owned()));
33 } else if cmd == "colsep" {
34 self.static_columns.push(None);
d669f60d
SW
35 } else if let Some(directive) = cmd.strip_prefix("label ") {
36 match directive.split_once(':') {
37 None => {
38 return Err(std::io::Error::new(
39 std::io::ErrorKind::InvalidInput,
40 format!("line {line_num}: Annotation missing ':'"),
41 ))
42 }
43 Some((col, label)) => self
44 .substitute_labels
45 .insert(col.to_owned(), label.to_owned()),
46 };
b2f31832
SW
47 } else {
48 return Err(std::io::Error::new(
49 std::io::ErrorKind::InvalidInput,
f105c5bc 50 format!("line {line_num}: Unknown command: {cmd}"),
b2f31832 51 ));
e44de444
SW
52 }
53 Ok(())
54 }
31af9aac 55}
bc552978
SW
56impl Default for Config {
57 fn default() -> Self {
58 Self {
59 column_threshold: 2,
60 static_columns: vec![],
3135b2cd 61 hidden_columns: HashSet::new(),
d669f60d 62 substitute_labels: HashMap::new(),
bc552978
SW
63 }
64 }
65}
71e34cc0 66
5ffe8e3a 67const HEADER: &str = r#"<!DOCTYPE html>
cc2378d5
SW
68<html>
69<head>
5ffe8e3a
SW
70 <meta charset="utf-8">
71 <meta name="viewport" content="width=device-width, initial-scale=1">
cc2378d5 72 <style>
b8b365ce 73 td { text-align: center; }
cc2378d5
SW
74 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
75 th, td { white-space: nowrap; }
76 th { text-align: left; font-weight: normal; }
529cbaa2 77 th.spacer_row { height: .3em; }
a0577201 78 .spacer_col { border: none; width: .2em; }
cc2378d5 79 table { border-collapse: collapse }
3bc643e9 80 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
cc2378d5
SW
81 tr.key > th > div { width: 1em; }
82 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
83 td { border: thin solid gray; }
36bc3a39 84 td.leftover { text-align: left; border: none; padding-left: .4em; }
1dda21e6 85 td.yes { border: thin solid gray; background-color: #ddd; }
cc2378d5
SW
86 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
87 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
cc2378d5
SW
88 </style>
89 <script>
5ffe8e3a
SW
90 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
91 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
cc2378d5
SW
92 function h2(a, b) { highlight(a); highlight(b); }
93 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
94 </script>
95</head>
96<body>
97 <table>
76638ea1 98 <tbody>
5ffe8e3a 99"#;
cc2378d5
SW
100const FOOTER: &str = " </tbody>
101 </table>
102</body>
103</html>";
104
70436f23
SW
105#[derive(PartialEq, Eq, Debug)]
106pub struct HTML(String);
107impl HTML {
108 fn escape(value: &str) -> HTML {
109 let mut escaped: String = String::new();
110 for c in value.chars() {
111 match c {
112 '>' => escaped.push_str("&gt;"),
113 '<' => escaped.push_str("&lt;"),
114 '\'' => escaped.push_str("&#39;"),
115 '"' => escaped.push_str("&quot;"),
116 '&' => escaped.push_str("&amp;"),
117 ok_c => escaped.push(ok_c),
118 }
119 }
120 HTML(escaped)
121 }
122}
123impl From<&str> for HTML {
124 fn from(value: &str) -> HTML {
125 HTML(String::from(value))
126 }
127}
128impl FromIterator<HTML> for HTML {
129 fn from_iter<T>(iter: T) -> HTML
130 where
131 T: IntoIterator<Item = HTML>,
132 {
133 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
134 }
135}
136impl std::fmt::Display for HTML {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 write!(f, "{}", self.0)
139 }
140}
141
88a08162
SW
142#[derive(Debug, PartialEq, Eq)]
143enum InputLine<'a> {
144 Blank,
145 RowHeader(&'a str),
146 Entry(&'a str, Option<&'a str>),
e44de444 147 Command(&'a str),
e8657dff 148}
88a08162
SW
149impl<'a> From<&'a str> for InputLine<'a> {
150 fn from(value: &'a str) -> InputLine<'a> {
151 let trimmed = value.trim_end();
152 if trimmed.is_empty() {
153 InputLine::Blank
e44de444
SW
154 } else if let Some(cmd) = trimmed.strip_prefix('!') {
155 InputLine::Command(cmd)
88a08162
SW
156 } else if !trimmed.starts_with(' ') {
157 InputLine::RowHeader(value.trim())
158 } else {
159 match value.split_once(':') {
160 None => InputLine::Entry(value.trim(), None),
161 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
162 }
e8657dff
SW
163 }
164 }
165}
14e9852b 166
75bb888a 167#[derive(Debug, PartialEq, Eq)]
88a08162
SW
168struct Row {
169 label: String,
170 entries: HashMap<String, Vec<Option<String>>>,
75bb888a
SW
171}
172
06a6a5ca
SW
173#[derive(Debug, PartialEq, Eq)]
174enum Rowlike {
175 Row(Row),
176 Spacer,
177}
178
e44de444 179struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
8110b492 180 input: std::iter::Enumerate<Input>,
88a08162 181 row: Option<Row>,
e44de444 182 config: &'cfg mut Config,
201b9ef3 183}
e44de444
SW
184impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
185 fn new(config: &'cfg mut Config, input: Input) -> Self {
8110b492
SW
186 Self {
187 input: input.enumerate(),
188 row: None,
e44de444 189 config,
8110b492 190 }
201b9ef3
SW
191 }
192}
e44de444
SW
193impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
194 for Reader<'cfg, Input>
195{
06a6a5ca 196 type Item = Result<Rowlike, std::io::Error>;
201b9ef3
SW
197 fn next(&mut self) -> Option<Self::Item> {
198 loop {
8bf0d5b1 199 match self.input.next() {
06a6a5ca 200 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
8110b492 201 Some((_, Err(e))) => return Some(Err(e)),
88a08162 202 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
e44de444 203 InputLine::Command(cmd) => {
f105c5bc 204 if let Err(e) = self.config.apply_command(n + 1, cmd) {
e44de444
SW
205 return Some(Err(e));
206 }
207 }
88a08162 208 InputLine::Blank if self.row.is_some() => {
06a6a5ca 209 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
8110b492 210 }
14a039db 211 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
88a08162
SW
212 InputLine::Entry(col, instance) => match &mut self.row {
213 None => {
214 return Some(Err(std::io::Error::other(format!(
1df4654a 215 "line {}: Entry with no header",
88a08162
SW
216 n + 1
217 ))))
218 }
219 Some(ref mut row) => {
220 row.entries
221 .entry(col.to_owned())
222 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
223 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
224 }
225 },
226 InputLine::RowHeader(row) => {
227 let prev = std::mem::take(&mut self.row);
228 self.row = Some(Row {
229 label: row.to_owned(),
230 entries: HashMap::new(),
231 });
232 if prev.is_some() {
06a6a5ca 233 return Ok(prev.map(Rowlike::Row)).transpose();
88a08162 234 }
201b9ef3 235 }
88a08162 236 },
201b9ef3
SW
237 }
238 }
239 }
240}
241
586b332a 242fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
bc552978 243 let mut config = Config::default();
e44de444
SW
244 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
245 reader
586b332a 246 .collect::<Result<Vec<_>, _>>()
e44de444 247 .map(|rows| (rows, config))
75bb888a
SW
248}
249
06a6a5ca
SW
250fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
251 let empty = HashMap::new();
58b5f36d
SW
252 let mut counts: Vec<_> = rows
253 .iter()
06a6a5ca
SW
254 .flat_map(|rl| match rl {
255 Rowlike::Row(r) => r.entries.keys(),
256 Rowlike::Spacer => empty.keys(),
257 })
b8907770 258 .fold(HashMap::new(), |mut cs, col| {
88a08162 259 cs.entry(col.to_owned())
58b5f36d 260 .and_modify(|n| *n += 1)
f272e502 261 .or_insert(1);
58b5f36d 262 cs
f272e502 263 })
58b5f36d
SW
264 .into_iter()
265 .map(|(col, n)| (n, col))
266 .collect();
38d1167a 267 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
58b5f36d 268 counts
f272e502 269}
06a6a5ca 270fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
a411a19d
SW
271 let static_columns: HashSet<&str> = config
272 .static_columns
273 .iter()
a0577201 274 .flatten()
a411a19d
SW
275 .map(std::string::String::as_str)
276 .collect();
d22b2e05
SW
277 column_counts(rows)
278 .into_iter()
a411a19d 279 .filter_map(|(n, col)| {
3135b2cd
SW
280 (n >= config.column_threshold
281 && !static_columns.contains(col.as_str())
282 && !config.hidden_columns.contains(&col))
283 .then_some(col)
a411a19d 284 })
d22b2e05
SW
285 .collect()
286}
f272e502 287
f915bc90 288fn render_instances(instances: &[Option<String>]) -> HTML {
f8c2cab2
SW
289 let mut tally = 0;
290 let mut out = vec![];
291 for ins in instances {
292 match ins {
293 None => tally += 1,
294 Some(content) => {
295 if tally > 0 {
296 out.push(HTML(tally_marks(tally)));
297 tally = 0;
298 }
299 out.push(HTML::escape(content));
300 }
301 }
302 }
303 if tally > 0 {
304 out.push(HTML(tally_marks(tally)));
f915bc90 305 }
f8c2cab2
SW
306 HTML(
307 out.into_iter()
308 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
309 .collect::<Vec<_>>()
310 .join(" "),
311 )
f915bc90
SW
312}
313
314fn render_cell(col: &str, row: &mut Row) -> HTML {
315 let row_label = HTML::escape(row.label.as_ref());
316 let col_label = HTML::escape(col);
317 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
318 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
319 let contents = match instances {
320 None => HTML::from(""),
321 Some(is) => render_instances(is),
de408c29 322 };
d9bfcf4d 323 row.entries.remove(col);
5ffe8e3a
SW
324 HTML(format!(
325 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
326 ))
de408c29
SW
327}
328
9a626020
SW
329fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
330 let label = HTML::escape(notcol);
f8c2cab2 331 if instances.len() == 1 && instances[0].is_none() {
9a626020
SW
332 HTML(format!("{label}"))
333 } else {
f8c2cab2 334 let rest = render_instances(instances);
9a626020
SW
335 HTML(format!("{label}: {rest}"))
336 }
337}
338
b4bc28ba 339fn render_all_leftovers(config: &Config, row: &Row) -> HTML {
3135b2cd
SW
340 let mut order: Vec<_> = row
341 .entries
342 .keys()
343 .filter(|&col| !config.hidden_columns.contains(col))
344 .collect();
9a626020
SW
345 order.sort_unstable();
346 HTML(
347 order
348 .into_iter()
349 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
350 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
351 .collect::<Vec<_>>()
352 .join(", "),
353 )
354}
355
215d38d5 356fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
06a6a5ca 357 match rowlike {
529cbaa2 358 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
06a6a5ca
SW
359 Rowlike::Row(row) => {
360 let row_label = HTML::escape(row.label.as_ref());
a411a19d
SW
361 let static_cells = config
362 .static_columns
363 .iter()
a0577201 364 .map(|ocol| match ocol {
3135b2cd 365 Some(col) if config.hidden_columns.contains(col) => HTML::from(""),
a0577201
SW
366 Some(col) => render_cell(col, row),
367 None => HTML::from(r#"<td class="spacer_col"></td>"#),
368 })
a411a19d
SW
369 .collect::<HTML>();
370 let dynamic_cells = columns
06a6a5ca 371 .iter()
3135b2cd 372 .filter(|&col| !config.hidden_columns.contains(col))
06a6a5ca
SW
373 .map(|col| render_cell(col, row))
374 .collect::<HTML>();
b4bc28ba 375 let leftovers = render_all_leftovers(config, row);
06a6a5ca 376 HTML(format!(
a411a19d 377 "<tr><th id=\"{row_label}\">{row_label}</th>{static_cells}{dynamic_cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
06a6a5ca
SW
378 ))
379 }
380 }
de408c29
SW
381}
382
e3feb9dc 383fn column_header_labels<'a>(
f93f5541
SW
384 config: &'a Config,
385 columns: &'a [String],
386) -> impl Iterator<Item = Option<&'a String>> {
a0577201
SW
387 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
388 let dynamic_columns = columns.iter().map(Some);
d669f60d
SW
389 static_columns
390 .chain(dynamic_columns)
391 .filter(|ocol| ocol.map_or(true, |col| !config.hidden_columns.contains(col)))
392 .map(|ocol| {
393 ocol.map(|col| match config.substitute_labels.get(col) {
394 None => col,
395 Some(substitute) => substitute,
396 })
397 })
f93f5541
SW
398}
399
400fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
70436f23 401 HTML(
5ffe8e3a 402 String::from(r#"<tr class="key"><th></th>"#)
e3feb9dc 403 + &column_header_labels(config, columns).fold(String::new(), |mut acc, ocol| {
f93f5541
SW
404 match ocol {
405 Some(col) => {
406 let col_header = HTML::escape(col);
407 write!(
408 &mut acc,
409 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
410 )
a0577201 411 }
f93f5541
SW
412 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
413 }
414 .unwrap();
415 acc
416 })
70436f23
SW
417 + "</tr>\n",
418 )
76638ea1
SW
419}
420
4b99fb70
SW
421/// # Errors
422///
423/// Will return `Err` if
424/// * there's an i/o error while reading `input`
425/// * the log has invalid syntax:
426/// * an indented line with no preceding non-indented line
586b332a
SW
427pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
428 let (rows, config) = read_input(input)?;
429 let columns = column_order(&config, &rows);
70436f23
SW
430 Ok(HTML(format!(
431 "{HEADER}{}{}{FOOTER}",
215d38d5 432 render_column_headers(&config, &columns),
70436f23 433 rows.into_iter()
215d38d5 434 .map(|mut r| render_row(&config, &columns, &mut r))
70436f23
SW
435 .collect::<HTML>()
436 )))
ece97615 437}
75bb888a
SW
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
b8907770 443 #[test]
88a08162
SW
444 fn test_parse_line() {
445 assert_eq!(InputLine::from(""), InputLine::Blank);
446 assert_eq!(InputLine::from(" "), InputLine::Blank);
447 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
448 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
449 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
b8907770 450 assert_eq!(
88a08162
SW
451 InputLine::from(" foo:bar"),
452 InputLine::Entry("foo", Some("bar"))
b8907770
SW
453 );
454 assert_eq!(
88a08162
SW
455 InputLine::from(" foo: bar"),
456 InputLine::Entry("foo", Some("bar"))
b8907770 457 );
0d999bc3 458 assert_eq!(
88a08162
SW
459 InputLine::from(" foo: bar "),
460 InputLine::Entry("foo", Some("bar"))
461 );
462 assert_eq!(
463 InputLine::from(" foo: bar "),
464 InputLine::Entry("foo", Some("bar"))
465 );
466 assert_eq!(
467 InputLine::from(" foo : bar "),
468 InputLine::Entry("foo", Some("bar"))
0d999bc3 469 );
b8907770
SW
470 }
471
f8c2cab2
SW
472 #[test]
473 fn test_tally_marks() {
474 assert_eq!(tally_marks(1), "𝍷");
475 assert_eq!(tally_marks(2), "𝍷𝍷");
476 assert_eq!(tally_marks(3), "𝍷𝍷𝍷");
477 assert_eq!(tally_marks(4), "𝍷𝍷𝍷𝍷");
478 assert_eq!(tally_marks(5), "𝍸");
479 assert_eq!(tally_marks(6), "𝍸𝍷");
480 assert_eq!(tally_marks(7), "𝍸𝍷𝍷");
481 assert_eq!(tally_marks(8), "𝍸𝍷𝍷𝍷");
482 assert_eq!(tally_marks(9), "𝍸𝍷𝍷𝍷𝍷");
483 assert_eq!(tally_marks(10), "𝍸𝍸");
484 assert_eq!(tally_marks(11), "𝍸𝍸𝍷");
485 }
486
586b332a
SW
487 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
488 read_input(input).map(|(rows, _)| rows)
489 }
e44de444
SW
490 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
491 read_input(input).map(|(_, config)| config)
492 }
75bb888a
SW
493 #[test]
494 fn test_read_rows() {
495 assert_eq!(
12e91300 496 read_rows(&b"foo"[..]).unwrap(),
06a6a5ca 497 vec![Rowlike::Row(Row {
88a08162
SW
498 label: "foo".to_owned(),
499 entries: HashMap::new(),
06a6a5ca 500 })]
75bb888a 501 );
9dfa98b7 502 assert_eq!(
12e91300 503 read_rows(&b"bar"[..]).unwrap(),
06a6a5ca 504 vec![Rowlike::Row(Row {
88a08162
SW
505 label: "bar".to_owned(),
506 entries: HashMap::new(),
06a6a5ca 507 })]
9dfa98b7 508 );
2aa9ef94 509 assert_eq!(
12e91300 510 read_rows(&b"foo\nbar\n"[..]).unwrap(),
2aa9ef94 511 vec![
06a6a5ca 512 Rowlike::Row(Row {
88a08162
SW
513 label: "foo".to_owned(),
514 entries: HashMap::new(),
06a6a5ca
SW
515 }),
516 Rowlike::Row(Row {
88a08162
SW
517 label: "bar".to_owned(),
518 entries: HashMap::new(),
06a6a5ca 519 })
2aa9ef94
SW
520 ]
521 );
201b9ef3 522 assert_eq!(
12e91300 523 read_rows(&b"foo\n bar\n"[..]).unwrap(),
06a6a5ca 524 vec![Rowlike::Row(Row {
88a08162
SW
525 label: "foo".to_owned(),
526 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 527 })]
201b9ef3
SW
528 );
529 assert_eq!(
12e91300 530 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
06a6a5ca 531 vec![Rowlike::Row(Row {
88a08162
SW
532 label: "foo".to_owned(),
533 entries: HashMap::from([
534 ("bar".to_owned(), vec![None]),
535 ("baz".to_owned(), vec![None])
536 ]),
06a6a5ca 537 })]
201b9ef3
SW
538 );
539 assert_eq!(
12e91300 540 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
722ea297
SW
541 vec![
542 Rowlike::Row(Row {
543 label: "foo".to_owned(),
544 entries: HashMap::new(),
545 }),
546 Rowlike::Row(Row {
547 label: "bar".to_owned(),
548 entries: HashMap::new(),
549 })
550 ]
551 );
552 assert_eq!(
12e91300 553 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
201b9ef3 554 vec![
06a6a5ca 555 Rowlike::Row(Row {
88a08162
SW
556 label: "foo".to_owned(),
557 entries: HashMap::new(),
06a6a5ca 558 }),
14a039db 559 Rowlike::Spacer,
06a6a5ca 560 Rowlike::Row(Row {
88a08162
SW
561 label: "bar".to_owned(),
562 entries: HashMap::new(),
06a6a5ca 563 })
201b9ef3
SW
564 ]
565 );
1f6bd845 566 assert_eq!(
12e91300 567 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
1f6bd845 568 vec![
06a6a5ca 569 Rowlike::Row(Row {
88a08162
SW
570 label: "foo".to_owned(),
571 entries: HashMap::new(),
06a6a5ca
SW
572 }),
573 Rowlike::Row(Row {
88a08162
SW
574 label: "bar".to_owned(),
575 entries: HashMap::new(),
06a6a5ca 576 })
1f6bd845
SW
577 ]
578 );
579 assert_eq!(
12e91300 580 read_rows(&b"foo \n bar \n"[..]).unwrap(),
06a6a5ca 581 vec![Rowlike::Row(Row {
88a08162
SW
582 label: "foo".to_owned(),
583 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 584 })]
1f6bd845 585 );
201b9ef3 586
12e91300 587 let bad = read_rows(&b" foo"[..]);
201b9ef3 588 assert!(bad.is_err());
1df4654a 589 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
201b9ef3 590
12e91300 591 let bad2 = read_rows(&b"foo\n\n bar"[..]);
201b9ef3 592 assert!(bad2.is_err());
1df4654a 593 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
75bb888a 594 }
f272e502 595
e44de444
SW
596 #[test]
597 fn test_read_config() {
598 assert_eq!(
fa8b5479
SW
599 read_config(&b"!col_threshold 10"[..])
600 .unwrap()
601 .column_threshold,
602 10
e44de444 603 );
a411a19d
SW
604 assert_eq!(
605 read_config(&b"!col foo"[..]).unwrap().static_columns,
a0577201 606 vec![Some("foo".to_owned())]
a411a19d 607 );
d669f60d
SW
608 assert_eq!(
609 read_config(&b"!label foo:bar"[..])
610 .unwrap()
611 .substitute_labels["foo"],
612 "bar"
613 );
e44de444 614
b2f31832
SW
615 let bad_command = read_config(&b"!no such command"[..]);
616 assert!(bad_command.is_err());
f105c5bc 617 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
b2f31832 618
e44de444
SW
619 let bad_num = read_config(&b"!col_threshold foo"[..]);
620 assert!(bad_num.is_err());
f105c5bc 621 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
d669f60d
SW
622
623 let bad_sub = read_config(&b"!label foo"[..]);
624 assert!(bad_sub.is_err());
625 assert!(format!("{bad_sub:?}").contains("line 1: Annotation missing ':'"));
e44de444
SW
626 }
627
f272e502
SW
628 #[test]
629 fn test_column_counts() {
630 assert_eq!(
12e91300 631 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
58b5f36d 632 vec![(1, String::from("bar")), (1, String::from("baz"))]
f272e502
SW
633 );
634 assert_eq!(
12e91300 635 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
38d1167a 636 vec![(2, String::from("baz")), (1, String::from("bar"))]
f272e502 637 );
397ef957 638 assert_eq!(
12e91300 639 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
38d1167a 640 vec![(2, String::from("baz")), (1, String::from("bar"))]
397ef957 641 );
b8907770
SW
642 assert_eq!(
643 column_counts(
12e91300 644 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
b8907770 645 ),
38d1167a 646 vec![(2, String::from("baz")), (1, String::from("bar"))]
b8907770 647 );
f272e502 648 }
de408c29 649
a638dfe7 650 #[test]
e3feb9dc 651 fn test_column_header_labels() {
a638dfe7
SW
652 let mut cfg = Config::default();
653
e3feb9dc 654 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"foo".to_owned())]));
a638dfe7
SW
655
656 cfg.static_columns.push(Some("bar".to_owned()));
e3feb9dc 657 assert!(column_header_labels(&cfg, &["foo".to_owned()])
a638dfe7
SW
658 .eq([Some(&"bar".to_owned()), Some(&"foo".to_owned())]));
659
660 cfg.static_columns.push(None);
e3feb9dc 661 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([
a638dfe7
SW
662 Some(&"bar".to_owned()),
663 None,
664 Some(&"foo".to_owned())
665 ]));
666
d669f60d
SW
667 cfg.substitute_labels
668 .insert("foo".to_owned(), "foo (bits)".to_owned());
669 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([
670 Some(&"bar".to_owned()),
671 None,
672 Some(&"foo (bits)".to_owned())
673 ]));
674
a638dfe7 675 cfg.hidden_columns.insert("foo".to_owned());
e3feb9dc 676 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"bar".to_owned()), None]));
a638dfe7
SW
677
678 cfg.hidden_columns.insert("bar".to_owned());
e3feb9dc 679 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([None]));
a638dfe7
SW
680 }
681
de408c29
SW
682 #[test]
683 fn test_render_cell() {
684 assert_eq!(
685 render_cell(
686 "foo",
d9bfcf4d 687 &mut Row {
88a08162
SW
688 label: "nope".to_owned(),
689 entries: HashMap::new(),
de408c29
SW
690 }
691 ),
5ffe8e3a
SW
692 HTML::from(
693 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
694 )
de408c29
SW
695 );
696 assert_eq!(
697 render_cell(
698 "foo",
d9bfcf4d 699 &mut Row {
88a08162
SW
700 label: "nope".to_owned(),
701 entries: HashMap::from([("bar".to_owned(), vec![None])]),
de408c29
SW
702 }
703 ),
5ffe8e3a
SW
704 HTML::from(
705 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
706 )
de408c29
SW
707 );
708 assert_eq!(
709 render_cell(
710 "foo",
d9bfcf4d 711 &mut Row {
88a08162
SW
712 label: "nope".to_owned(),
713 entries: HashMap::from([("foo".to_owned(), vec![None])]),
de408c29
SW
714 }
715 ),
5ffe8e3a 716 HTML::from(
f8c2cab2 717 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">𝍷</td>"#
5ffe8e3a 718 )
de408c29
SW
719 );
720 assert_eq!(
721 render_cell(
722 "foo",
d9bfcf4d 723 &mut Row {
88a08162
SW
724 label: "nope".to_owned(),
725 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
de408c29
SW
726 }
727 ),
5ffe8e3a 728 HTML::from(
f8c2cab2 729 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">𝍷𝍷</td>"#
5ffe8e3a 730 )
de408c29
SW
731 );
732 assert_eq!(
733 render_cell(
734 "foo",
d9bfcf4d 735 &mut Row {
88a08162 736 label: "nope".to_owned(),
5ffe8e3a
SW
737 entries: HashMap::from([(
738 "foo".to_owned(),
739 vec![Some("5".to_owned()), Some("10".to_owned())]
740 )]),
de408c29
SW
741 }
742 ),
5ffe8e3a
SW
743 HTML::from(
744 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
745 )
de408c29
SW
746 );
747 assert_eq!(
748 render_cell(
749 "foo",
d9bfcf4d 750 &mut Row {
88a08162
SW
751 label: "nope".to_owned(),
752 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
de408c29
SW
753 }
754 ),
5ffe8e3a 755 HTML::from(
f8c2cab2 756 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 𝍷</td>"#
5ffe8e3a 757 )
70436f23
SW
758 );
759 assert_eq!(
760 render_cell(
761 "heart",
d9bfcf4d 762 &mut Row {
88a08162
SW
763 label: "nope".to_owned(),
764 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
70436f23
SW
765 }
766 ),
5ffe8e3a
SW
767 HTML::from(
768 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')">&lt;3</td>"#
769 )
70436f23
SW
770 );
771 assert_eq!(
772 render_cell(
773 "foo",
d9bfcf4d 774 &mut Row {
88a08162
SW
775 label: "bob's".to_owned(),
776 entries: HashMap::from([("foo".to_owned(), vec![None])]),
70436f23
SW
777 }
778 ),
5ffe8e3a 779 HTML::from(
f8c2cab2 780 r#"<td class="yes" onmouseover="h2('bob&#39;s','foo')" onmouseout="ch2('bob&#39;s','foo')">𝍷</td>"#
5ffe8e3a 781 )
de408c29 782 );
d9bfcf4d
SW
783 let mut r = Row {
784 label: "nope".to_owned(),
785 entries: HashMap::from([
786 ("foo".to_owned(), vec![None]),
787 ("baz".to_owned(), vec![None]),
788 ]),
789 };
790 assert_eq!(r.entries.len(), 2);
791 render_cell("foo", &mut r);
792 assert_eq!(r.entries.len(), 1);
793 render_cell("bar", &mut r);
794 assert_eq!(r.entries.len(), 1);
795 render_cell("baz", &mut r);
796 assert_eq!(r.entries.len(), 0);
de408c29 797 }
25fd008e 798
9a626020
SW
799 #[test]
800 fn test_render_leftovers() {
801 assert_eq!(
b4bc28ba
SW
802 render_all_leftovers(
803 &Config::default(),
804 &Row {
805 label: "nope".to_owned(),
806 entries: HashMap::from([("foo".to_owned(), vec![None])]),
807 }
808 ),
9a626020
SW
809 HTML::from("foo")
810 );
811 assert_eq!(
b4bc28ba
SW
812 render_all_leftovers(
813 &Config::default(),
814 &Row {
815 label: "nope".to_owned(),
816 entries: HashMap::from([
817 ("foo".to_owned(), vec![None]),
818 ("bar".to_owned(), vec![None])
819 ]),
820 }
821 ),
9a626020
SW
822 HTML::from("bar, foo")
823 );
824 assert_eq!(
b4bc28ba
SW
825 render_all_leftovers(
826 &Config::default(),
827 &Row {
828 label: "nope".to_owned(),
829 entries: HashMap::from([
830 ("foo".to_owned(), vec![None]),
831 ("bar".to_owned(), vec![None, None])
832 ]),
833 }
834 ),
f8c2cab2 835 HTML::from("bar: 𝍷𝍷, foo")
9a626020 836 );
3135b2cd
SW
837 assert_eq!(
838 render_all_leftovers(
839 &Config {
840 column_threshold: 2,
841 static_columns: vec![],
842 hidden_columns: HashSet::from(["private".to_owned()]),
d669f60d 843 substitute_labels: HashMap::new(),
3135b2cd
SW
844 },
845 &Row {
846 label: "nope".to_owned(),
847 entries: HashMap::from([("private".to_owned(), vec![None]),]),
848 }
849 ),
850 HTML::from("")
851 );
9a626020
SW
852 }
853
25fd008e
SW
854 #[test]
855 fn test_render_row() {
856 assert_eq!(
857 render_row(
bc552978 858 &Config::default(),
25fd008e 859 &["foo".to_owned()],
06a6a5ca 860 &mut Rowlike::Row(Row {
25fd008e
SW
861 label: "nope".to_owned(),
862 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 863 })
25fd008e
SW
864 ),
865 HTML::from(
36bc3a39 866 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>
a411a19d
SW
867"#
868 )
869 );
870 assert_eq!(
871 render_row(
872 &Config {
873 column_threshold: 0,
a0577201 874 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
3135b2cd 875 hidden_columns: HashSet::new(),
d669f60d 876 substitute_labels: HashMap::new(),
a411a19d
SW
877 },
878 &["baz".to_owned()],
879 &mut Rowlike::Row(Row {
880 label: "nope".to_owned(),
881 entries: HashMap::from([
882 ("bar".to_owned(), vec![Some("r".to_owned())]),
883 ("baz".to_owned(), vec![Some("z".to_owned())]),
884 ("foo".to_owned(), vec![Some("f".to_owned())]),
885 ]),
886 })
887 ),
888 HTML::from(
889 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="yes" onmouseover="h2('nope','baz')" onmouseout="ch2('nope','baz')">z</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
a0577201
SW
890"#
891 )
892 );
893 assert_eq!(
894 render_row(
895 &Config {
896 column_threshold: 0,
897 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
3135b2cd 898 hidden_columns: HashSet::new(),
d669f60d 899 substitute_labels: HashMap::new(),
a0577201
SW
900 },
901 &[],
902 &mut Rowlike::Row(Row {
903 label: "nope".to_owned(),
904 entries: HashMap::from([
905 ("bar".to_owned(), vec![Some("r".to_owned())]),
906 ("foo".to_owned(), vec![Some("f".to_owned())]),
907 ]),
908 })
909 ),
910 HTML::from(
911 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="spacer_col"></td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
3135b2cd
SW
912"#
913 )
914 );
915 assert_eq!(
916 render_row(
917 &Config {
918 column_threshold: 0,
919 static_columns: vec![],
920 hidden_columns: HashSet::from(["foo".to_owned()]),
d669f60d 921 substitute_labels: HashMap::new(),
3135b2cd
SW
922 },
923 &[],
924 &mut Rowlike::Row(Row {
925 label: "nope".to_owned(),
926 entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]),
927 })
928 ),
929 HTML::from(
930 r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
931"#
932 )
933 );
934 assert_eq!(
935 render_row(
936 &Config {
937 column_threshold: 0,
938 static_columns: vec![Some("foo".to_owned())],
939 hidden_columns: HashSet::from(["foo".to_owned()]),
d669f60d 940 substitute_labels: HashMap::new(),
3135b2cd
SW
941 },
942 &[],
943 &mut Rowlike::Row(Row {
944 label: "nope".to_owned(),
945 entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]),
946 })
947 ),
948 HTML::from(
949 r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
25fd008e
SW
950"#
951 )
952 );
953 }
75bb888a 954}