serge-core 0.1.4

View tree, widgets, events, PaintCtx/ScenePrimitive and view scopes of the serge UI framework
Documentation
//! Navigation hook: `Link` and `navigate()` ask the router installed for
//! this UI thread to open a path.

use std::cell::RefCell;
use std::rc::Rc;

type Navigator = Rc<dyn Fn(&str)>;

thread_local! {
    static NAVIGATOR: RefCell<Option<Navigator>> = const { RefCell::new(None) };
}

/// Installs the router's navigation function (the router does this when the
/// app starts).
pub fn set_navigator(f: Rc<dyn Fn(&str)>) {
    NAVIGATOR.with(|n| *n.borrow_mut() = Some(f));
}

/// Opens `path` (`/projects/7?tab=a`) in the app's router. Without a router
/// (no routes) it does nothing.
pub fn navigate(path: &str) {
    let f = NAVIGATOR.with(|n| n.borrow().clone());
    if let Some(f) = f {
        f(path);
    }
}

/// The `href` a `Link` to `to` gets on the web, or `None` when the browser
/// would read a scheme other than `http`, `https`, `mailto` or `tel` from
/// it (`javascript:`, `data:`, `blob:`, …); such a link renders without an
/// `href`. Values without a scheme (`notes/1`, `/projects/7`, `?tab=a`,
/// `#top`) are kept. Server rendering and the DOM both call this, so the
/// value is the same before and after hydration.
///
/// The value is cleaned as the WHATWG URL parser does before it reads the
/// scheme: leading and trailing C0 controls and spaces are removed, and so
/// is every tab, LF and CR. Like a browser, `a:b` has the scheme `a`; write
/// `./a:b` for the relative path.
pub fn link_href(to: &str) -> Option<String> {
    let cleaned: String = to
        .trim_matches(|c: char| c <= ' ')
        .chars()
        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
        .collect();
    match url_scheme(&cleaned) {
        None => Some(cleaned),
        Some(s) if ["http", "https", "mailto", "tel"].contains(&s.as_str()) => Some(cleaned),
        Some(_) => None,
    }
}

/// The lowercased scheme of an already cleaned URL string, or `None` when
/// the URL parser's scheme state ends without a `:` (a relative URL).
fn url_scheme(url: &str) -> Option<String> {
    let mut chars = url.chars();
    let first = chars.next().filter(char::is_ascii_alphabetic)?;
    let mut scheme = String::from(first.to_ascii_lowercase());
    for c in chars {
        match c {
            ':' => return Some(scheme),
            c if c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.') => {
                scheme.push(c.to_ascii_lowercase());
            }
            _ => return None,
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::link_href;

    #[test]
    fn relative_and_web_targets_are_kept() {
        for to in [
            "about",
            "notes/1",
            "./a:b",
            "/projects/7?tab=files",
            "?tab=a",
            "#top",
            "",
            "//example.com/x",
            "https://example.com/",
            "HTTP://example.com/",
            "mailto:a@example.com",
            "tel:+1-555-0100",
        ] {
            assert_eq!(link_href(to).as_deref(), Some(to), "{to:?}");
        }
    }

    #[test]
    fn the_value_is_cleaned_like_the_url_parser() {
        assert_eq!(link_href("  /a\tb\n\r ").as_deref(), Some("/ab"));
        assert_eq!(
            link_href("\u{0}\u{1f}notes/1\u{0}").as_deref(),
            Some("notes/1")
        );
        assert_eq!(link_href("ht\ttp:/x").as_deref(), Some("http:/x"));
        // Not C0 controls or spaces: kept, and the value has no scheme.
        for to in ["\u{a0}javascript:alert(1)", "\u{2028}javascript:alert(1)"] {
            assert_eq!(link_href(to).as_deref(), Some(to), "{to:?}");
        }
        // A character outside the scheme alphabet before `:`: no scheme.
        assert_eq!(link_href("java script:x").as_deref(), Some("java script:x"));
        assert_eq!(
            link_href("javascript\u{0}:x").as_deref(),
            Some("javascript\u{0}:x")
        );
    }

    #[test]
    fn other_schemes_get_no_href() {
        let mut targets: Vec<String> = [
            "javascript:alert(1)",
            "JaVaScRiPt:alert(1)",
            "java\tscr\nipt\r:alert(1)",
            "javascript:alert(1)\u{0} ",
            "data:text/html,<script>alert(1)</script>",
            "vbscript:msgbox(1)",
            "blob:https://example.com/0",
            "file:///etc/passwd",
            "filesystem:https://example.com/x",
            "about:blank",
            "intent://x#Intent;end",
            "ms-msdt:/id",
            "a:b",
            "localhost:3000/x",
            "c:/windows",
        ]
        .map(String::from)
        .to_vec();
        targets.extend((0..=0x20u8).map(|b| format!("{}javascript:alert(1)", char::from(b))));
        for to in targets {
            assert_eq!(link_href(&to), None, "{to:?}");
        }
    }
}