noonoo-engine 0.21.0

Noonoo's orchestration: a parsed, styled, laid-out engine over a DOM document.
Documentation
//! Linked stylesheets: `<link rel=stylesheet>` and `@import`, loaded
//! through the host's [`Loader`](noonoo_net::Loader) like images, and put
//! into the cascade in document order whenever they arrive.
//!
//! A fetched sheet's `url()` values are made absolute against the sheet's
//! own URL before it is parsed, so everything downstream (`@import`,
//! `@font-face` sources) sees absolute URLs.

use std::collections::HashMap;

use noonoo_css::{Rule, Stylesheet, TokenKind, tokenize};
use noonoo_dom::NodeId;
use noonoo_net::RequestId;

use crate::Engine;
use crate::resources::Resources;

/// How deep `@import` may nest below a `<link>`.
pub(crate) const MAX_IMPORT_DEPTH: usize = 6;
/// The most sheets one engine will fetch (links and imports together).
const MAX_SHEETS: usize = 256;

/// A fetched (or fetching) stylesheet.
struct Sheet {
    url: String,
    parent: Option<usize>,
    depth: usize,
    /// The media list its rules apply under, if it is conditional.
    media: Option<String>,
    state: State,
}

enum State {
    Pending,
    Failed,
    Ready {
        sheet: Stylesheet,
        /// The sheets its `@import` rules brought in, in order.
        imports: Vec<usize>,
    },
}

/// Every sheet requested so far, as a forest rooted at the `<link>`s.
#[derive(Default)]
pub(crate) struct Sheets {
    nodes: Vec<Sheet>,
    roots: HashMap<NodeId, usize>,
    pending: HashMap<RequestId, usize>,
}

impl Sheets {
    /// The stylesheets for a `<link>`: each import before the sheet that
    /// imported it, whatever has arrived so far.
    pub(crate) fn for_link(&self, link: NodeId) -> Vec<Stylesheet> {
        let mut out = Vec::new();
        if let Some(&root) = self.roots.get(&link) {
            self.flatten(root, &mut out);
        }
        out
    }

    fn flatten(&self, index: usize, out: &mut Vec<Stylesheet>) {
        if let State::Ready { sheet, imports } = &self.nodes[index].state {
            for &import in imports {
                self.flatten(import, out);
            }
            out.push(sheet.clone());
        }
    }

    pub(crate) fn owns(&self, id: RequestId) -> bool {
        self.pending.contains_key(&id)
    }

    pub(crate) fn take(&mut self, id: RequestId) -> usize {
        self.pending.remove(&id).expect("a pending sheet request")
    }
}

/// Media types a screen never matches: a link with only these is not fetched.
fn is_non_screen_list(media: &str) -> bool {
    let mut any = false;
    for query in media.split(',') {
        let query = query.trim().to_ascii_lowercase();
        if query.is_empty() {
            return false;
        }
        let bare = query.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
        if !bare || matches!(query.as_str(), "all" | "screen" | "not" | "only") {
            return false;
        }
        any = true;
    }
    any
}

/// The `(href, media)` of a `<link>` that asks for a screen stylesheet:
/// `rel` has `stylesheet` and not `alternate`, no `disabled`, a `type` that
/// is empty or `text/css`, a non-empty `href`.
fn stylesheet_link(element: &noonoo_dom::ElementData) -> Option<(String, Option<String>)> {
    let rel = element.attr("rel")?;
    let mut tokens = rel.split_ascii_whitespace().map(str::to_ascii_lowercase);
    let tokens: Vec<String> = tokens.by_ref().collect();
    if !tokens.iter().any(|t| t == "stylesheet") || tokens.iter().any(|t| t == "alternate") {
        return None;
    }
    if element.attr("disabled").is_some() {
        return None;
    }
    if let Some(kind) = element.attr("type") {
        let essence = kind.split(';').next().unwrap_or("").trim();
        if !essence.is_empty() && !essence.eq_ignore_ascii_case("text/css") {
            return None;
        }
    }
    let href = element.attr("href")?.trim();
    if href.is_empty() {
        return None;
    }
    let media = element
        .attr("media")
        .map(str::trim)
        .filter(|m| !m.is_empty() && !m.eq_ignore_ascii_case("all"))
        .map(str::to_owned);
    if media.as_deref().is_some_and(is_non_screen_list) {
        return None;
    }
    Some((href.to_owned(), media))
}

/// Make the `url()` values in `css` absolute against `base`.
pub(crate) fn absolutize_urls(css: &str, base: &str) -> String {
    let tokens = tokenize(css);
    let mut out = String::with_capacity(css.len());
    let mut copied = 0;
    let mut i = 0;
    while i < tokens.len() {
        let first = i;
        let (reference, end) = match &tokens[i].kind {
            TokenKind::Url(url) => (Some(url.clone()), tokens[i].end),
            TokenKind::Function(name) if name.eq_ignore_ascii_case("url") => {
                // `url( "…" )`: a function, a string, a close paren.
                let mut j = i + 1;
                while matches!(tokens.get(j).map(|t| &t.kind), Some(TokenKind::Whitespace)) {
                    j += 1;
                }
                let string = match tokens.get(j).map(|t| &t.kind) {
                    Some(TokenKind::Str(s)) => Some(s.clone()),
                    _ => None,
                };
                j += 1;
                while matches!(tokens.get(j).map(|t| &t.kind), Some(TokenKind::Whitespace)) {
                    j += 1;
                }
                match (string, tokens.get(j)) {
                    (Some(s), Some(close)) if matches!(close.kind, TokenKind::CloseParen) => {
                        i = j;
                        (Some(s), close.end)
                    }
                    _ => (None, 0),
                }
            }
            _ => (None, 0),
        };
        if let Some(reference) = reference {
            let reference = reference.trim();
            if !reference.is_empty() && !reference.starts_with('#') {
                let absolute = noonoo_net::resolve(base, reference);
                out.push_str(&css[copied..tokens[first].start]);
                out.push_str("url(\"");
                out.push_str(&absolute.replace('\\', "\\\\").replace('"', "\\\""));
                out.push_str("\")");
                copied = end;
            }
        }
        i += 1;
    }
    out.push_str(&css[copied..]);
    out
}

/// An `@import` prelude as `(href, media)`: a string or `url()` first,
/// then an optional media list.
fn parse_import(prelude: &str) -> Option<(String, Option<String>)> {
    let tokens = tokenize(prelude);
    let mut i = 0;
    let skip = |i: &mut usize| {
        while matches!(tokens.get(*i).map(|t| &t.kind), Some(TokenKind::Whitespace)) {
            *i += 1;
        }
    };
    skip(&mut i);
    let (href, mut next) = match &tokens.get(i)?.kind {
        TokenKind::Str(s) | TokenKind::Url(s) => (s.clone(), i + 1),
        TokenKind::Function(name) if name.eq_ignore_ascii_case("url") => {
            let mut j = i + 1;
            skip(&mut j);
            let TokenKind::Str(s) = &tokens.get(j)?.kind else {
                return None;
            };
            let s = s.clone();
            j += 1;
            skip(&mut j);
            if !matches!(tokens.get(j)?.kind, TokenKind::CloseParen) {
                return None;
            }
            (s, j + 1)
        }
        _ => return None,
    };
    skip(&mut next);
    let media = tokens
        .get(next)
        .map(|first| prelude[first.start..].trim().to_owned())
        .filter(|m| !m.is_empty() && !m.eq_ignore_ascii_case("all"));
    Some((href, media))
}

impl Engine {
    /// Start loading each `<link rel=stylesheet>` not yet requested;
    /// returns how many loads started.
    pub(crate) fn load_links(&mut self) -> usize {
        if self.resources.loader.is_none() {
            return 0;
        }
        let mut started = 0;
        for link in self.dom.get_elements_by_tag_name("link") {
            if self.resources.sheets.roots.contains_key(&link) {
                continue;
            }
            let Some((href, media)) = self.dom.element(link).and_then(stylesheet_link) else {
                continue;
            };
            let url = match &self.resources.base_url {
                Some(base) => noonoo_net::resolve(base, &href),
                None => href,
            };
            if let Some(index) = start_sheet(&mut self.resources, url, None, 0, media) {
                self.resources.sheets.roots.insert(link, index);
                started += 1;
            }
        }
        started
    }

    /// Take in a finished sheet load. True when the set of rules in force
    /// changed.
    pub(crate) fn sheet_arrived(
        &mut self,
        index: usize,
        result: Result<Vec<u8>, noonoo_net::LoadError>,
    ) -> bool {
        let Ok(bytes) = result else {
            self.resources.sheets.nodes[index].state = State::Failed;
            return false;
        };
        let text = String::from_utf8_lossy(&bytes);
        let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
        let (url, depth, media) = {
            let node = &self.resources.sheets.nodes[index];
            (node.url.clone(), node.depth, node.media.clone())
        };
        let css = absolutize_urls(text, &url);
        let parsed = Stylesheet::parse(&css).unwrap_or_default();

        // `@import` rules count only before any other rule.
        let mut imports = Vec::new();
        for rule in &parsed.rules {
            let Rule::At {
                name,
                prelude,
                block: None,
            } = rule
            else {
                break;
            };
            if name.eq_ignore_ascii_case("charset") {
                continue;
            }
            if !name.eq_ignore_ascii_case("import") {
                break;
            }
            let Some((href, import_media)) = parse_import(prelude) else {
                continue;
            };
            if import_media.as_deref().is_some_and(is_non_screen_list) {
                continue;
            }
            let child_url = noonoo_net::resolve(&url, &href);
            if depth + 1 > MAX_IMPORT_DEPTH || self.in_chain(index, &child_url) {
                continue;
            }
            // A conditional parent's condition carries to an unconditional
            // import; an import with its own list uses that list.
            let child_media = import_media.or_else(|| media.clone());
            if let Some(child) = start_sheet(
                &mut self.resources,
                child_url,
                Some(index),
                depth + 1,
                child_media,
            ) {
                imports.push(child);
            }
        }

        let sheet = match &media {
            Some(media) => {
                Stylesheet::parse(&format!("@media {media} {{ {css} }}")).unwrap_or_default()
            }
            None => parsed,
        };
        self.resources.sheets.nodes[index].state = State::Ready { sheet, imports };
        true
    }

    /// Whether `url` is `index`'s own URL or one of its ancestors'.
    fn in_chain(&self, index: usize, url: &str) -> bool {
        let mut at = Some(index);
        while let Some(i) = at {
            let node = &self.resources.sheets.nodes[i];
            if node.url == url {
                return true;
            }
            at = node.parent;
        }
        false
    }
}

fn start_sheet(
    resources: &mut Resources,
    url: String,
    parent: Option<usize>,
    depth: usize,
    media: Option<String>,
) -> Option<usize> {
    if resources.sheets.nodes.len() >= MAX_SHEETS {
        return None;
    }
    let loader = resources.loader.as_ref()?;
    let index = resources.sheets.nodes.len();
    resources.sheets.nodes.push(Sheet {
        url: url.clone(),
        parent,
        depth,
        media,
        state: State::Pending,
    });
    let (request, completion) = resources.completions.request(url);
    resources.sheets.pending.insert(request.id, index);
    loader.start(request, completion);
    Some(index)
}