discord-message-format/src/convert.rs

53 lines
1.8 KiB
Rust

use super::DiscordComponent;
pub trait ToHtml {
fn to_html(&self) -> String;
}
impl<'a> ToHtml for DiscordComponent<'a> {
fn to_html(&self) -> String {
match self {
DiscordComponent::Plain(s) => s.to_string(), // TODO: Escape
DiscordComponent::Literal(c) => c.to_string(),
DiscordComponent::Link(target) => format!(r#"<a href="{0}">{0}</a>"#, target),
DiscordComponent::Bold(children) => {
format!("<strong>{}</strong>", children.to_html())
}
DiscordComponent::Italic(children) => {
format!("<em>{}</em>", children.to_html())
}
DiscordComponent::Strikethrough(children) => {
format!("<del>{}</del>", children.to_html())
}
DiscordComponent::Underline(children) => {
format!("<u>{}</u>", children.to_html())
}
DiscordComponent::Code(source) => format!("<code>{}</code>", source),
DiscordComponent::CodeBlock { lang, source } => {
let language_class = lang
.map(|l| " class=\"language-".to_owned() + l + "\"")
.unwrap_or_else(String::new);
format!("<pre><code{}>{}</code></pre>", language_class, source)
}
DiscordComponent::Spoiler(children) => {
format!("<span data-mx-spoiler>{}</span>", children.to_html())
}
DiscordComponent::LineBreak => "<br>".to_string(),
DiscordComponent::Quote(children) => {
format!("<blockquote>{}</blockquote>", children.to_html())
}
}
}
}
impl<'a> ToHtml for Vec<DiscordComponent<'a>> {
fn to_html(&self) -> String {
self.iter().map(|c| c.to_html()).collect()
}
}