footing 0.1.12

Feature-gated foundations for Rust backend services
Documentation
use super::RedocDocsError;

pub(super) fn render(
    template: &str,
    title: &str,
    script_url: &str,
) -> Result<String, RedocDocsError> {
    let title = escape(title);
    let head = "<link rel=\"icon\" href=\"data:,\">\n<link rel=\"stylesheet\" href=\"./page.css\">";
    let body = format!(
        "<div id=\"redoc-container\" aria-busy=\"true\" data-spec-url=\"./openapi.json\" data-options-url=\"./options.json\"><p role=\"status\">Loading API documentation…</p></div>\n<script src=\"{}\" defer></script>\n<script src=\"./init.js\" defer></script>",
        escape(script_url)
    );
    let slots = [
        ("{{title}}", title.as_str()),
        ("{{head}}", head),
        ("{{body}}", body.as_str()),
    ];
    let mut replacements = Vec::with_capacity(slots.len());
    for (slot, value) in slots {
        let mut matches = template.match_indices(slot);
        let Some((position, _)) = matches.next() else {
            return Err(RedocDocsError::InvalidTemplate(slot));
        };
        if matches.next().is_some() {
            return Err(RedocDocsError::InvalidTemplate(slot));
        }
        replacements.push((position, slot.len(), value));
    }
    replacements.sort_by_key(|(position, _, _)| *position);
    let mut html = String::with_capacity(template.len() + body.len() + title.len());
    let mut previous = 0;
    for (position, length, value) in replacements {
        html.push_str(&template[previous..position]);
        html.push_str(value);
        previous = position + length;
    }
    html.push_str(&template[previous..]);
    Ok(html)
}

fn escape(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            ch => escaped.push(ch),
        }
    }
    escaped
}