forked from cadey/maj
Merge pull request 'Add support for alt-text in preformatted blocks' (#15) from alch_emii/maj-prs:alt-text into main
Reviewed-on: cadey/maj#15
This commit is contained in:
commit
e9bcdf9f52
|
@ -48,8 +48,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: A, data: T) -> Builder
|
||||
where
|
||||
A: Into<String>,
|
||||
T: Into<String>,
|
||||
{
|
||||
self.nodes.push(Node::Preformatted { alt: alt_text.into(), body: data.into() });
|
||||
self
|
||||
}
|
||||
|
||||
|
@ -135,7 +139,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)?,
|
||||
|
@ -187,7 +191,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,
|
||||
|
@ -246,7 +262,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(),
|
||||
|
@ -266,7 +285,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(),
|
||||
}
|
||||
|
@ -277,18 +297,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;
|
||||
}
|
||||
|
@ -387,13 +411,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()),
|
||||
];
|
||||
|
@ -443,7 +467,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));
|
||||
|
|
|
@ -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),
|
||||
|
|
|
@ -25,7 +25,7 @@ fn gem_to_md(tcana: Vec<Node>, 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)?
|
||||
}
|
||||
|
|
|
@ -80,7 +80,12 @@ fn gemtext_to_html(inp: Vec<u8>) -> (String, impl ToHtml) {
|
|||
name.as_ref().or(Some(&to.to_string())).unwrap()
|
||||
)
|
||||
.unwrap(),
|
||||
Preformatted(body) => write!(buf, "<code><pre>{}</pre></code>", body).unwrap(),
|
||||
Preformatted { alt, body } => write!(
|
||||
buf,
|
||||
"<code><pre title = \"{}\">{}</pre></code>",
|
||||
alt.replace("\"", "\\\"").replace("\\", "\\\\"),
|
||||
body
|
||||
).unwrap(),
|
||||
ListItem(body) => write!(buf, "<li>{}</li>", body).unwrap(),
|
||||
Quote(body) => write!(buf, "<blockquote>{}</blockquote>", body).unwrap(),
|
||||
}
|
||||
|
|
|
@ -56,7 +56,7 @@ async fn dice(req: Request) -> Result<Response, Error> {
|
|||
.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()));
|
||||
|
||||
|
|
Loading…
Reference in New Issue