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