From 4c86fbba1ea9d751c9f653ebef461225123cad8c Mon Sep 17 00:00:00 2001 From: Emii Tatsuo Date: Mon, 30 Nov 2020 13:58:32 -0500 Subject: [PATCH 1/3] =?UTF-8?q?Add=20support=20for=20alt-text=20in=20prefo?= =?UTF-8?q?rmatted=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)); -- 2.44.0 From 9bc2ea115928e4799f714245d176f858bde69590 Mon Sep 17 00:00:00 2001 From: Emii Tatsuo Date: Mon, 30 Nov 2020 14:17:13 -0500 Subject: [PATCH 2/3] Fix bug with type inferring for the `preformatted()` method --- gemtext/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gemtext/src/lib.rs b/gemtext/src/lib.rs index b2bce9d..ca62fa7 100644 --- a/gemtext/src/lib.rs +++ b/gemtext/src/lib.rs @@ -26,7 +26,7 @@ impl Builder { self } - pub fn preformatted(mut self, alt_text: T, data: T) -> Builder + pub fn preformatted(mut self, alt_text: A, data: T) -> Builder where A: Into, T: Into, -- 2.44.0 From 5a6208dedf3bd6514b0c6db01be6529b5c4f73e7 Mon Sep 17 00:00:00 2001 From: Emi Tatsuo Date: Thu, 10 Dec 2020 11:53:57 -0500 Subject: [PATCH 3/3] Fix dependant workspace members --- majc/src/gemini.rs | 2 +- pilno/karnycukta/src/zbasu/mod.rs | 2 +- site/src/http.rs | 7 ++++++- site/src/server.rs | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/majc/src/gemini.rs b/majc/src/gemini.rs index c0853d1..58065c1 100644 --- a/majc/src/gemini.rs +++ b/majc/src/gemini.rs @@ -224,7 +224,7 @@ pub fn render(body: &str) -> StyledString { styled.append(StyledString::styled(name, Style::from(Effect::Underline))) } }, - Preformatted(data) => styled.append(StyledString::plain(data)), + Preformatted { body, .. } => styled.append(StyledString::plain(body)), Heading { level, body } => styled.append(StyledString::styled( format!("{} {}", "#".repeat(level as usize), body), Style::from(Effect::Bold), diff --git a/pilno/karnycukta/src/zbasu/mod.rs b/pilno/karnycukta/src/zbasu/mod.rs index e2f2679..3a32c24 100644 --- a/pilno/karnycukta/src/zbasu/mod.rs +++ b/pilno/karnycukta/src/zbasu/mod.rs @@ -25,7 +25,7 @@ fn gem_to_md(tcana: Vec, out: &mut impl Write) -> io::Result<()> { Some(name) => write!(out, "[{}]({})\n\n", name, to)?, None => write!(out, "[{0}]({0})", to)?, }, - Preformatted(body) => write!(out, "```\n{}\n```\n\n", body)?, + Preformatted { alt, body } => write!(out, "```{}\n{}\n```\n\n", alt, body)?, Heading { level, body } => { write!(out, "##{} {}\n\n", "#".repeat(level as usize), body)? } diff --git a/site/src/http.rs b/site/src/http.rs index fee6a9a..29066f9 100644 --- a/site/src/http.rs +++ b/site/src/http.rs @@ -80,7 +80,12 @@ fn gemtext_to_html(inp: Vec) -> (String, impl ToHtml) { name.as_ref().or(Some(&to.to_string())).unwrap() ) .unwrap(), - Preformatted(body) => write!(buf, "
{}
", body).unwrap(), + Preformatted { alt, body } => write!( + buf, + "
{}
", + alt.replace("\"", "\\\"").replace("\\", "\\\\"), + body + ).unwrap(), ListItem(body) => write!(buf, "
  • {}
  • ", body).unwrap(), Quote(body) => write!(buf, "
    {}
    ", body).unwrap(), } diff --git a/site/src/server.rs b/site/src/server.rs index 64ad802..deb1644 100644 --- a/site/src/server.rs +++ b/site/src/server.rs @@ -56,7 +56,7 @@ async fn dice(req: Request) -> Result { .text("") .text(format!("You rolled {} and you got:", dice)) .text("") - .preformatted(format!("{}", dice_roll(dice)?)) + .preformatted("", format!("{}", dice_roll(dice)?)) .text("") .link("/dice", Some("Do another roll".to_string())); -- 2.44.0