]> git.scottworley.com Git - tablify/blame - src/lib.rs
Start on 0.6.0
[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
ba61b04b 314fn render_cell(config: &Config, col: &str, row: &mut Row) -> HTML {
f915bc90 315 let row_label = HTML::escape(row.label.as_ref());
aa80485a
SW
316 let col_label = HTML::escape(
317 config
318 .substitute_labels
319 .get(col)
320 .map_or(col, std::string::String::as_str),
321 );
f915bc90 322 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
a1a4b3c8
SW
323 let is_empty = match instances {
324 None => true,
325 Some(is) => is.iter().all(|ins| match ins {
326 None => false,
327 Some(content) => content == "×",
328 }),
329 };
b59ad433 330 let class = HTML::from(if is_empty { "" } else { r#" class="yes""# });
f915bc90
SW
331 let contents = match instances {
332 None => HTML::from(""),
333 Some(is) => render_instances(is),
de408c29 334 };
d9bfcf4d 335 row.entries.remove(col);
5ffe8e3a 336 HTML(format!(
b59ad433 337 r#"<td{class} onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
5ffe8e3a 338 ))
de408c29
SW
339}
340
9a626020
SW
341fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
342 let label = HTML::escape(notcol);
f8c2cab2 343 if instances.len() == 1 && instances[0].is_none() {
9a626020
SW
344 HTML(format!("{label}"))
345 } else {
f8c2cab2 346 let rest = render_instances(instances);
9a626020
SW
347 HTML(format!("{label}: {rest}"))
348 }
349}
350
b4bc28ba 351fn render_all_leftovers(config: &Config, row: &Row) -> HTML {
3135b2cd
SW
352 let mut order: Vec<_> = row
353 .entries
354 .keys()
355 .filter(|&col| !config.hidden_columns.contains(col))
356 .collect();
9a626020
SW
357 order.sort_unstable();
358 HTML(
359 order
360 .into_iter()
361 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
362 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
363 .collect::<Vec<_>>()
364 .join(", "),
365 )
366}
367
215d38d5 368fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
06a6a5ca 369 match rowlike {
529cbaa2 370 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
06a6a5ca
SW
371 Rowlike::Row(row) => {
372 let row_label = HTML::escape(row.label.as_ref());
a411a19d
SW
373 let static_cells = config
374 .static_columns
375 .iter()
a0577201 376 .map(|ocol| match ocol {
3135b2cd 377 Some(col) if config.hidden_columns.contains(col) => HTML::from(""),
ba61b04b 378 Some(col) => render_cell(config, col, row),
a0577201
SW
379 None => HTML::from(r#"<td class="spacer_col"></td>"#),
380 })
a411a19d
SW
381 .collect::<HTML>();
382 let dynamic_cells = columns
06a6a5ca 383 .iter()
3135b2cd 384 .filter(|&col| !config.hidden_columns.contains(col))
ba61b04b 385 .map(|col| render_cell(config, col, row))
06a6a5ca 386 .collect::<HTML>();
b4bc28ba 387 let leftovers = render_all_leftovers(config, row);
06a6a5ca 388 HTML(format!(
a411a19d 389 "<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
390 ))
391 }
392 }
de408c29
SW
393}
394
e3feb9dc 395fn column_header_labels<'a>(
f93f5541
SW
396 config: &'a Config,
397 columns: &'a [String],
398) -> impl Iterator<Item = Option<&'a String>> {
a0577201
SW
399 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
400 let dynamic_columns = columns.iter().map(Some);
d669f60d
SW
401 static_columns
402 .chain(dynamic_columns)
403 .filter(|ocol| ocol.map_or(true, |col| !config.hidden_columns.contains(col)))
404 .map(|ocol| {
405 ocol.map(|col| match config.substitute_labels.get(col) {
406 None => col,
407 Some(substitute) => substitute,
408 })
409 })
f93f5541
SW
410}
411
412fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
70436f23 413 HTML(
5ffe8e3a 414 String::from(r#"<tr class="key"><th></th>"#)
e3feb9dc 415 + &column_header_labels(config, columns).fold(String::new(), |mut acc, ocol| {
f93f5541
SW
416 match ocol {
417 Some(col) => {
418 let col_header = HTML::escape(col);
419 write!(
420 &mut acc,
421 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
422 )
a0577201 423 }
f93f5541
SW
424 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
425 }
426 .unwrap();
427 acc
428 })
70436f23
SW
429 + "</tr>\n",
430 )
76638ea1
SW
431}
432
4b99fb70
SW
433/// # Errors
434///
435/// Will return `Err` if
436/// * there's an i/o error while reading `input`
437/// * the log has invalid syntax:
438/// * an indented line with no preceding non-indented line
586b332a
SW
439pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
440 let (rows, config) = read_input(input)?;
441 let columns = column_order(&config, &rows);
70436f23
SW
442 Ok(HTML(format!(
443 "{HEADER}{}{}{FOOTER}",
215d38d5 444 render_column_headers(&config, &columns),
70436f23 445 rows.into_iter()
215d38d5 446 .map(|mut r| render_row(&config, &columns, &mut r))
70436f23
SW
447 .collect::<HTML>()
448 )))
ece97615 449}
75bb888a
SW
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
b8907770 455 #[test]
88a08162
SW
456 fn test_parse_line() {
457 assert_eq!(InputLine::from(""), InputLine::Blank);
458 assert_eq!(InputLine::from(" "), InputLine::Blank);
459 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
460 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
461 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
b8907770 462 assert_eq!(
88a08162
SW
463 InputLine::from(" foo:bar"),
464 InputLine::Entry("foo", Some("bar"))
b8907770
SW
465 );
466 assert_eq!(
88a08162
SW
467 InputLine::from(" foo: bar"),
468 InputLine::Entry("foo", Some("bar"))
b8907770 469 );
0d999bc3 470 assert_eq!(
88a08162
SW
471 InputLine::from(" foo: bar "),
472 InputLine::Entry("foo", Some("bar"))
473 );
474 assert_eq!(
475 InputLine::from(" foo: bar "),
476 InputLine::Entry("foo", Some("bar"))
477 );
478 assert_eq!(
479 InputLine::from(" foo : bar "),
480 InputLine::Entry("foo", Some("bar"))
0d999bc3 481 );
b8907770
SW
482 }
483
f8c2cab2
SW
484 #[test]
485 fn test_tally_marks() {
486 assert_eq!(tally_marks(1), "𝍷");
487 assert_eq!(tally_marks(2), "𝍷𝍷");
488 assert_eq!(tally_marks(3), "𝍷𝍷𝍷");
489 assert_eq!(tally_marks(4), "𝍷𝍷𝍷𝍷");
490 assert_eq!(tally_marks(5), "𝍸");
491 assert_eq!(tally_marks(6), "𝍸𝍷");
492 assert_eq!(tally_marks(7), "𝍸𝍷𝍷");
493 assert_eq!(tally_marks(8), "𝍸𝍷𝍷𝍷");
494 assert_eq!(tally_marks(9), "𝍸𝍷𝍷𝍷𝍷");
495 assert_eq!(tally_marks(10), "𝍸𝍸");
496 assert_eq!(tally_marks(11), "𝍸𝍸𝍷");
497 }
498
586b332a
SW
499 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
500 read_input(input).map(|(rows, _)| rows)
501 }
e44de444
SW
502 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
503 read_input(input).map(|(_, config)| config)
504 }
75bb888a
SW
505 #[test]
506 fn test_read_rows() {
507 assert_eq!(
12e91300 508 read_rows(&b"foo"[..]).unwrap(),
06a6a5ca 509 vec![Rowlike::Row(Row {
88a08162
SW
510 label: "foo".to_owned(),
511 entries: HashMap::new(),
06a6a5ca 512 })]
75bb888a 513 );
9dfa98b7 514 assert_eq!(
12e91300 515 read_rows(&b"bar"[..]).unwrap(),
06a6a5ca 516 vec![Rowlike::Row(Row {
88a08162
SW
517 label: "bar".to_owned(),
518 entries: HashMap::new(),
06a6a5ca 519 })]
9dfa98b7 520 );
2aa9ef94 521 assert_eq!(
12e91300 522 read_rows(&b"foo\nbar\n"[..]).unwrap(),
2aa9ef94 523 vec![
06a6a5ca 524 Rowlike::Row(Row {
88a08162
SW
525 label: "foo".to_owned(),
526 entries: HashMap::new(),
06a6a5ca
SW
527 }),
528 Rowlike::Row(Row {
88a08162
SW
529 label: "bar".to_owned(),
530 entries: HashMap::new(),
06a6a5ca 531 })
2aa9ef94
SW
532 ]
533 );
201b9ef3 534 assert_eq!(
12e91300 535 read_rows(&b"foo\n bar\n"[..]).unwrap(),
06a6a5ca 536 vec![Rowlike::Row(Row {
88a08162
SW
537 label: "foo".to_owned(),
538 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 539 })]
201b9ef3
SW
540 );
541 assert_eq!(
12e91300 542 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
06a6a5ca 543 vec![Rowlike::Row(Row {
88a08162
SW
544 label: "foo".to_owned(),
545 entries: HashMap::from([
546 ("bar".to_owned(), vec![None]),
547 ("baz".to_owned(), vec![None])
548 ]),
06a6a5ca 549 })]
201b9ef3
SW
550 );
551 assert_eq!(
12e91300 552 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
722ea297
SW
553 vec![
554 Rowlike::Row(Row {
555 label: "foo".to_owned(),
556 entries: HashMap::new(),
557 }),
558 Rowlike::Row(Row {
559 label: "bar".to_owned(),
560 entries: HashMap::new(),
561 })
562 ]
563 );
564 assert_eq!(
12e91300 565 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
201b9ef3 566 vec![
06a6a5ca 567 Rowlike::Row(Row {
88a08162
SW
568 label: "foo".to_owned(),
569 entries: HashMap::new(),
06a6a5ca 570 }),
14a039db 571 Rowlike::Spacer,
06a6a5ca 572 Rowlike::Row(Row {
88a08162
SW
573 label: "bar".to_owned(),
574 entries: HashMap::new(),
06a6a5ca 575 })
201b9ef3
SW
576 ]
577 );
1f6bd845 578 assert_eq!(
12e91300 579 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
1f6bd845 580 vec![
06a6a5ca 581 Rowlike::Row(Row {
88a08162
SW
582 label: "foo".to_owned(),
583 entries: HashMap::new(),
06a6a5ca
SW
584 }),
585 Rowlike::Row(Row {
88a08162
SW
586 label: "bar".to_owned(),
587 entries: HashMap::new(),
06a6a5ca 588 })
1f6bd845
SW
589 ]
590 );
591 assert_eq!(
12e91300 592 read_rows(&b"foo \n bar \n"[..]).unwrap(),
06a6a5ca 593 vec![Rowlike::Row(Row {
88a08162
SW
594 label: "foo".to_owned(),
595 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 596 })]
1f6bd845 597 );
201b9ef3 598
12e91300 599 let bad = read_rows(&b" foo"[..]);
201b9ef3 600 assert!(bad.is_err());
1df4654a 601 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
201b9ef3 602
12e91300 603 let bad2 = read_rows(&b"foo\n\n bar"[..]);
201b9ef3 604 assert!(bad2.is_err());
1df4654a 605 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
75bb888a 606 }
f272e502 607
e44de444
SW
608 #[test]
609 fn test_read_config() {
610 assert_eq!(
fa8b5479
SW
611 read_config(&b"!col_threshold 10"[..])
612 .unwrap()
613 .column_threshold,
614 10
e44de444 615 );
a411a19d
SW
616 assert_eq!(
617 read_config(&b"!col foo"[..]).unwrap().static_columns,
a0577201 618 vec![Some("foo".to_owned())]
a411a19d 619 );
d669f60d
SW
620 assert_eq!(
621 read_config(&b"!label foo:bar"[..])
622 .unwrap()
623 .substitute_labels["foo"],
624 "bar"
625 );
e44de444 626
b2f31832
SW
627 let bad_command = read_config(&b"!no such command"[..]);
628 assert!(bad_command.is_err());
f105c5bc 629 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
b2f31832 630
e44de444
SW
631 let bad_num = read_config(&b"!col_threshold foo"[..]);
632 assert!(bad_num.is_err());
f105c5bc 633 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
d669f60d
SW
634
635 let bad_sub = read_config(&b"!label foo"[..]);
636 assert!(bad_sub.is_err());
637 assert!(format!("{bad_sub:?}").contains("line 1: Annotation missing ':'"));
e44de444
SW
638 }
639
f272e502
SW
640 #[test]
641 fn test_column_counts() {
642 assert_eq!(
12e91300 643 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
58b5f36d 644 vec![(1, String::from("bar")), (1, String::from("baz"))]
f272e502
SW
645 );
646 assert_eq!(
12e91300 647 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
38d1167a 648 vec![(2, String::from("baz")), (1, String::from("bar"))]
f272e502 649 );
397ef957 650 assert_eq!(
12e91300 651 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
38d1167a 652 vec![(2, String::from("baz")), (1, String::from("bar"))]
397ef957 653 );
b8907770
SW
654 assert_eq!(
655 column_counts(
12e91300 656 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
b8907770 657 ),
38d1167a 658 vec![(2, String::from("baz")), (1, String::from("bar"))]
b8907770 659 );
f272e502 660 }
de408c29 661
a638dfe7 662 #[test]
e3feb9dc 663 fn test_column_header_labels() {
a638dfe7
SW
664 let mut cfg = Config::default();
665
e3feb9dc 666 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"foo".to_owned())]));
a638dfe7
SW
667
668 cfg.static_columns.push(Some("bar".to_owned()));
e3feb9dc 669 assert!(column_header_labels(&cfg, &["foo".to_owned()])
a638dfe7
SW
670 .eq([Some(&"bar".to_owned()), Some(&"foo".to_owned())]));
671
672 cfg.static_columns.push(None);
e3feb9dc 673 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([
a638dfe7
SW
674 Some(&"bar".to_owned()),
675 None,
676 Some(&"foo".to_owned())
677 ]));
678
d669f60d
SW
679 cfg.substitute_labels
680 .insert("foo".to_owned(), "foo (bits)".to_owned());
681 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([
682 Some(&"bar".to_owned()),
683 None,
684 Some(&"foo (bits)".to_owned())
685 ]));
686
a638dfe7 687 cfg.hidden_columns.insert("foo".to_owned());
e3feb9dc 688 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"bar".to_owned()), None]));
a638dfe7
SW
689
690 cfg.hidden_columns.insert("bar".to_owned());
e3feb9dc 691 assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([None]));
a638dfe7
SW
692 }
693
de408c29
SW
694 #[test]
695 fn test_render_cell() {
696 assert_eq!(
697 render_cell(
ba61b04b 698 &Config::default(),
de408c29 699 "foo",
d9bfcf4d 700 &mut Row {
88a08162
SW
701 label: "nope".to_owned(),
702 entries: HashMap::new(),
de408c29
SW
703 }
704 ),
5ffe8e3a 705 HTML::from(
b59ad433 706 r#"<td onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
5ffe8e3a 707 )
de408c29
SW
708 );
709 assert_eq!(
710 render_cell(
ba61b04b 711 &Config::default(),
de408c29 712 "foo",
d9bfcf4d 713 &mut Row {
88a08162
SW
714 label: "nope".to_owned(),
715 entries: HashMap::from([("bar".to_owned(), vec![None])]),
de408c29
SW
716 }
717 ),
5ffe8e3a 718 HTML::from(
b59ad433 719 r#"<td onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
5ffe8e3a 720 )
de408c29
SW
721 );
722 assert_eq!(
723 render_cell(
ba61b04b 724 &Config::default(),
de408c29 725 "foo",
d9bfcf4d 726 &mut Row {
88a08162
SW
727 label: "nope".to_owned(),
728 entries: HashMap::from([("foo".to_owned(), vec![None])]),
de408c29
SW
729 }
730 ),
5ffe8e3a 731 HTML::from(
f8c2cab2 732 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">𝍷</td>"#
5ffe8e3a 733 )
de408c29
SW
734 );
735 assert_eq!(
736 render_cell(
ba61b04b 737 &Config::default(),
de408c29 738 "foo",
d9bfcf4d 739 &mut Row {
88a08162
SW
740 label: "nope".to_owned(),
741 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
de408c29
SW
742 }
743 ),
5ffe8e3a 744 HTML::from(
f8c2cab2 745 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">𝍷𝍷</td>"#
5ffe8e3a 746 )
de408c29
SW
747 );
748 assert_eq!(
749 render_cell(
ba61b04b 750 &Config::default(),
de408c29 751 "foo",
d9bfcf4d 752 &mut Row {
88a08162 753 label: "nope".to_owned(),
5ffe8e3a
SW
754 entries: HashMap::from([(
755 "foo".to_owned(),
756 vec![Some("5".to_owned()), Some("10".to_owned())]
757 )]),
de408c29
SW
758 }
759 ),
5ffe8e3a
SW
760 HTML::from(
761 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
762 )
de408c29
SW
763 );
764 assert_eq!(
765 render_cell(
ba61b04b 766 &Config::default(),
de408c29 767 "foo",
d9bfcf4d 768 &mut Row {
88a08162
SW
769 label: "nope".to_owned(),
770 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
de408c29
SW
771 }
772 ),
5ffe8e3a 773 HTML::from(
f8c2cab2 774 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 𝍷</td>"#
5ffe8e3a 775 )
70436f23 776 );
a1a4b3c8
SW
777 assert_eq!(
778 render_cell(
ba61b04b 779 &Config::default(),
a1a4b3c8
SW
780 "foo",
781 &mut Row {
782 label: "nope".to_owned(),
783 entries: HashMap::from([("foo".to_owned(), vec![Some("×".to_owned())])]),
784 }
785 ),
786 HTML::from(
b59ad433 787 r#"<td onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">×</td>"#
a1a4b3c8
SW
788 )
789 );
70436f23
SW
790 assert_eq!(
791 render_cell(
ba61b04b 792 &Config::default(),
70436f23 793 "heart",
d9bfcf4d 794 &mut Row {
88a08162
SW
795 label: "nope".to_owned(),
796 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
70436f23
SW
797 }
798 ),
5ffe8e3a
SW
799 HTML::from(
800 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')">&lt;3</td>"#
801 )
70436f23
SW
802 );
803 assert_eq!(
804 render_cell(
ba61b04b 805 &Config::default(),
70436f23 806 "foo",
d9bfcf4d 807 &mut Row {
88a08162
SW
808 label: "bob's".to_owned(),
809 entries: HashMap::from([("foo".to_owned(), vec![None])]),
70436f23
SW
810 }
811 ),
5ffe8e3a 812 HTML::from(
f8c2cab2 813 r#"<td class="yes" onmouseover="h2('bob&#39;s','foo')" onmouseout="ch2('bob&#39;s','foo')">𝍷</td>"#
5ffe8e3a 814 )
de408c29 815 );
d9bfcf4d
SW
816 let mut r = Row {
817 label: "nope".to_owned(),
818 entries: HashMap::from([
819 ("foo".to_owned(), vec![None]),
820 ("baz".to_owned(), vec![None]),
821 ]),
822 };
823 assert_eq!(r.entries.len(), 2);
ba61b04b 824 render_cell(&Config::default(), "foo", &mut r);
d9bfcf4d 825 assert_eq!(r.entries.len(), 1);
ba61b04b 826 render_cell(&Config::default(), "bar", &mut r);
d9bfcf4d 827 assert_eq!(r.entries.len(), 1);
ba61b04b 828 render_cell(&Config::default(), "baz", &mut r);
d9bfcf4d 829 assert_eq!(r.entries.len(), 0);
de408c29 830 }
25fd008e 831
9a626020
SW
832 #[test]
833 fn test_render_leftovers() {
834 assert_eq!(
b4bc28ba
SW
835 render_all_leftovers(
836 &Config::default(),
837 &Row {
838 label: "nope".to_owned(),
839 entries: HashMap::from([("foo".to_owned(), vec![None])]),
840 }
841 ),
9a626020
SW
842 HTML::from("foo")
843 );
844 assert_eq!(
b4bc28ba
SW
845 render_all_leftovers(
846 &Config::default(),
847 &Row {
848 label: "nope".to_owned(),
849 entries: HashMap::from([
850 ("foo".to_owned(), vec![None]),
851 ("bar".to_owned(), vec![None])
852 ]),
853 }
854 ),
9a626020
SW
855 HTML::from("bar, foo")
856 );
857 assert_eq!(
b4bc28ba
SW
858 render_all_leftovers(
859 &Config::default(),
860 &Row {
861 label: "nope".to_owned(),
862 entries: HashMap::from([
863 ("foo".to_owned(), vec![None]),
864 ("bar".to_owned(), vec![None, None])
865 ]),
866 }
867 ),
f8c2cab2 868 HTML::from("bar: 𝍷𝍷, foo")
9a626020 869 );
3135b2cd
SW
870 assert_eq!(
871 render_all_leftovers(
872 &Config {
873 column_threshold: 2,
874 static_columns: vec![],
875 hidden_columns: HashSet::from(["private".to_owned()]),
d669f60d 876 substitute_labels: HashMap::new(),
3135b2cd
SW
877 },
878 &Row {
879 label: "nope".to_owned(),
880 entries: HashMap::from([("private".to_owned(), vec![None]),]),
881 }
882 ),
883 HTML::from("")
884 );
9a626020
SW
885 }
886
25fd008e
SW
887 #[test]
888 fn test_render_row() {
889 assert_eq!(
890 render_row(
bc552978 891 &Config::default(),
25fd008e 892 &["foo".to_owned()],
06a6a5ca 893 &mut Rowlike::Row(Row {
25fd008e
SW
894 label: "nope".to_owned(),
895 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 896 })
25fd008e
SW
897 ),
898 HTML::from(
b59ad433 899 r#"<tr><th id="nope">nope</th><td onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')">bar</td></tr>
a411a19d
SW
900"#
901 )
902 );
903 assert_eq!(
904 render_row(
905 &Config {
906 column_threshold: 0,
a0577201 907 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
3135b2cd 908 hidden_columns: HashSet::new(),
d669f60d 909 substitute_labels: HashMap::new(),
a411a19d
SW
910 },
911 &["baz".to_owned()],
912 &mut Rowlike::Row(Row {
913 label: "nope".to_owned(),
914 entries: HashMap::from([
915 ("bar".to_owned(), vec![Some("r".to_owned())]),
916 ("baz".to_owned(), vec![Some("z".to_owned())]),
917 ("foo".to_owned(), vec![Some("f".to_owned())]),
918 ]),
919 })
920 ),
921 HTML::from(
922 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
923"#
924 )
925 );
926 assert_eq!(
927 render_row(
928 &Config {
929 column_threshold: 0,
930 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
3135b2cd 931 hidden_columns: HashSet::new(),
d669f60d 932 substitute_labels: HashMap::new(),
a0577201
SW
933 },
934 &[],
935 &mut Rowlike::Row(Row {
936 label: "nope".to_owned(),
937 entries: HashMap::from([
938 ("bar".to_owned(), vec![Some("r".to_owned())]),
939 ("foo".to_owned(), vec![Some("f".to_owned())]),
940 ]),
941 })
942 ),
943 HTML::from(
944 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
945"#
946 )
947 );
948 assert_eq!(
949 render_row(
950 &Config {
951 column_threshold: 0,
952 static_columns: vec![],
953 hidden_columns: HashSet::from(["foo".to_owned()]),
d669f60d 954 substitute_labels: HashMap::new(),
3135b2cd
SW
955 },
956 &[],
957 &mut Rowlike::Row(Row {
958 label: "nope".to_owned(),
959 entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]),
960 })
961 ),
962 HTML::from(
963 r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
964"#
965 )
966 );
967 assert_eq!(
968 render_row(
969 &Config {
970 column_threshold: 0,
971 static_columns: vec![Some("foo".to_owned())],
972 hidden_columns: HashSet::from(["foo".to_owned()]),
d669f60d 973 substitute_labels: HashMap::new(),
3135b2cd
SW
974 },
975 &[],
976 &mut Rowlike::Row(Row {
977 label: "nope".to_owned(),
978 entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]),
979 })
980 ),
981 HTML::from(
982 r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
aa80485a
SW
983"#
984 )
985 );
986 assert_eq!(
987 render_row(
988 &Config {
989 column_threshold: 0,
990 static_columns: vec![],
991 hidden_columns: HashSet::new(),
992 substitute_labels: HashMap::from([("foo".to_owned(), "bar".to_owned())]),
993 },
994 &["foo".to_owned()],
995 &mut Rowlike::Row(Row {
996 label: "nope".to_owned(),
997 entries: HashMap::from([("foo".to_owned(), vec![None])]),
998 })
999 ),
1000 HTML::from(
1001 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">𝍷</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
25fd008e
SW
1002"#
1003 )
1004 );
1005 }
75bb888a 1006}