pub const OUTLET_ATTR: &str = "data-krab-router-outlet";
pub const IGNORE_ATTR: &str = "data-krab-router-ignore";
pub const ANNOUNCER_ID: &str = "krab-router-announcer";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkClick {
pub href: String,
pub link_origin: String,
pub document_origin: String,
pub target: Option<String>,
pub has_download: bool,
pub opted_out: bool,
pub button: i16,
pub modifier_held: bool,
pub default_prevented: bool,
}
pub fn should_intercept(click: &LinkClick) -> bool {
if click.default_prevented || click.opted_out || click.has_download {
return false;
}
if click.button != 0 || click.modifier_held {
return false;
}
if let Some(target) = &click.target {
if !target.is_empty() && target != "_self" {
return false;
}
}
if click.link_origin != click.document_origin {
return false;
}
if click.href.starts_with('#') {
return false;
}
true
}
pub fn is_same_document_fragment(current: &str, next: &str) -> bool {
strip_fragment(current) == strip_fragment(next) && next.contains('#')
}
fn strip_fragment(url: &str) -> &str {
match url.split_once('#') {
Some((base, _)) => base,
None => url,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FragmentTarget<'a> {
Top,
Element(&'a str),
}
pub fn fragment_target(url: &str) -> Option<FragmentTarget<'_>> {
let (_, fragment) = url.split_once('#')?;
if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") {
Some(FragmentTarget::Top)
} else {
Some(FragmentTarget::Element(fragment))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Tag {
name: String,
start: usize,
end: usize,
kind: TagKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TagKind {
Start {
self_closing: bool,
outlet: bool,
},
End,
}
fn is_raw_text(name: &str) -> bool {
matches!(name, "script" | "style" | "textarea" | "title")
}
fn next_tag(html: &str, from: usize) -> Option<Tag> {
let mut pos = from;
loop {
let at = pos + html.get(pos..)?.find('<')?;
let rest = &html[at..];
if let Some(body) = rest.strip_prefix("<!--") {
pos = at + 4 + body.find("-->")? + 3;
continue;
}
if rest.starts_with("<!") || rest.starts_with("<?") {
pos = at + rest.find('>')? + 1;
continue;
}
if let Some(tag) = parse_tag(html, at) {
return Some(tag);
}
pos = at + 1;
}
}
fn parse_tag(html: &str, at: usize) -> Option<Tag> {
let after = html.get(at + 1..)?;
let is_end = after.starts_with('/');
let name_start = at + 1 + usize::from(is_end);
let name: String = html
.get(name_start..)?
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
.collect();
if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
let (end, self_closing, outlet) = scan_attributes(html, name_start + name.len())?;
Some(Tag {
name: name.to_ascii_lowercase(),
start: at,
end,
kind: if is_end {
TagKind::End
} else {
TagKind::Start {
self_closing,
outlet,
}
},
})
}
fn scan_attributes(html: &str, from: usize) -> Option<(usize, bool, bool)> {
let bytes = html.as_bytes();
let len = bytes.len();
let mut pos = from;
let mut outlet = false;
loop {
while pos < len && bytes[pos].is_ascii_whitespace() {
pos += 1;
}
if pos >= len {
return None;
}
match bytes[pos] {
b'>' => return Some((pos + 1, false, outlet)),
b'/' if html[pos..].starts_with("/>") => return Some((pos + 2, true, outlet)),
b'/' => pos += 1,
_ => {
let name_start = pos;
while pos < len
&& !bytes[pos].is_ascii_whitespace()
&& !matches!(bytes[pos], b'=' | b'>' | b'/')
{
pos += 1;
}
if pos == name_start {
pos += 1;
continue;
}
if html[name_start..pos].eq_ignore_ascii_case(OUTLET_ATTR) {
outlet = true;
}
pos = skip_attribute_value(html, pos);
}
}
}
}
fn skip_attribute_value(html: &str, from: usize) -> usize {
let bytes = html.as_bytes();
let len = bytes.len();
let mut probe = from;
while probe < len && bytes[probe].is_ascii_whitespace() {
probe += 1;
}
if probe >= len || bytes[probe] != b'=' {
return from;
}
probe += 1;
while probe < len && bytes[probe].is_ascii_whitespace() {
probe += 1;
}
if probe >= len {
return probe;
}
match bytes[probe] {
quote @ (b'"' | b'\'') => {
probe += 1;
while probe < len && bytes[probe] != quote {
probe += 1;
}
(probe + 1).min(len)
}
_ => {
while probe < len && !bytes[probe].is_ascii_whitespace() && bytes[probe] != b'>' {
probe += 1;
}
probe
}
}
}
fn skip_raw_text(html: &str, name: &str, from: usize) -> usize {
find_ignore_ascii_case(html, &format!("</{name}"), from).unwrap_or(html.len())
}
fn find_ignore_ascii_case(haystack: &str, needle: &str, from: usize) -> Option<usize> {
let hay = haystack.as_bytes();
let ned = needle.as_bytes();
if ned.is_empty() || hay.len() < ned.len() || from > hay.len() - ned.len() {
return None;
}
(from..=hay.len() - ned.len()).find(|&i| hay[i..i + ned.len()].eq_ignore_ascii_case(ned))
}
fn scan_for<F>(html: &str, mut accept: F) -> Option<Tag>
where
F: FnMut(&Tag) -> bool,
{
let mut pos = 0usize;
loop {
let tag = next_tag(html, pos)?;
pos = tag.end;
if accept(&tag) {
return Some(tag);
}
if let TagKind::Start {
self_closing: false,
..
} = tag.kind
{
if is_raw_text(&tag.name) {
pos = skip_raw_text(html, &tag.name, pos);
}
}
}
}
pub fn extract_outlet_html(document_html: &str) -> Option<String> {
let opening = scan_for(document_html, |tag| {
matches!(tag.kind, TagKind::Start { outlet: true, .. })
})?;
if matches!(
opening.kind,
TagKind::Start {
self_closing: true,
..
}
) {
return Some(String::new());
}
let content_start = opening.end;
let mut depth = 1usize;
let mut pos = content_start;
loop {
let tag = next_tag(document_html, pos)?;
pos = tag.end;
match tag.kind {
TagKind::Start {
self_closing: false,
..
} => {
if tag.name == opening.name {
depth += 1;
} else if is_raw_text(&tag.name) {
pos = skip_raw_text(document_html, &tag.name, pos);
}
}
TagKind::Start { .. } => {}
TagKind::End if tag.name == opening.name => {
depth -= 1;
if depth == 0 {
return Some(document_html[content_start..tag.start].to_string());
}
}
TagKind::End => {}
}
}
}
pub fn extract_title(document_html: &str) -> Option<String> {
let opening = scan_for(document_html, |tag| {
tag.name == "title" && matches!(tag.kind, TagKind::Start { .. })
})?;
let end = find_ignore_ascii_case(document_html, "</title", opening.end)?;
Some(decode_html_entities(document_html[opening.end..end].trim()))
}
fn decode_html_entities(text: &str) -> String {
if !text.contains('&') {
return text.to_string();
}
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
let after = &rest[amp + 1..];
match after.find(';').filter(|&end| end <= 8) {
Some(end) => match decode_entity(&after[..end]) {
Some(decoded) => {
out.push(decoded);
rest = &after[end + 1..];
}
None => {
out.push('&');
rest = after;
}
},
None => {
out.push('&');
rest = after;
}
}
}
out.push_str(rest);
out
}
fn decode_entity(name: &str) -> Option<char> {
match name {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some('\u{a0}'),
_ => {
let digits = name.strip_prefix('#')?;
let code = match digits.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => digits.parse::<u32>().ok()?,
};
char::from_u32(code)
}
}
}
#[cfg(all(feature = "web", target_arch = "wasm32"))]
mod browser {
use super::*;
use crate::hydrate;
use std::cell::{Cell, RefCell};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::spawn_local;
use web_sys::{Document, Element, HtmlAnchorElement, HtmlElement, MouseEvent, Window};
const SCROLL_X_KEY: &str = "krabScrollX";
const SCROLL_Y_KEY: &str = "krabScrollY";
thread_local! {
static NAVIGATION: Cell<u64> = const { Cell::new(0) };
static RENDERED_URL: RefCell<Option<String>> = const { RefCell::new(None) };
}
fn rendered_url() -> Option<String> {
RENDERED_URL
.with(|url| url.borrow().clone())
.or_else(current_href)
}
fn set_rendered_url(url: &str) {
RENDERED_URL.with(|rendered| *rendered.borrow_mut() = Some(url.to_string()));
}
fn begin_navigation() -> u64 {
NAVIGATION.with(|generation| {
let next = generation.get().wrapping_add(1);
generation.set(next);
next
})
}
fn is_current(generation: u64) -> bool {
NAVIGATION.with(|current| current.get() == generation)
}
#[wasm_bindgen(js_name = start_router)]
pub fn start() {
let Some(window) = web_sys::window() else {
return;
};
let Some(document) = window.document() else {
return;
};
if document
.document_element()
.and_then(|el| el.get_attribute("data-krab-router-active"))
.is_some()
{
return;
}
if let Some(root) = document.document_element() {
let _ = root.set_attribute("data-krab-router-active", "1");
}
if let Ok(history) = window.history() {
let _ = js_sys::Reflect::set(
history.as_ref(),
&JsValue::from_str("scrollRestoration"),
&JsValue::from_str("manual"),
);
}
install_click_listener(&document);
install_popstate_listener(&window);
}
fn install_click_listener(document: &Document) {
let handler = Closure::<dyn FnMut(MouseEvent)>::new(move |event: MouseEvent| {
let Some(anchor) = closest_anchor(&event) else {
return;
};
let Some(click) = describe_click(&event, &anchor) else {
return;
};
if !should_intercept(&click) {
return;
}
event.prevent_default();
let href = click.href.clone();
spawn_local(async move {
navigate_to(&href, true).await;
});
});
let _ = document.add_event_listener_with_callback_and_bool(
"click",
handler.as_ref().unchecked_ref(),
true,
);
handler.forget();
}
fn install_popstate_listener(window: &Window) {
let handler = Closure::<dyn FnMut(web_sys::Event)>::new(move |_| {
let Some(href) = current_href() else {
return;
};
spawn_local(async move {
navigate_to(&href, false).await;
});
});
let _ =
window.add_event_listener_with_callback("popstate", handler.as_ref().unchecked_ref());
handler.forget();
}
fn closest_anchor(event: &MouseEvent) -> Option<HtmlAnchorElement> {
let target = event.target()?.dyn_into::<Element>().ok()?;
target
.closest("a")
.ok()
.flatten()
.and_then(|el| el.dyn_into::<HtmlAnchorElement>().ok())
}
fn describe_click(event: &MouseEvent, anchor: &HtmlAnchorElement) -> Option<LinkClick> {
let document_origin = web_sys::window()?.location().origin().ok()?;
Some(LinkClick {
href: anchor.href(),
link_origin: anchor.origin(),
document_origin,
target: Some(anchor.target()),
has_download: anchor.has_attribute("download"),
opted_out: anchor.has_attribute(IGNORE_ATTR),
button: event.button(),
modifier_held: event.ctrl_key()
|| event.shift_key()
|| event.alt_key()
|| event.meta_key(),
default_prevented: event.default_prevented(),
})
}
fn current_href() -> Option<String> {
web_sys::window()?.location().href().ok()
}
fn find_outlet(document: &Document) -> Option<Element> {
document
.query_selector(&format!("[{OUTLET_ATTR}]"))
.ok()
.flatten()
}
struct FetchedDocument {
html: String,
final_url: Option<String>,
}
pub async fn navigate_to(href: &str, push: bool) {
let Some(window) = web_sys::window() else {
return;
};
let Some(document) = window.document() else {
return;
};
if let Some(rendered) = rendered_url() {
if is_same_document_fragment(&rendered, href) {
set_rendered_url(href);
if push {
remember_scroll(&window);
push_history(&window, href, href);
scroll_to_fragment(&window, &document, href);
} else if let Some((x, y)) = saved_scroll(&window) {
window.scroll_to_with_x_and_y(x, y);
} else {
scroll_to_fragment(&window, &document, href);
}
return;
}
}
if find_outlet(&document).is_none() {
hard_navigate(href);
return;
}
let generation = begin_navigation();
let Some(fetched) = fetch_document(href).await else {
if is_current(generation) {
hard_navigate(href);
}
return;
};
if !is_current(generation) {
return;
}
let Some(next_html) = extract_outlet_html(&fetched.html) else {
hard_navigate(href);
return;
};
let Some(outlet) = find_outlet(&document) else {
hard_navigate(href);
return;
};
if push {
remember_scroll(&window);
}
crate::unmount(&outlet);
outlet.set_inner_html(&next_html);
set_rendered_url(fetched.final_url.as_deref().unwrap_or(href));
let title = extract_title(&fetched.html);
if let Some(title) = &title {
document.set_title(title);
}
if push {
let final_url = fetched.final_url.as_deref().unwrap_or(href);
push_history(&window, final_url, href);
}
hydrate();
focus_outlet(&outlet);
announce(&document, title.as_deref().unwrap_or(href));
if push {
if !scroll_to_fragment(&window, &document, href) {
window.scroll_to_with_x_and_y(0.0, 0.0);
}
} else if let Some((x, y)) = saved_scroll(&window) {
window.scroll_to_with_x_and_y(x, y);
}
}
fn scroll_to_fragment(window: &Window, document: &Document, href: &str) -> bool {
match fragment_target(href) {
None => false,
Some(FragmentTarget::Top) => {
let raw = href.split_once('#').map_or("", |(_, fragment)| fragment);
match (!raw.is_empty())
.then(|| fragment_element(document, raw))
.flatten()
{
Some(element) => element.scroll_into_view(),
None => window.scroll_to_with_x_and_y(0.0, 0.0),
}
true
}
Some(FragmentTarget::Element(raw)) => match fragment_element(document, raw) {
Some(element) => {
element.scroll_into_view();
true
}
None => false,
},
}
}
fn fragment_element(document: &Document, raw: &str) -> Option<Element> {
let decoded = js_sys::decode_uri_component(raw)
.ok()
.and_then(|v| v.as_string());
std::iter::once(raw.to_string())
.chain(decoded)
.find_map(|name| {
document.get_element_by_id(&name).or_else(|| {
document
.get_elements_by_name(&name)
.item(0)
.and_then(|n| n.dyn_into::<Element>().ok())
})
})
}
async fn fetch_document(href: &str) -> Option<FetchedDocument> {
use wasm_bindgen_futures::JsFuture;
let window = web_sys::window()?;
let opts = web_sys::RequestInit::new();
opts.set_method("GET");
let request = web_sys::Request::new_with_str_and_init(href, &opts).ok()?;
request.headers().set("x-krab-router", "1").ok()?;
request.headers().set("accept", "text/html").ok()?;
let response: web_sys::Response = JsFuture::from(window.fetch_with_request(&request))
.await
.ok()?
.dyn_into()
.ok()?;
if !response.ok() {
return None;
}
let final_url = response.url();
let html = JsFuture::from(response.text().ok()?)
.await
.ok()?
.as_string()?;
Some(FetchedDocument {
html,
final_url: (!final_url.is_empty()).then_some(final_url),
})
}
fn push_history(window: &Window, url: &str, requested: &str) {
let Ok(history) = window.history() else {
return;
};
if history
.push_state_with_url(&JsValue::NULL, "", Some(url))
.is_err()
{
let _ = history.push_state_with_url(&JsValue::NULL, "", Some(requested));
}
}
fn remember_scroll(window: &Window) {
let Ok(history) = window.history() else {
return;
};
let x = window.scroll_x().unwrap_or(0.0);
let y = window.scroll_y().unwrap_or(0.0);
let state = js_sys::Object::new();
let _ = js_sys::Reflect::set(
state.as_ref(),
&JsValue::from_str(SCROLL_X_KEY),
&JsValue::from_f64(x),
);
let _ = js_sys::Reflect::set(
state.as_ref(),
&JsValue::from_str(SCROLL_Y_KEY),
&JsValue::from_f64(y),
);
let _ = history.replace_state(state.as_ref(), "");
}
fn saved_scroll(window: &Window) -> Option<(f64, f64)> {
let state = window.history().ok()?.state().ok()?;
let x = js_sys::Reflect::get(&state, &JsValue::from_str(SCROLL_X_KEY))
.ok()?
.as_f64()?;
let y = js_sys::Reflect::get(&state, &JsValue::from_str(SCROLL_Y_KEY))
.ok()?
.as_f64()?;
Some((x, y))
}
fn focus_outlet(outlet: &Element) {
if !outlet.has_attribute("tabindex") {
let _ = outlet.set_attribute("tabindex", "-1");
}
if let Some(element) = outlet.dyn_ref::<HtmlElement>() {
let _ = element.focus();
}
}
fn announce(document: &Document, message: &str) {
let region = match document.get_element_by_id(ANNOUNCER_ID) {
Some(region) => region,
None => {
let Ok(created) = document.create_element("div") else {
return;
};
created.set_id(ANNOUNCER_ID);
let _ = created.set_attribute("role", "status");
let _ = created.set_attribute("aria-live", "polite");
let _ = created.set_attribute("aria-atomic", "true");
let _ = created.set_attribute(
"style",
"position:absolute;width:1px;height:1px;margin:-1px;padding:0;\
overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;",
);
let Some(body) = document.body() else {
return;
};
if body.append_child(created.as_ref()).is_err() {
return;
}
created
}
};
region.set_text_content(Some(message));
}
fn hard_navigate(href: &str) {
if let Some(window) = web_sys::window() {
let _ = window.location().assign(href);
}
}
}
#[cfg(all(feature = "web", target_arch = "wasm32"))]
pub use browser::{navigate_to, start};
#[cfg(test)]
mod tests {
use super::*;
fn base_click() -> LinkClick {
LinkClick {
href: "https://example.com/about".to_string(),
link_origin: "https://example.com".to_string(),
document_origin: "https://example.com".to_string(),
target: None,
has_download: false,
opted_out: false,
button: 0,
modifier_held: false,
default_prevented: false,
}
}
#[test]
fn a_plain_same_origin_click_is_intercepted() {
assert!(should_intercept(&base_click()));
}
#[test]
fn modified_and_non_primary_clicks_are_left_to_the_browser() {
let modified = LinkClick {
modifier_held: true,
..base_click()
};
assert!(!should_intercept(&modified));
let middle = LinkClick {
button: 1,
..base_click()
};
assert!(!should_intercept(&middle));
}
#[test]
fn cross_origin_links_are_left_to_the_browser() {
let external = LinkClick {
href: "https://other.example/page".to_string(),
link_origin: "https://other.example".to_string(),
..base_click()
};
assert!(!should_intercept(&external));
}
#[test]
fn origin_comparison_is_not_a_host_comparison() {
let other_port = LinkClick {
link_origin: "https://example.com:8443".to_string(),
..base_click()
};
assert!(!should_intercept(&other_port));
}
#[test]
fn targeted_and_download_links_are_left_to_the_browser() {
let new_tab = LinkClick {
target: Some("_blank".to_string()),
..base_click()
};
assert!(!should_intercept(&new_tab));
let download = LinkClick {
has_download: true,
..base_click()
};
assert!(!should_intercept(&download));
}
#[test]
fn an_empty_or_self_target_is_still_intercepted() {
for target in ["", "_self"] {
let click = LinkClick {
target: Some(target.to_string()),
..base_click()
};
assert!(should_intercept(&click), "target={target:?}");
}
}
#[test]
fn an_explicit_opt_out_is_honoured() {
let opted_out = LinkClick {
opted_out: true,
..base_click()
};
assert!(!should_intercept(&opted_out));
}
#[test]
fn an_already_handled_event_is_not_hijacked() {
let handled = LinkClick {
default_prevented: true,
..base_click()
};
assert!(!should_intercept(&handled));
}
#[test]
fn bare_fragments_are_left_to_the_browser() {
let fragment = LinkClick {
href: "#section".to_string(),
..base_click()
};
assert!(!should_intercept(&fragment));
}
#[test]
fn same_page_fragment_navigation_is_detected() {
assert!(is_same_document_fragment("/docs", "/docs#usage"));
assert!(is_same_document_fragment("/docs#intro", "/docs#usage"));
assert!(!is_same_document_fragment("/docs", "/guide#usage"));
assert!(!is_same_document_fragment("/docs", "/docs"));
}
#[test]
fn fragment_targets_follow_the_html_rules() {
assert_eq!(fragment_target("/docs"), None);
assert_eq!(fragment_target("/docs#"), Some(FragmentTarget::Top));
assert_eq!(fragment_target("/docs#TOP"), Some(FragmentTarget::Top));
assert_eq!(
fragment_target("/docs#usage"),
Some(FragmentTarget::Element("usage"))
);
assert_eq!(
fragment_target("https://x.test/a?b=c#caf%C3%A9"),
Some(FragmentTarget::Element("caf%C3%A9"))
);
}
#[test]
fn outlet_contents_are_extracted() {
let html = r#"<html><body>
<nav>keep me</nav>
<main data-krab-router-outlet><h1>Page</h1></main>
</body></html>"#;
let extracted = extract_outlet_html(html).expect("outlet not found");
assert_eq!(extracted.trim(), "<h1>Page</h1>");
assert!(!extracted.contains("keep me"));
}
#[test]
fn nested_same_tag_elements_do_not_truncate_the_outlet() {
let html = r#"<main data-krab-router-outlet>
<main class="inner">nested</main><p>after</p>
</main>"#;
let extracted = extract_outlet_html(html).expect("outlet not found");
assert!(extracted.contains("nested"), "got: {extracted}");
assert!(
extracted.contains("<p>after</p>"),
"content after the nested element was truncated: {extracted}"
);
}
#[test]
fn a_tag_with_a_shared_prefix_does_not_close_the_outlet() {
let html = r#"<main data-krab-router-outlet><mains>x</mains><p>tail</p></main>"#;
let extracted = extract_outlet_html(html).expect("outlet not found");
assert!(extracted.contains("<p>tail</p>"), "got: {extracted}");
}
#[test]
fn a_document_without_an_outlet_yields_none() {
let html = "<html><body><main>no marker</main></body></html>";
assert!(extract_outlet_html(html).is_none());
}
#[test]
fn a_self_closing_outlet_yields_empty_content() {
let html = r#"<div data-krab-router-outlet/>"#;
assert_eq!(extract_outlet_html(html).as_deref(), Some(""));
}
#[test]
fn outlet_works_on_tags_other_than_main() {
let html = r#"<section id="x" data-krab-router-outlet><p>hi</p></section>"#;
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>hi</p>"));
}
#[test]
fn the_marker_inside_a_comment_is_not_an_outlet() {
let html = r#"<html><body>
<!-- put <main data-krab-router-outlet> here -->
<main data-krab-router-outlet><p>real</p></main>
</body></html>"#;
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>real</p>"));
}
#[test]
fn the_marker_inside_a_script_is_not_an_outlet() {
let html = concat!(
r#"<html><body>"#,
r#"<script>var sel = "[data-krab-router-outlet]";</script>"#,
r#"<main data-krab-router-outlet><p>real</p></main>"#,
r#"</body></html>"#
);
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>real</p>"));
}
#[test]
fn the_marker_inside_an_attribute_value_is_not_an_outlet() {
let html = concat!(
r#"<div data-doc="data-krab-router-outlet">docs</div>"#,
r#"<main data-krab-router-outlet><p>real</p></main>"#
);
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>real</p>"));
}
#[test]
fn a_close_tag_inside_a_script_does_not_truncate_the_outlet() {
let html = concat!(
r#"<main data-krab-router-outlet>"#,
r#"<script>var s = "</main>";</script>"#,
r#"<p>tail</p>"#,
r#"</main>"#
);
let extracted = extract_outlet_html(html).expect("outlet not found");
assert!(
extracted.contains("<p>tail</p>"),
"a </main> inside a script body truncated the outlet: {extracted}"
);
}
#[test]
fn a_close_tag_inside_a_comment_does_not_truncate_the_outlet() {
let html = concat!(
r#"<main data-krab-router-outlet>"#,
r#"<!-- </main> -->"#,
r#"<p>tail</p>"#,
r#"</main>"#
);
let extracted = extract_outlet_html(html).expect("outlet not found");
assert!(extracted.contains("<p>tail</p>"), "got: {extracted}");
}
#[test]
fn a_doctype_and_stray_angle_brackets_are_tolerated() {
let html = concat!(
"<!doctype html><html><body><p>a < b</p>",
r#"<main data-krab-router-outlet><p>real</p></main>"#,
"</body></html>"
);
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>real</p>"));
}
#[test]
fn the_marker_is_matched_case_insensitively_on_any_attribute_order() {
let html = r#"<MAIN id="x" DATA-KRAB-ROUTER-OUTLET class="y"><p>hi</p></MAIN>"#;
assert_eq!(extract_outlet_html(html).as_deref(), Some("<p>hi</p>"));
}
#[test]
fn the_title_is_extracted_and_entity_decoded() {
let html = r#"<html><head><title>Krab & friends — docs</title></head></html>"#;
assert_eq!(
extract_title(html).as_deref(),
Some("Krab & friends — docs")
);
}
#[test]
fn a_title_with_attributes_is_still_found() {
let html = r#"<head><title data-x="1">Page</title></head>"#;
assert_eq!(extract_title(html).as_deref(), Some("Page"));
}
#[test]
fn a_title_mentioned_in_a_comment_is_not_the_documents_title() {
let html = r#"<head><!-- <title>wrong</title> --><title>right</title></head>"#;
assert_eq!(extract_title(html).as_deref(), Some("right"));
}
#[test]
fn a_document_without_a_title_yields_none() {
assert!(extract_title("<html><body>none</body></html>").is_none());
}
#[test]
fn entity_decoding_leaves_a_bare_ampersand_alone() {
assert_eq!(decode_html_entities("Tom & Jerry"), "Tom & Jerry");
assert_eq!(
decode_html_entities("a ¬anentity; b"),
"a ¬anentity; b"
);
assert_eq!(decode_html_entities("<tag>"), "<tag>");
assert_eq!(decode_html_entities("AB"), "AB");
}
}