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) };
}
pub fn set_navigator(f: Rc<dyn Fn(&str)>) {
NAVIGATOR.with(|n| *n.borrow_mut() = Some(f));
}
pub fn navigate(path: &str) {
let f = NAVIGATOR.with(|n| n.borrow().clone());
if let Some(f) = f {
f(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,
}
}
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"));
for to in ["\u{a0}javascript:alert(1)", "\u{2028}javascript:alert(1)"] {
assert_eq!(link_href(to).as_deref(), Some(to), "{to:?}");
}
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:?}");
}
}
}