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