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