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