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