crossfoot-inline 0.1.0

Inline XBRL 1.1 document sets and the transformation registry (Crossfoot)
Documentation
//! Text of inline elements: the displayed content (with `ix:exclude` removed), the escaped
//! XHTML serialization used for `escape="true"` facts and footnotes, and whitespace helpers.

use crossfoot_core::ns;
use crossfoot_core::xml::{resolve_uri, Node};

use crate::schema::is_ix;

#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum Exclude {
    /// Drop `ix:exclude` subtrees (facts, continuations, footnotes).
    Html,
}

/// Inner text of `n` (descendant text nodes in document order), honouring exclusions.
pub(crate) fn inner_text(n: Node<'_>, out: &mut String, excl: Exclude) {
    for c in n.children() {
        if c.is_text() {
            out.push_str(c.text().unwrap_or(""));
        } else if c.is_element() {
            if excl == Exclude::Html && is_ix(c) && c.local() == "exclude" {
                continue;
            }
            inner_text(c, out, excl);
        }
    }
}

/// HTML elements that serialize as `<x/>` when empty.
fn self_closing(local: &str) -> bool {
    matches!(
        local,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "keygen"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
            | "basefont"
            | "frame"
            | "isindex"
    )
}

fn uri_attrs(local: &str) -> &'static [&'static str] {
    match local {
        "a" | "area" => &["href"],
        "blockquote" | "del" | "ins" | "q" => &["cite"],
        "form" => &["action"],
        "input" => &["src", "usemap"],
        "img" => &["src", "longdesc", "usemap"],
        "object" => &["codebase", "classid", "data", "archive", "usemap"],
        _ => &[],
    }
}

pub(crate) fn escape_text(s: &str, out: &mut String) {
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
}

fn escape_attr(s: &str, out: &mut String) {
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
}

/// Context for escaped serialization: the document's HTML `<base href>` used to resolve
/// relative URIs in escaped content.
#[derive(Clone, Default)]
pub(crate) struct EscapeCtx {
    pub html_base: Option<String>,
}

fn resolve_html_uri(ctx: &EscapeCtx, v: &str) -> String {
    match &ctx.html_base {
        Some(b) if !b.is_empty() && !crossfoot_core::xml::has_scheme(v) => {
            resolve_uri(b, v).replace(' ', "%20")
        }
        _ => v.to_string(),
    }
}

fn tag_name(e: Node<'_>) -> String {
    let q = e.name();
    if q.ns.as_ref() == ns::XHTML || q.prefix.is_empty() {
        q.local.to_string()
    } else {
        format!("{}:{}", q.prefix, q.local)
    }
}

fn start_tag(e: Node<'_>, ctx: &EscapeCtx, empty: bool, out: &mut String) {
    let name = tag_name(e);
    out.push('<');
    out.push_str(&name);
    let mut attrs: Vec<(String, String, String)> = e
        .attributes()
        .iter()
        .map(|a| {
            let key = if a.name.ns.is_empty() {
                a.name.local.to_string()
            } else {
                format!("{{{}}}{}", a.name.ns, a.name.local)
            };
            let shown = if a.name.ns.is_empty() {
                a.name.local.to_string()
            } else if a.name.ns.as_ref() == ns::XML {
                format!("xml:{}", a.name.local)
            } else if a.name.prefix.is_empty() {
                a.name.local.to_string()
            } else {
                format!("{}:{}", a.name.prefix, a.name.local)
            };
            (key, shown, a.value.to_string())
        })
        .collect();
    attrs.sort();
    let uris = uri_attrs(e.local());
    for (key, shown, v) in attrs {
        let v = if uris.contains(&key.as_str()) {
            resolve_html_uri(ctx, &v)
        } else {
            v
        };
        out.push(' ');
        out.push_str(&shown);
        out.push_str("=\"");
        escape_attr(&v, out);
        out.push('"');
    }
    if empty {
        if self_closing(e.local()) {
            out.push_str("/>");
        } else {
            out.push_str("></");
            out.push_str(&name);
            out.push('>');
        }
    } else {
        out.push('>');
    }
}

/// Escaped serialization of the content of `n` (not `n` itself): text escaped, XHTML
/// elements written with their tags, ix elements unwrapped, `ix:exclude` dropped.
pub(crate) fn escaped_content(n: Node<'_>, out: &mut String, ctx: &EscapeCtx) {
    for c in n.children() {
        if c.is_text() {
            escape_text(c.text().unwrap_or(""), out);
        } else if c.is_element() {
            if is_ix(c) {
                if c.local() == "exclude" {
                    continue;
                }
                escaped_content(c, out, ctx);
                continue;
            }
            let mut inner = String::new();
            escaped_content(c, &mut inner, ctx);
            if inner.is_empty() {
                start_tag(c, ctx, true, out);
            } else {
                start_tag(c, ctx, false, out);
                out.push_str(&inner);
                out.push_str("</");
                out.push_str(&tag_name(c));
                out.push('>');
            }
        }
    }
}

/// XML Schema whitespace collapse.
pub(crate) fn collapse(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for w in s.split([' ', '\t', '\n', '\r']).filter(|w| !w.is_empty()) {
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(w);
    }
    out
}

/// Trim XML whitespace (not NBSP).
pub(crate) fn xtrim(s: &str) -> &str {
    s.trim_matches([' ', '\t', '\n', '\r'])
}