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