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