laravel-comments 0.3.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! Safe HTML from a comment's Markdown, with the `markdown` feature.

use std::collections::HashSet;

use pulldown_cmark::{Event, Options, Parser, html};

/// Renders Markdown as HTML that's safe to show as it is: raw HTML in the text shows as text,
/// links keep only `http`, `https`, and `mailto` addresses and get
/// `rel="nofollow ugc noopener noreferrer"`, and images are dropped, so a comment can't load
/// anything into the page. [`ammonia`] cleans the result.
///
/// ```
/// let html = laravel_comments::markdown::to_html("**Hi** <script>alert(1)</script> [me](javascript:alert(1))");
/// assert_eq!(html, "<p><strong>Hi</strong> &lt;script&gt;alert(1)&lt;/script&gt; <a rel=\"nofollow ugc noopener noreferrer\">me</a></p>\n");
/// ```
#[must_use]
pub fn to_html(markdown: &str) -> String {
    let options = Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES;
    let events = Parser::new_ext(markdown, options).map(|event| match event {
        Event::Html(raw) | Event::InlineHtml(raw) => Event::Text(raw),
        event => event,
    });
    let mut rendered = String::new();
    html::push_html(&mut rendered, events);

    let tags: HashSet<&str> = [
        "a",
        "blockquote",
        "br",
        "code",
        "del",
        "em",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "hr",
        "li",
        "ol",
        "p",
        "pre",
        "strong",
        "table",
        "tbody",
        "td",
        "th",
        "thead",
        "tr",
        "ul",
    ]
    .into_iter()
    .collect();
    ammonia::Builder::default()
        .tags(tags)
        .url_schemes(["http", "https", "mailto"].into_iter().collect())
        .link_rel(Some("nofollow ugc noopener noreferrer"))
        .clean(&rendered)
        .to_string()
}