From 4c86fbba1ea9d751c9f653ebef461225123cad8c Mon Sep 17 00:00:00 2001 From: Emii Tatsuo Date: Mon, 30 Nov 2020 13:58:32 -0500 Subject: [PATCH] =?UTF-8?q?Add=20support=20for=20alt-text=20in=20preformat?= =?UTF-8?q?ted=20blocks=20=E2=9A=A0=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚠️ Breaking Change ⚠️ This adds support for parsing and rendering alt-text in preformatted blocks. This changes the public API both around the `Node` enum and the `preformatted()` method of the builder. I cannot think of a way to avoid this that is not needlessly overcomplicated, except maybe merging the preformatted & body into a single newline delimited string but that's hella gross and i don't think anyone wants that. Lemme know if you can think of a better way of doing this Preformatted blocks without alt text can still be created by passing in an empty string. Because alt text isn't separated by a space, this does not add any unnecessary padding. I chose not to accept Option here because an empty string serves the same function but encourages users to use alt-text in their documents, which is very important for increasing accessibility. --- gemtext/src/lib.rs | 52 +++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/gemtext/src/lib.rs b/gemtext/src/lib.rs index 8d532cd..b2bce9d 100644 --- a/gemtext/src/lib.rs +++ b/gemtext/src/lib.rs @@ -26,8 +26,12 @@ impl Builder { self } - pub fn preformatted>(mut self, data: T) -> Builder { - self.nodes.push(Node::Preformatted(data.into())); + pub fn preformatted(mut self, alt_text: T, data: T) -> Builder + where + A: Into, + T: Into, + { + self.nodes.push(Node::Preformatted { alt: alt_text.into(), body: data.into() }); self } @@ -113,7 +117,7 @@ pub fn render(nodes: impl AsRef<[Node]>, out: &mut impl Write) -> io::Result<()> Some(name) => write!(out, "=> {} {}\n", to, name)?, None => write!(out, "=> {}\n", to)?, }, - Preformatted(body) => write!(out, "```\n{}\n```\n", body)?, + Preformatted { alt, body } => write!(out, "```{}\n{}\n```\n", alt, body)?, Heading { level, body } => write!(out, "{} {}\n", "#".repeat(*level as usize), body)?, ListItem(body) => write!(out, "* {}\n", body)?, Quote(body) => write!(out, "> {}\n", body)?, @@ -165,7 +169,19 @@ pub enum Node { /// (e.g. Python) should be able to be copied and pasted from the client into /// a file and interpreted/compiled without any problems arising from the /// client's manner of displaying them. - Preformatted(String), + /// + /// The first preformatted toggle of a document is often followed by a short + /// string, which acts as alt-text for the preformatted block. This is also + /// often used to denote the language of code in a block of text. For example, + /// a block starting with the text `\`\`\`rust` may be interpreted as rust + /// code, and a block starting with `\`\`\` An ascii art owl` would be + /// described aptly to visually impaired users using a screen reader. The alt + /// text may be separated from the toggle by whitespace. `gemtext` currently + /// renders alt text without this separation. + /// + /// To create a preformatted block with no alt text, simply pass a zero-length + /// string as alt text. + Preformatted { alt: String, body: String }, /// Lines beginning with "#" are heading lines. Heading lines consist of one, /// two or three consecutive "#" characters, followed by optional whitespace, @@ -224,7 +240,10 @@ impl Node { /// # use gemtext::Node; /// let simple_text = Node::Text(String::from("Henlo worl")); /// let linky_link = Node::Link { to: "gemini://cetacean.club/maj/".to_string(), name: Some("Maj".to_string()) }; - /// let human_rights = Node::Preformatted("trans rights! 🏳️‍⚧️".to_string());; + /// let human_rights = Node::Preformatted { + /// alt: "".to_string(), + /// body: "trans rights! 🏳️‍⚧️".to_string(), + /// }; /// /// assert_eq!( /// simple_text.estimate_len(), @@ -244,7 +263,8 @@ impl Node { Self::Text(text) => text.len(), Self::Link { to, name } => 3 + to.as_bytes().len() + name.as_ref().map(|n| n.as_bytes().len() + 1).unwrap_or(0), - Self::Preformatted(text) => text.as_bytes().len() + 8, + Self::Preformatted { alt, body } => alt.as_bytes().len() + + body.as_bytes().len() + 8, Self::Heading { level, body } => *level as usize + 1 + body.as_bytes().len(), Self::ListItem(item) | Self::Quote(item)=> 2 + item.as_bytes().len(), } @@ -255,18 +275,22 @@ pub fn parse(doc: &str) -> Vec { let mut result: Vec = vec![]; let mut collect_preformatted: bool = false; let mut preformatted_buffer: Vec = vec![]; + let mut alt = ""; for line in doc.lines() { - if line.starts_with("```") { + if let Some(trailing) = line.strip_prefix("```") { collect_preformatted = !collect_preformatted; if !collect_preformatted { - result.push(Node::Preformatted( - String::from_utf8(preformatted_buffer) + result.push(Node::Preformatted { + alt: alt.to_string(), + body: String::from_utf8(preformatted_buffer) .unwrap() .trim_end() .to_string(), - )); + }); preformatted_buffer = vec![]; + } else { + alt = trailing.trim(); } continue; } @@ -365,13 +389,13 @@ mod tests { #[test] fn preformatted() { let _ = pretty_env_logger::try_init(); - let msg = "```\n\ - hi there\n\ + let msg = "```hi there\n\ + obi-wan kenobi\n\ ```\n\ \n\ Test\n"; let expected: Vec = vec![ - Node::Preformatted("hi there".to_string()), + Node::Preformatted{ alt: "hi there".to_string(), body: "obi-wan kenobi".to_string() }, Node::Text(String::new()), Node::Text("Test".to_string()), ]; @@ -421,7 +445,7 @@ mod tests { let _ = pretty_env_logger::try_init(); let msg = include_str!("../../testdata/ambig_preformatted.gmi"); let expected: Vec = vec![ - Node::Preformatted("FOO".to_string()), + Node::Preformatted { alt: "foo".to_string(), body: "FOO".to_string() }, Node::Text("Foo bar".to_string()), ]; assert_eq!(expected, parse(msg));