chiark / gitweb /
SeparatorLine (with proper date formatting!)
authorSimon Tatham <anakin@pobox.com>
Sun, 24 Dec 2023 21:26:32 +0000 (21:26 +0000)
committerSimon Tatham <anakin@pobox.com>
Sun, 24 Dec 2023 21:36:24 +0000 (21:36 +0000)
src/text.rs

index a5c62bdd7e2b2ad9419d54d5866dd612ab474fdd..386b91751f9ff66e6a08775c07a9f585a99a6f92 100644 (file)
@@ -1,3 +1,5 @@
+use chrono::{DateTime,Utc,Local};
+
 use super::coloured_string::ColouredString;
 
 pub trait TextFragment {
@@ -19,3 +21,77 @@ impl TextFragment for BlankLine {
         }
     }
 }
+
+pub struct SeparatorLine {
+    timestamp: Option<DateTime<Utc>>,
+    favourited: bool,
+    boosted: bool,
+}
+
+impl SeparatorLine {
+    pub fn newbox(
+        timestamp: Option<DateTime<Utc>>,
+        favourited: bool,
+        boosted: bool,
+    ) -> Box<dyn TextFragment> {
+        Box::new(SeparatorLine {
+            timestamp,
+            favourited,
+            boosted,
+        })
+    }
+}
+
+impl TextFragment for SeparatorLine {
+    fn render(&self, width: usize) -> Vec<ColouredString> {
+        let mut suffix = ColouredString::plain("");
+        let display_pre = ColouredString::uniform("[", 'S');
+        let display_post = ColouredString::uniform("]--", 'S');
+        match self.timestamp {
+            Some(date) => {
+                let datestr = date.with_timezone(&Local)
+                    .format("%a %b %e %H:%M:%S %Y").to_string();
+                suffix = &display_pre +
+                    ColouredString::uniform(&datestr, 'D') +
+                    &display_post + suffix;
+            },
+            _ => (),
+        }
+        if self.boosted {
+            suffix = &display_pre + ColouredString::uniform("B", 'D') +
+                &display_post + suffix;
+        }
+        if self.favourited {
+            suffix = &display_pre + ColouredString::uniform("F", 'D') +
+                &display_post + suffix;
+        }
+        let w = suffix.width();
+        if w < width - 1 {
+            suffix = ColouredString::uniform("-", 'S').repeat(width - 1 - w) +
+                suffix;
+        }
+        vec! {
+            suffix.split(width).next().unwrap().to_owned()
+        }
+    }
+}
+
+#[test]
+fn blank() {
+    assert_eq!(BlankLine::newbox().render(40), vec! {
+            ColouredString::plain("")
+        });
+}
+
+#[test]
+fn separator() {
+    // Would be nice to test time formatting here, but I'd have to
+    // think of a way to test it independently of TZ
+    assert_eq!(SeparatorLine::newbox(None, true, false)
+               .render(60), vec! {
+            ColouredString::general(
+                "------------------------------------------------------[F]--",
+                "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSDSSS",
+                )
+        });
+}