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