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