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