]> git.scottworley.com Git - tablify/blame - src/lib.rs
Name the DEFAULT_CONFIG
[tablify] / src / lib.rs
CommitLineData
88a08162 1use std::borrow::ToOwned;
a411a19d 2use std::collections::{HashMap, HashSet};
7067975b 3use std::fmt::Write;
9dfa98b7 4use std::io::BufRead;
75bb888a
SW
5use std::iter::Iterator;
6
e44de444
SW
7#[derive(PartialEq, Eq, Debug)]
8struct Config {
9 column_threshold: usize,
a0577201 10 static_columns: Vec<Option<String>>,
e44de444
SW
11}
12impl Config {
f105c5bc 13 fn apply_command(&mut self, line_num: usize, cmd: &str) -> Result<(), std::io::Error> {
e44de444 14 if let Some(threshold) = cmd.strip_prefix("col_threshold ") {
f105c5bc
SW
15 self.column_threshold = threshold.parse().map_err(|e| {
16 std::io::Error::new(
17 std::io::ErrorKind::InvalidInput,
18 format!("line {line_num}: col_threshold must be numeric: {e}"),
19 )
20 })?;
a411a19d 21 } else if let Some(col) = cmd.strip_prefix("col ") {
a0577201
SW
22 self.static_columns.push(Some(col.to_owned()));
23 } else if cmd == "colsep" {
24 self.static_columns.push(None);
b2f31832
SW
25 } else {
26 return Err(std::io::Error::new(
27 std::io::ErrorKind::InvalidInput,
f105c5bc 28 format!("line {line_num}: Unknown command: {cmd}"),
b2f31832 29 ));
e44de444
SW
30 }
31 Ok(())
32 }
31af9aac 33}
28cf4fa2 34
71e34cc0
SW
35const DEFAULT_CONFIG: Config = Config {
36 column_threshold: 2,
37 static_columns: vec![],
38};
39
5ffe8e3a 40const HEADER: &str = r#"<!DOCTYPE html>
cc2378d5
SW
41<html>
42<head>
5ffe8e3a
SW
43 <meta charset="utf-8">
44 <meta name="viewport" content="width=device-width, initial-scale=1">
cc2378d5 45 <style>
b8b365ce 46 td { text-align: center; }
cc2378d5
SW
47 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
48 th, td { white-space: nowrap; }
49 th { text-align: left; font-weight: normal; }
529cbaa2 50 th.spacer_row { height: .3em; }
a0577201 51 .spacer_col { border: none; width: .2em; }
cc2378d5 52 table { border-collapse: collapse }
3bc643e9 53 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
cc2378d5
SW
54 tr.key > th > div { width: 1em; }
55 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
56 td { border: thin solid gray; }
36bc3a39 57 td.leftover { text-align: left; border: none; padding-left: .4em; }
1dda21e6 58 td.yes { border: thin solid gray; background-color: #ddd; }
cc2378d5
SW
59 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
60 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
cc2378d5
SW
61 </style>
62 <script>
5ffe8e3a
SW
63 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
64 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
cc2378d5
SW
65 function h2(a, b) { highlight(a); highlight(b); }
66 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
67 </script>
68</head>
69<body>
70 <table>
76638ea1 71 <tbody>
5ffe8e3a 72"#;
cc2378d5
SW
73const FOOTER: &str = " </tbody>
74 </table>
75</body>
76</html>";
77
70436f23
SW
78#[derive(PartialEq, Eq, Debug)]
79pub struct HTML(String);
80impl HTML {
81 fn escape(value: &str) -> HTML {
82 let mut escaped: String = String::new();
83 for c in value.chars() {
84 match c {
85 '>' => escaped.push_str("&gt;"),
86 '<' => escaped.push_str("&lt;"),
87 '\'' => escaped.push_str("&#39;"),
88 '"' => escaped.push_str("&quot;"),
89 '&' => escaped.push_str("&amp;"),
90 ok_c => escaped.push(ok_c),
91 }
92 }
93 HTML(escaped)
94 }
95}
96impl From<&str> for HTML {
97 fn from(value: &str) -> HTML {
98 HTML(String::from(value))
99 }
100}
101impl FromIterator<HTML> for HTML {
102 fn from_iter<T>(iter: T) -> HTML
103 where
104 T: IntoIterator<Item = HTML>,
105 {
106 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
107 }
108}
109impl std::fmt::Display for HTML {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 write!(f, "{}", self.0)
112 }
113}
114
88a08162
SW
115#[derive(Debug, PartialEq, Eq)]
116enum InputLine<'a> {
117 Blank,
118 RowHeader(&'a str),
119 Entry(&'a str, Option<&'a str>),
e44de444 120 Command(&'a str),
e8657dff 121}
88a08162
SW
122impl<'a> From<&'a str> for InputLine<'a> {
123 fn from(value: &'a str) -> InputLine<'a> {
124 let trimmed = value.trim_end();
125 if trimmed.is_empty() {
126 InputLine::Blank
e44de444
SW
127 } else if let Some(cmd) = trimmed.strip_prefix('!') {
128 InputLine::Command(cmd)
88a08162
SW
129 } else if !trimmed.starts_with(' ') {
130 InputLine::RowHeader(value.trim())
131 } else {
132 match value.split_once(':') {
133 None => InputLine::Entry(value.trim(), None),
134 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
135 }
e8657dff
SW
136 }
137 }
138}
14e9852b 139
75bb888a 140#[derive(Debug, PartialEq, Eq)]
88a08162
SW
141struct Row {
142 label: String,
143 entries: HashMap<String, Vec<Option<String>>>,
75bb888a
SW
144}
145
06a6a5ca
SW
146#[derive(Debug, PartialEq, Eq)]
147enum Rowlike {
148 Row(Row),
149 Spacer,
150}
151
e44de444 152struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
8110b492 153 input: std::iter::Enumerate<Input>,
88a08162 154 row: Option<Row>,
e44de444 155 config: &'cfg mut Config,
201b9ef3 156}
e44de444
SW
157impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
158 fn new(config: &'cfg mut Config, input: Input) -> Self {
8110b492
SW
159 Self {
160 input: input.enumerate(),
161 row: None,
e44de444 162 config,
8110b492 163 }
201b9ef3
SW
164 }
165}
e44de444
SW
166impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
167 for Reader<'cfg, Input>
168{
06a6a5ca 169 type Item = Result<Rowlike, std::io::Error>;
201b9ef3
SW
170 fn next(&mut self) -> Option<Self::Item> {
171 loop {
8bf0d5b1 172 match self.input.next() {
06a6a5ca 173 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
8110b492 174 Some((_, Err(e))) => return Some(Err(e)),
88a08162 175 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
e44de444 176 InputLine::Command(cmd) => {
f105c5bc 177 if let Err(e) = self.config.apply_command(n + 1, cmd) {
e44de444
SW
178 return Some(Err(e));
179 }
180 }
88a08162 181 InputLine::Blank if self.row.is_some() => {
06a6a5ca 182 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
8110b492 183 }
14a039db 184 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
88a08162
SW
185 InputLine::Entry(col, instance) => match &mut self.row {
186 None => {
187 return Some(Err(std::io::Error::other(format!(
1df4654a 188 "line {}: Entry with no header",
88a08162
SW
189 n + 1
190 ))))
191 }
192 Some(ref mut row) => {
193 row.entries
194 .entry(col.to_owned())
195 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
196 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
197 }
198 },
199 InputLine::RowHeader(row) => {
200 let prev = std::mem::take(&mut self.row);
201 self.row = Some(Row {
202 label: row.to_owned(),
203 entries: HashMap::new(),
204 });
205 if prev.is_some() {
06a6a5ca 206 return Ok(prev.map(Rowlike::Row)).transpose();
88a08162 207 }
201b9ef3 208 }
88a08162 209 },
201b9ef3
SW
210 }
211 }
212 }
213}
214
586b332a 215fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
71e34cc0 216 let mut config = DEFAULT_CONFIG;
e44de444
SW
217 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
218 reader
586b332a 219 .collect::<Result<Vec<_>, _>>()
e44de444 220 .map(|rows| (rows, config))
75bb888a
SW
221}
222
06a6a5ca
SW
223fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
224 let empty = HashMap::new();
58b5f36d
SW
225 let mut counts: Vec<_> = rows
226 .iter()
06a6a5ca
SW
227 .flat_map(|rl| match rl {
228 Rowlike::Row(r) => r.entries.keys(),
229 Rowlike::Spacer => empty.keys(),
230 })
b8907770 231 .fold(HashMap::new(), |mut cs, col| {
88a08162 232 cs.entry(col.to_owned())
58b5f36d 233 .and_modify(|n| *n += 1)
f272e502 234 .or_insert(1);
58b5f36d 235 cs
f272e502 236 })
58b5f36d
SW
237 .into_iter()
238 .map(|(col, n)| (n, col))
239 .collect();
38d1167a 240 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
58b5f36d 241 counts
f272e502 242}
06a6a5ca 243fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
a411a19d
SW
244 let static_columns: HashSet<&str> = config
245 .static_columns
246 .iter()
a0577201 247 .flatten()
a411a19d
SW
248 .map(std::string::String::as_str)
249 .collect();
d22b2e05
SW
250 column_counts(rows)
251 .into_iter()
a411a19d
SW
252 .filter_map(|(n, col)| {
253 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
254 })
d22b2e05
SW
255 .collect()
256}
f272e502 257
58c0a717 258fn render_one_instance(instance: &Option<String>) -> HTML {
88a08162 259 match instance {
70436f23
SW
260 None => HTML::from("✓"),
261 Some(instance) => HTML::escape(instance.as_ref()),
de408c29
SW
262 }
263}
264
f915bc90
SW
265fn render_instances(instances: &[Option<String>]) -> HTML {
266 let all_empty = instances.iter().all(Option::is_none);
267 if all_empty && instances.len() == 1 {
70436f23 268 HTML::from("")
de408c29 269 } else if all_empty {
f915bc90 270 HTML(format!("{}", instances.len()))
de408c29 271 } else {
70436f23 272 HTML(
88a08162 273 instances
70436f23 274 .iter()
58c0a717 275 .map(render_one_instance)
70436f23
SW
276 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
277 .collect::<Vec<_>>()
278 .join(" "),
279 )
f915bc90
SW
280 }
281}
282
283fn render_cell(col: &str, row: &mut Row) -> HTML {
284 let row_label = HTML::escape(row.label.as_ref());
285 let col_label = HTML::escape(col);
286 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
287 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
288 let contents = match instances {
289 None => HTML::from(""),
290 Some(is) => render_instances(is),
de408c29 291 };
d9bfcf4d 292 row.entries.remove(col);
5ffe8e3a
SW
293 HTML(format!(
294 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
295 ))
de408c29
SW
296}
297
9a626020
SW
298fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
299 let label = HTML::escape(notcol);
300 let rest = render_instances(instances);
301 if rest == HTML::from("") {
302 HTML(format!("{label}"))
303 } else {
304 HTML(format!("{label}: {rest}"))
305 }
306}
307
308fn render_all_leftovers(row: &Row) -> HTML {
309 let mut order: Vec<_> = row.entries.keys().collect();
310 order.sort_unstable();
311 HTML(
312 order
313 .into_iter()
314 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
315 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
316 .collect::<Vec<_>>()
317 .join(", "),
318 )
319}
320
215d38d5 321fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
06a6a5ca 322 match rowlike {
529cbaa2 323 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
06a6a5ca
SW
324 Rowlike::Row(row) => {
325 let row_label = HTML::escape(row.label.as_ref());
a411a19d
SW
326 let static_cells = config
327 .static_columns
328 .iter()
a0577201
SW
329 .map(|ocol| match ocol {
330 Some(col) => render_cell(col, row),
331 None => HTML::from(r#"<td class="spacer_col"></td>"#),
332 })
a411a19d
SW
333 .collect::<HTML>();
334 let dynamic_cells = columns
06a6a5ca
SW
335 .iter()
336 .map(|col| render_cell(col, row))
337 .collect::<HTML>();
338 let leftovers = render_all_leftovers(row);
339 HTML(format!(
a411a19d 340 "<tr><th id=\"{row_label}\">{row_label}</th>{static_cells}{dynamic_cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
06a6a5ca
SW
341 ))
342 }
343 }
de408c29
SW
344}
345
215d38d5 346fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
a0577201
SW
347 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
348 let dynamic_columns = columns.iter().map(Some);
70436f23 349 HTML(
5ffe8e3a 350 String::from(r#"<tr class="key"><th></th>"#)
a0577201
SW
351 + &static_columns
352 .chain(dynamic_columns)
353 .fold(String::new(), |mut acc, ocol| {
354 match ocol {
355 Some(col) => {
356 let col_header = HTML::escape(col);
357 write!(
358 &mut acc,
359 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
360 )
361 }
362 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
363 }
a411a19d
SW
364 .unwrap();
365 acc
a0577201 366 })
70436f23
SW
367 + "</tr>\n",
368 )
76638ea1
SW
369}
370
4b99fb70
SW
371/// # Errors
372///
373/// Will return `Err` if
374/// * there's an i/o error while reading `input`
375/// * the log has invalid syntax:
376/// * an indented line with no preceding non-indented line
586b332a
SW
377pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
378 let (rows, config) = read_input(input)?;
379 let columns = column_order(&config, &rows);
70436f23
SW
380 Ok(HTML(format!(
381 "{HEADER}{}{}{FOOTER}",
215d38d5 382 render_column_headers(&config, &columns),
70436f23 383 rows.into_iter()
215d38d5 384 .map(|mut r| render_row(&config, &columns, &mut r))
70436f23
SW
385 .collect::<HTML>()
386 )))
ece97615 387}
75bb888a
SW
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
b8907770 393 #[test]
88a08162
SW
394 fn test_parse_line() {
395 assert_eq!(InputLine::from(""), InputLine::Blank);
396 assert_eq!(InputLine::from(" "), InputLine::Blank);
397 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
398 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
399 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
b8907770 400 assert_eq!(
88a08162
SW
401 InputLine::from(" foo:bar"),
402 InputLine::Entry("foo", Some("bar"))
b8907770
SW
403 );
404 assert_eq!(
88a08162
SW
405 InputLine::from(" foo: bar"),
406 InputLine::Entry("foo", Some("bar"))
b8907770 407 );
0d999bc3 408 assert_eq!(
88a08162
SW
409 InputLine::from(" foo: bar "),
410 InputLine::Entry("foo", Some("bar"))
411 );
412 assert_eq!(
413 InputLine::from(" foo: bar "),
414 InputLine::Entry("foo", Some("bar"))
415 );
416 assert_eq!(
417 InputLine::from(" foo : bar "),
418 InputLine::Entry("foo", Some("bar"))
0d999bc3 419 );
b8907770
SW
420 }
421
586b332a
SW
422 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
423 read_input(input).map(|(rows, _)| rows)
424 }
e44de444
SW
425 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
426 read_input(input).map(|(_, config)| config)
427 }
75bb888a
SW
428 #[test]
429 fn test_read_rows() {
430 assert_eq!(
12e91300 431 read_rows(&b"foo"[..]).unwrap(),
06a6a5ca 432 vec![Rowlike::Row(Row {
88a08162
SW
433 label: "foo".to_owned(),
434 entries: HashMap::new(),
06a6a5ca 435 })]
75bb888a 436 );
9dfa98b7 437 assert_eq!(
12e91300 438 read_rows(&b"bar"[..]).unwrap(),
06a6a5ca 439 vec![Rowlike::Row(Row {
88a08162
SW
440 label: "bar".to_owned(),
441 entries: HashMap::new(),
06a6a5ca 442 })]
9dfa98b7 443 );
2aa9ef94 444 assert_eq!(
12e91300 445 read_rows(&b"foo\nbar\n"[..]).unwrap(),
2aa9ef94 446 vec![
06a6a5ca 447 Rowlike::Row(Row {
88a08162
SW
448 label: "foo".to_owned(),
449 entries: HashMap::new(),
06a6a5ca
SW
450 }),
451 Rowlike::Row(Row {
88a08162
SW
452 label: "bar".to_owned(),
453 entries: HashMap::new(),
06a6a5ca 454 })
2aa9ef94
SW
455 ]
456 );
201b9ef3 457 assert_eq!(
12e91300 458 read_rows(&b"foo\n bar\n"[..]).unwrap(),
06a6a5ca 459 vec![Rowlike::Row(Row {
88a08162
SW
460 label: "foo".to_owned(),
461 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 462 })]
201b9ef3
SW
463 );
464 assert_eq!(
12e91300 465 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
06a6a5ca 466 vec![Rowlike::Row(Row {
88a08162
SW
467 label: "foo".to_owned(),
468 entries: HashMap::from([
469 ("bar".to_owned(), vec![None]),
470 ("baz".to_owned(), vec![None])
471 ]),
06a6a5ca 472 })]
201b9ef3
SW
473 );
474 assert_eq!(
12e91300 475 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
722ea297
SW
476 vec![
477 Rowlike::Row(Row {
478 label: "foo".to_owned(),
479 entries: HashMap::new(),
480 }),
481 Rowlike::Row(Row {
482 label: "bar".to_owned(),
483 entries: HashMap::new(),
484 })
485 ]
486 );
487 assert_eq!(
12e91300 488 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
201b9ef3 489 vec![
06a6a5ca 490 Rowlike::Row(Row {
88a08162
SW
491 label: "foo".to_owned(),
492 entries: HashMap::new(),
06a6a5ca 493 }),
14a039db 494 Rowlike::Spacer,
06a6a5ca 495 Rowlike::Row(Row {
88a08162
SW
496 label: "bar".to_owned(),
497 entries: HashMap::new(),
06a6a5ca 498 })
201b9ef3
SW
499 ]
500 );
1f6bd845 501 assert_eq!(
12e91300 502 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
1f6bd845 503 vec![
06a6a5ca 504 Rowlike::Row(Row {
88a08162
SW
505 label: "foo".to_owned(),
506 entries: HashMap::new(),
06a6a5ca
SW
507 }),
508 Rowlike::Row(Row {
88a08162
SW
509 label: "bar".to_owned(),
510 entries: HashMap::new(),
06a6a5ca 511 })
1f6bd845
SW
512 ]
513 );
514 assert_eq!(
12e91300 515 read_rows(&b"foo \n bar \n"[..]).unwrap(),
06a6a5ca 516 vec![Rowlike::Row(Row {
88a08162
SW
517 label: "foo".to_owned(),
518 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 519 })]
1f6bd845 520 );
201b9ef3 521
12e91300 522 let bad = read_rows(&b" foo"[..]);
201b9ef3 523 assert!(bad.is_err());
1df4654a 524 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
201b9ef3 525
12e91300 526 let bad2 = read_rows(&b"foo\n\n bar"[..]);
201b9ef3 527 assert!(bad2.is_err());
1df4654a 528 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
75bb888a 529 }
f272e502 530
e44de444
SW
531 #[test]
532 fn test_read_config() {
533 assert_eq!(
fa8b5479
SW
534 read_config(&b"!col_threshold 10"[..])
535 .unwrap()
536 .column_threshold,
537 10
e44de444 538 );
a411a19d
SW
539 assert_eq!(
540 read_config(&b"!col foo"[..]).unwrap().static_columns,
a0577201 541 vec![Some("foo".to_owned())]
a411a19d 542 );
e44de444 543
b2f31832
SW
544 let bad_command = read_config(&b"!no such command"[..]);
545 assert!(bad_command.is_err());
f105c5bc 546 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
b2f31832 547
e44de444
SW
548 let bad_num = read_config(&b"!col_threshold foo"[..]);
549 assert!(bad_num.is_err());
f105c5bc 550 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
e44de444
SW
551 }
552
f272e502
SW
553 #[test]
554 fn test_column_counts() {
555 assert_eq!(
12e91300 556 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
58b5f36d 557 vec![(1, String::from("bar")), (1, String::from("baz"))]
f272e502
SW
558 );
559 assert_eq!(
12e91300 560 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
38d1167a 561 vec![(2, String::from("baz")), (1, String::from("bar"))]
f272e502 562 );
397ef957 563 assert_eq!(
12e91300 564 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
38d1167a 565 vec![(2, String::from("baz")), (1, String::from("bar"))]
397ef957 566 );
b8907770
SW
567 assert_eq!(
568 column_counts(
12e91300 569 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
b8907770 570 ),
38d1167a 571 vec![(2, String::from("baz")), (1, String::from("bar"))]
b8907770 572 );
f272e502 573 }
de408c29
SW
574
575 #[test]
576 fn test_render_cell() {
577 assert_eq!(
578 render_cell(
579 "foo",
d9bfcf4d 580 &mut Row {
88a08162
SW
581 label: "nope".to_owned(),
582 entries: HashMap::new(),
de408c29
SW
583 }
584 ),
5ffe8e3a
SW
585 HTML::from(
586 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
587 )
de408c29
SW
588 );
589 assert_eq!(
590 render_cell(
591 "foo",
d9bfcf4d 592 &mut Row {
88a08162
SW
593 label: "nope".to_owned(),
594 entries: HashMap::from([("bar".to_owned(), vec![None])]),
de408c29
SW
595 }
596 ),
5ffe8e3a
SW
597 HTML::from(
598 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
599 )
de408c29
SW
600 );
601 assert_eq!(
602 render_cell(
603 "foo",
d9bfcf4d 604 &mut Row {
88a08162
SW
605 label: "nope".to_owned(),
606 entries: HashMap::from([("foo".to_owned(), vec![None])]),
de408c29
SW
607 }
608 ),
5ffe8e3a
SW
609 HTML::from(
610 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
611 )
de408c29
SW
612 );
613 assert_eq!(
614 render_cell(
615 "foo",
d9bfcf4d 616 &mut Row {
88a08162
SW
617 label: "nope".to_owned(),
618 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
de408c29
SW
619 }
620 ),
5ffe8e3a
SW
621 HTML::from(
622 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
623 )
de408c29
SW
624 );
625 assert_eq!(
626 render_cell(
627 "foo",
d9bfcf4d 628 &mut Row {
88a08162 629 label: "nope".to_owned(),
5ffe8e3a
SW
630 entries: HashMap::from([(
631 "foo".to_owned(),
632 vec![Some("5".to_owned()), Some("10".to_owned())]
633 )]),
de408c29
SW
634 }
635 ),
5ffe8e3a
SW
636 HTML::from(
637 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
638 )
de408c29
SW
639 );
640 assert_eq!(
641 render_cell(
642 "foo",
d9bfcf4d 643 &mut Row {
88a08162
SW
644 label: "nope".to_owned(),
645 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
de408c29
SW
646 }
647 ),
5ffe8e3a
SW
648 HTML::from(
649 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
650 )
70436f23
SW
651 );
652 assert_eq!(
653 render_cell(
654 "heart",
d9bfcf4d 655 &mut Row {
88a08162
SW
656 label: "nope".to_owned(),
657 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
70436f23
SW
658 }
659 ),
5ffe8e3a
SW
660 HTML::from(
661 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')">&lt;3</td>"#
662 )
70436f23
SW
663 );
664 assert_eq!(
665 render_cell(
666 "foo",
d9bfcf4d 667 &mut Row {
88a08162
SW
668 label: "bob's".to_owned(),
669 entries: HashMap::from([("foo".to_owned(), vec![None])]),
70436f23
SW
670 }
671 ),
5ffe8e3a
SW
672 HTML::from(
673 r#"<td class="yes" onmouseover="h2('bob&#39;s','foo')" onmouseout="ch2('bob&#39;s','foo')"></td>"#
674 )
de408c29 675 );
d9bfcf4d
SW
676 let mut r = Row {
677 label: "nope".to_owned(),
678 entries: HashMap::from([
679 ("foo".to_owned(), vec![None]),
680 ("baz".to_owned(), vec![None]),
681 ]),
682 };
683 assert_eq!(r.entries.len(), 2);
684 render_cell("foo", &mut r);
685 assert_eq!(r.entries.len(), 1);
686 render_cell("bar", &mut r);
687 assert_eq!(r.entries.len(), 1);
688 render_cell("baz", &mut r);
689 assert_eq!(r.entries.len(), 0);
de408c29 690 }
25fd008e 691
9a626020
SW
692 #[test]
693 fn test_render_leftovers() {
694 assert_eq!(
695 render_all_leftovers(&Row {
696 label: "nope".to_owned(),
697 entries: HashMap::from([("foo".to_owned(), vec![None])]),
698 }),
699 HTML::from("foo")
700 );
701 assert_eq!(
702 render_all_leftovers(&Row {
703 label: "nope".to_owned(),
704 entries: HashMap::from([
705 ("foo".to_owned(), vec![None]),
706 ("bar".to_owned(), vec![None])
707 ]),
708 }),
709 HTML::from("bar, foo")
710 );
711 assert_eq!(
712 render_all_leftovers(&Row {
713 label: "nope".to_owned(),
714 entries: HashMap::from([
715 ("foo".to_owned(), vec![None]),
716 ("bar".to_owned(), vec![None, None])
717 ]),
718 }),
719 HTML::from("bar: 2, foo")
720 );
721 }
722
25fd008e
SW
723 #[test]
724 fn test_render_row() {
725 assert_eq!(
726 render_row(
71e34cc0 727 &DEFAULT_CONFIG,
25fd008e 728 &["foo".to_owned()],
06a6a5ca 729 &mut Rowlike::Row(Row {
25fd008e
SW
730 label: "nope".to_owned(),
731 entries: HashMap::from([("bar".to_owned(), vec![None])]),
06a6a5ca 732 })
25fd008e
SW
733 ),
734 HTML::from(
36bc3a39 735 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>
a411a19d
SW
736"#
737 )
738 );
739 assert_eq!(
740 render_row(
741 &Config {
742 column_threshold: 0,
a0577201 743 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
a411a19d
SW
744 },
745 &["baz".to_owned()],
746 &mut Rowlike::Row(Row {
747 label: "nope".to_owned(),
748 entries: HashMap::from([
749 ("bar".to_owned(), vec![Some("r".to_owned())]),
750 ("baz".to_owned(), vec![Some("z".to_owned())]),
751 ("foo".to_owned(), vec![Some("f".to_owned())]),
752 ]),
753 })
754 ),
755 HTML::from(
756 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="yes" onmouseover="h2('nope','baz')" onmouseout="ch2('nope','baz')">z</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>
a0577201
SW
757"#
758 )
759 );
760 assert_eq!(
761 render_row(
762 &Config {
763 column_threshold: 0,
764 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
765 },
766 &[],
767 &mut Rowlike::Row(Row {
768 label: "nope".to_owned(),
769 entries: HashMap::from([
770 ("bar".to_owned(), vec![Some("r".to_owned())]),
771 ("foo".to_owned(), vec![Some("f".to_owned())]),
772 ]),
773 })
774 ),
775 HTML::from(
776 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>
25fd008e
SW
777"#
778 )
779 );
780 }
75bb888a 781}