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