Add support for alt-text in preformatted blocks ⚠️
continuous-integration/drone/pr Build is failing Details

⚠️  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<String> 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.
This commit is contained in:
Emii Tatsuo 2020-11-30 13:58:32 -05:00
parent a7fabdc909
commit 4c86fbba1e
No known key found for this signature in database
GPG Key ID: 68FAB2E2E6DFC98B
1 changed files with 38 additions and 14 deletions

View File

@ -26,8 +26,12 @@ impl Builder {
self
}
pub fn preformatted<T: Into<String>>(mut self, data: T) -> Builder {
self.nodes.push(Node::Preformatted(data.into()));
pub fn preformatted<A, T>(mut self, alt_text: T, data: T) -> Builder
where
A: Into<String>,
T: Into<String>,
{
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<Node> {
let mut result: Vec<Node> = vec![];
let mut collect_preformatted: bool = false;
let mut preformatted_buffer: Vec<u8> = 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<Node> = 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<Node> = 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));