]> git.scottworley.com Git - tablify/blob - src/lib.rs
Set ids, add divs & triggers to engage with the CSS & JS
[tablify] / src / lib.rs
1 use std::collections::{HashMap, HashSet};
2 use std::fmt::Write;
3 use std::io::BufRead;
4 use std::iter::Iterator;
5
6 const HEADER: &str = "<!DOCTYPE html>
7 <html>
8 <head>
9 <meta charset=\"utf-8\">
10 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
11 <style>
12 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
13 th, td { white-space: nowrap; }
14 th { text-align: left; font-weight: normal; }
15 table { border-collapse: collapse }
16 tr.key > th { height: 8em; vertical-align: bottom; line-height: 1 }
17 tr.key > th > div { width: 1em; }
18 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
19 td { border: thin solid gray; }
20 td.numeric { text-align: right; }
21 td.yes { border: thin solid gray; background-color: #ddd; }
22 td.spacer { border: none; }
23 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
24 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
25 img { height: 1.2em; }
26 </style>
27 <script>
28 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } }
29 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } }
30 function h2(a, b) { highlight(a); highlight(b); }
31 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
32 </script>
33 </head>
34 <body>
35 <table>
36 <tbody>
37 ";
38 const FOOTER: &str = " </tbody>
39 </table>
40 </body>
41 </html>";
42
43 #[derive(Debug, PartialEq, Eq, Hash)]
44 struct Entry {
45 col: String,
46 instance: Option<String>,
47 }
48 impl From<&str> for Entry {
49 fn from(value: &str) -> Entry {
50 match value.split_once(':') {
51 None => Entry {
52 col: String::from(value),
53 instance: None,
54 },
55 Some((col, instance)) => Entry {
56 col: String::from(col.trim()),
57 instance: Some(String::from(instance.trim())),
58 },
59 }
60 }
61 }
62
63 #[derive(Debug, PartialEq, Eq)]
64 struct RowInput {
65 label: String,
66 entries: Vec<Entry>,
67 }
68
69 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
70 input: std::iter::Enumerate<Input>,
71 row: Option<RowInput>,
72 }
73 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
74 fn new(input: Input) -> Self {
75 Self {
76 input: input.enumerate(),
77 row: None,
78 }
79 }
80 }
81 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
82 type Item = Result<RowInput, std::io::Error>;
83 fn next(&mut self) -> Option<Self::Item> {
84 loop {
85 match self
86 .input
87 .next()
88 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
89 {
90 None => return Ok(std::mem::take(&mut self.row)).transpose(),
91 Some((_, Err(e))) => return Some(Err(e)),
92 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
93 return Ok(std::mem::take(&mut self.row)).transpose()
94 }
95 Some((_, Ok(line))) if line.is_empty() => {}
96 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
97 None => {
98 return Some(Err(std::io::Error::other(format!(
99 "{}: Entry with no header",
100 n + 1
101 ))))
102 }
103 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
104 },
105 Some((_, Ok(line))) => {
106 let prev = std::mem::take(&mut self.row);
107 self.row = Some(RowInput {
108 label: line,
109 entries: vec![],
110 });
111 if prev.is_some() {
112 return Ok(prev).transpose();
113 }
114 }
115 }
116 }
117 }
118 }
119
120 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
121 Reader::new(std::io::BufReader::new(input).lines())
122 }
123
124 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
125 let mut counts: Vec<_> = rows
126 .iter()
127 .flat_map(|r| {
128 r.entries
129 .iter()
130 .map(|e| &e.col)
131 .collect::<HashSet<_>>()
132 .into_iter()
133 })
134 .fold(HashMap::new(), |mut cs, col| {
135 cs.entry(String::from(col))
136 .and_modify(|n| *n += 1)
137 .or_insert(1);
138 cs
139 })
140 .into_iter()
141 .map(|(col, n)| (n, col))
142 .collect();
143 counts.sort();
144 counts
145 }
146 fn column_order(rows: &[RowInput]) -> Vec<String> {
147 column_counts(rows)
148 .into_iter()
149 .map(|(_, col)| col)
150 .collect()
151 }
152
153 fn render_instance(entry: &Entry) -> String {
154 match &entry.instance {
155 None => String::from("✓ "),
156 Some(instance) => String::from(instance) + " ",
157 }
158 }
159
160 fn render_cell(col: &str, row: &RowInput) -> String {
161 // TODO: Escape HTML special characters
162 let row_label = &row.label;
163 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
164 let class = if entries.is_empty() { "" } else { "yes" };
165 let all_empty = entries.iter().all(|e| e.instance.is_none());
166 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
167 String::new()
168 } else if all_empty {
169 format!("{}", entries.len())
170 } else {
171 entries
172 .iter()
173 .map(|i| render_instance(i))
174 .collect::<String>()
175 };
176 format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col}')\" onmouseout=\"ch2('{row_label}','{col}')\">{}</td>", contents.trim())
177 }
178
179 fn render_row(columns: &[String], row: &RowInput) -> String {
180 // This is O(n^2) & doesn't need to be
181 // TODO: Escape HTML special characters
182 let row_label = &row.label;
183 format!(
184 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
185 &columns
186 .iter()
187 .map(|col| render_cell(col, row))
188 .collect::<String>()
189 )
190 }
191
192 fn render_column_headers(columns: &[String]) -> String {
193 // TODO: Escape HTML special characters
194 String::from("<tr class=\"key\"><th></th>")
195 + &columns.iter().fold(String::new(), |mut acc, c| {
196 write!(&mut acc, "<th id=\"{c}\"><div><div>{c}</div></div></th>").unwrap();
197 acc
198 })
199 + "</tr>\n"
200 }
201
202 /// # Errors
203 ///
204 /// Will return `Err` if
205 /// * there's an i/o error while reading `input`
206 /// * the log has invalid syntax:
207 /// * an indented line with no preceding non-indented line
208 pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> {
209 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
210 let columns = column_order(&rows);
211 Ok(String::from(HEADER)
212 + &render_column_headers(&columns)
213 + &rows
214 .into_iter()
215 .map(|r| render_row(&columns, &r))
216 .collect::<String>()
217 + FOOTER)
218 }
219
220 #[cfg(test)]
221 mod tests {
222 use super::*;
223
224 #[test]
225 fn test_parse_entry() {
226 assert_eq!(
227 Entry::from("foo"),
228 Entry {
229 col: String::from("foo"),
230 instance: None
231 }
232 );
233 assert_eq!(
234 Entry::from("foo:bar"),
235 Entry {
236 col: String::from("foo"),
237 instance: Some(String::from("bar"))
238 }
239 );
240 assert_eq!(
241 Entry::from("foo: bar"),
242 Entry {
243 col: String::from("foo"),
244 instance: Some(String::from("bar"))
245 }
246 );
247 }
248
249 #[test]
250 fn test_read_rows() {
251 assert_eq!(
252 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
253 vec![RowInput {
254 label: String::from("foo"),
255 entries: vec![]
256 }]
257 );
258 assert_eq!(
259 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
260 vec![RowInput {
261 label: String::from("bar"),
262 entries: vec![]
263 }]
264 );
265 assert_eq!(
266 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
267 vec![
268 RowInput {
269 label: String::from("foo"),
270 entries: vec![]
271 },
272 RowInput {
273 label: String::from("bar"),
274 entries: vec![]
275 }
276 ]
277 );
278 assert_eq!(
279 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
280 vec![RowInput {
281 label: String::from("foo"),
282 entries: vec![Entry::from("bar")]
283 }]
284 );
285 assert_eq!(
286 read_rows(&b"foo\n bar\n baz\n"[..])
287 .flatten()
288 .collect::<Vec<_>>(),
289 vec![RowInput {
290 label: String::from("foo"),
291 entries: vec![Entry::from("bar"), Entry::from("baz")]
292 }]
293 );
294 assert_eq!(
295 read_rows(&b"foo\n\nbar\n"[..])
296 .flatten()
297 .collect::<Vec<_>>(),
298 vec![
299 RowInput {
300 label: String::from("foo"),
301 entries: vec![]
302 },
303 RowInput {
304 label: String::from("bar"),
305 entries: vec![]
306 }
307 ]
308 );
309 assert_eq!(
310 read_rows(&b"foo\n \nbar\n"[..])
311 .flatten()
312 .collect::<Vec<_>>(),
313 vec![
314 RowInput {
315 label: String::from("foo"),
316 entries: vec![]
317 },
318 RowInput {
319 label: String::from("bar"),
320 entries: vec![]
321 }
322 ]
323 );
324 assert_eq!(
325 read_rows(&b"foo \n bar \n"[..])
326 .flatten()
327 .collect::<Vec<_>>(),
328 vec![RowInput {
329 label: String::from("foo"),
330 entries: vec![Entry::from("bar")]
331 }]
332 );
333
334 let bad = read_rows(&b" foo"[..]).next().unwrap();
335 assert!(bad.is_err());
336 assert!(format!("{bad:?}").contains("1: Entry with no header"));
337
338 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
339 assert!(bad2.is_err());
340 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
341 }
342
343 #[test]
344 fn test_column_counts() {
345 assert_eq!(
346 column_counts(
347 &read_rows(&b"foo\n bar\n baz\n"[..])
348 .collect::<Result<Vec<_>, _>>()
349 .unwrap()
350 ),
351 vec![(1, String::from("bar")), (1, String::from("baz"))]
352 );
353 assert_eq!(
354 column_counts(
355 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
356 .collect::<Result<Vec<_>, _>>()
357 .unwrap()
358 ),
359 vec![(1, String::from("bar")), (2, String::from("baz"))]
360 );
361 assert_eq!(
362 column_counts(
363 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
364 .collect::<Result<Vec<_>, _>>()
365 .unwrap()
366 ),
367 vec![(1, String::from("bar")), (2, String::from("baz"))]
368 );
369 assert_eq!(
370 column_counts(
371 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
372 .collect::<Result<Vec<_>, _>>()
373 .unwrap()
374 ),
375 vec![(1, String::from("bar")), (2, String::from("baz"))]
376 );
377 }
378
379 #[test]
380 fn test_render_cell() {
381 assert_eq!(
382 render_cell(
383 "foo",
384 &RowInput {
385 label: String::from("nope"),
386 entries: vec![]
387 }
388 ),
389 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
390 );
391 assert_eq!(
392 render_cell(
393 "foo",
394 &RowInput {
395 label: String::from("nope"),
396 entries: vec![Entry::from("bar")]
397 }
398 ),
399 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
400 );
401 assert_eq!(
402 render_cell(
403 "foo",
404 &RowInput {
405 label: String::from("nope"),
406 entries: vec![Entry::from("foo")]
407 }
408 ),
409 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
410 );
411 assert_eq!(
412 render_cell(
413 "foo",
414 &RowInput {
415 label: String::from("nope"),
416 entries: vec![Entry::from("foo"), Entry::from("foo")]
417 }
418 ),
419 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
420 );
421 assert_eq!(
422 render_cell(
423 "foo",
424 &RowInput {
425 label: String::from("nope"),
426 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
427 }
428 ),
429 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
430 );
431 assert_eq!(
432 render_cell(
433 "foo",
434 &RowInput {
435 label: String::from("nope"),
436 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
437 }
438 ),
439 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")
440 );
441 }
442 }