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