use std::cell::RefCell;
use std::rc::Rc;
use muskitty_dom::{Attribute, Namespace, Node, NodeKind};
use super::helpers;
use super::HtmlTreeConstructor;
use crate::error::ParseError;
use muskitty_html5_tokenizer::{TagKind, TagToken, Token, Tokenizer};
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
fn adjusted_current_node(parser: &HtmlTreeConstructor) -> Option<Rc<RefCell<Node>>> {
if parser.fragment_context.is_some() && parser.open_elements.len() == 1 {
return parser.fragment_context.clone();
}
Some(parser.current_node())
}
pub fn is_mathml_text_integration_point(node: &Rc<RefCell<Node>>) -> bool {
let n = node.borrow();
if let NodeKind::Element(e) = &n.kind {
if e.namespace == Namespace::MathMl {
return matches!(e.local_name.as_str(), "mi" | "mo" | "mn" | "ms" | "mtext");
}
}
false
}
pub fn is_html_integration_point(node: &Rc<RefCell<Node>>) -> bool {
let n = node.borrow();
if let NodeKind::Element(e) = &n.kind {
match e.namespace {
Namespace::MathMl => {
if e.local_name == "annotation-xml" {
return e
.attributes
.iter()
.find(|a| a.local_name == "encoding")
.map(|a| {
let v = a.value.to_ascii_lowercase();
v == "text/html" || v == "application/xhtml+xml"
})
.unwrap_or(false);
}
false
}
Namespace::Svg => matches!(e.local_name.as_str(), "foreignObject" | "desc" | "title"),
Namespace::Html => false,
}
} else {
false
}
}
fn adjusted_current_node_is_html(parser: &HtmlTreeConstructor) -> bool {
match adjusted_current_node(parser) {
None => true,
Some(node) => {
let n = node.borrow();
matches!(&n.kind, NodeKind::Element(e) if e.namespace == Namespace::Html)
}
}
}
pub fn dispatcher_routes_to_foreign(parser: &HtmlTreeConstructor, token: &Token) -> bool {
if parser.open_elements.is_empty() {
return false;
}
let Some(current) = adjusted_current_node(parser) else {
return false;
};
if adjusted_current_node_is_html(parser) {
return false;
}
if is_mathml_text_integration_point(¤t) {
match token {
Token::Tag(t)
if t.kind == TagKind::Start && t.name != "mglyph" && t.name != "malignmark" =>
{
return false;
}
Token::Character(_) => return false,
_ => {}
}
}
if let Token::Tag(t) = token {
if t.kind == TagKind::Start {
let n = current.borrow();
if let NodeKind::Element(e) = &n.kind {
if e.namespace == Namespace::MathMl
&& e.local_name == "annotation-xml"
&& t.name == "svg"
{
return false;
}
}
}
}
if is_html_integration_point(¤t) {
match token {
Token::Tag(t) if t.kind == TagKind::Start => return false,
Token::Character(_) => return false,
_ => {}
}
}
if matches!(token, Token::EOF) {
return false;
}
true
}
pub fn adjust_mathml_attributes(tag: &mut TagToken) {
for (name, _) in tag.attrs.iter_mut() {
if *name == "definitionurl" {
*name = "definitionURL".to_string();
}
}
}
pub fn adjust_svg_attributes(tag: &mut TagToken) {
for (name, _) in tag.attrs.iter_mut() {
let new_name = match name.as_str() {
"attributename" => "attributeName",
"attributetype" => "attributeType",
"basefrequency" => "baseFrequency",
"baseprofile" => "baseProfile",
"calcmode" => "calcMode",
"clippathunits" => "clipPathUnits",
"diffuseconstant" => "diffuseConstant",
"edgemode" => "edgeMode",
"filterunits" => "filterUnits",
"glyphref" => "glyphRef",
"gradienttransform" => "gradientTransform",
"gradientunits" => "gradientUnits",
"kernelmatrix" => "kernelMatrix",
"kernelunitlength" => "kernelUnitLength",
"keypoints" => "keyPoints",
"keysplines" => "keySplines",
"keytimes" => "keyTimes",
"lengthadjust" => "lengthAdjust",
"limitingconeangle" => "limitingConeAngle",
"markerheight" => "markerHeight",
"markerunits" => "markerUnits",
"markerwidth" => "markerWidth",
"maskcontentunits" => "maskContentUnits",
"maskunits" => "maskUnits",
"numoctaves" => "numOctaves",
"pathlength" => "pathLength",
"patterncontentunits" => "patternContentUnits",
"patterntransform" => "patternTransform",
"patternunits" => "patternUnits",
"pointsatx" => "pointsAtX",
"pointsaty" => "pointsAtY",
"pointsatz" => "pointsAtZ",
"preservealpha" => "preserveAlpha",
"preserveaspectratio" => "preserveAspectRatio",
"primitiveunits" => "primitiveUnits",
"refx" => "refX",
"refy" => "refY",
"repeatcount" => "repeatCount",
"repeatdur" => "repeatDur",
"requiredextensions" => "requiredExtensions",
"requiredfeatures" => "requiredFeatures",
"specularconstant" => "specularConstant",
"specularexponent" => "specularExponent",
"spreadmethod" => "spreadMethod",
"startoffset" => "startOffset",
"stddeviation" => "stdDeviation",
"stitchtiles" => "stitchTiles",
"surfacescale" => "surfaceScale",
"systemlanguage" => "systemLanguage",
"tablevalues" => "tableValues",
"targetx" => "targetX",
"targety" => "targetY",
"textlength" => "textLength",
"viewbox" => "viewBox",
"viewtarget" => "viewTarget",
"xchannelselector" => "xChannelSelector",
"ychannelselector" => "yChannelSelector",
"zoomandpan" => "zoomAndPan",
_ => continue,
};
*name = new_name.to_string();
}
}
pub fn adjust_foreign_attributes(tag: &mut TagToken) {
for (name, _value) in tag.attrs.iter_mut() {
let (prefix, local_name, ns_uri) = match name.as_str() {
"xlink:actuate" => ("xlink", "actuate", XLINK_NS),
"xlink:arcrole" => ("xlink", "arcrole", XLINK_NS),
"xlink:href" => ("xlink", "href", XLINK_NS),
"xlink:role" => ("xlink", "role", XLINK_NS),
"xlink:show" => ("xlink", "show", XLINK_NS),
"xlink:title" => ("xlink", "title", XLINK_NS),
"xlink:type" => ("xlink", "type", XLINK_NS),
"xml:lang" => ("xml", "lang", XML_NS),
"xml:space" => ("xml", "space", XML_NS),
"xmlns" => ("", "xmlns", XMLNS_NS),
"xmlns:xlink" => ("xmlns", "xlink", XMLNS_NS),
_ => continue,
};
*name = format!("\u{0}{prefix}\u{0}{local_name}\u{0}{ns_uri}");
}
}
pub fn adjust_svg_tag_name(name: &str) -> &str {
match name {
"altglyph" => "altGlyph",
"altglyphdef" => "altGlyphDef",
"altglyphitem" => "altGlyphItem",
"animatecolor" => "animateColor",
"animatemotion" => "animateMotion",
"animatetransform" => "animateTransform",
"clippath" => "clipPath",
"feblend" => "feBlend",
"fecolormatrix" => "feColorMatrix",
"fecomponenttransfer" => "feComponentTransfer",
"fecomposite" => "feComposite",
"feconvolvematrix" => "feConvolveMatrix",
"fediffuselighting" => "feDiffuseLighting",
"fedisplacementmap" => "feDisplacementMap",
"fedistantlight" => "feDistantLight",
"fedropshadow" => "feDropShadow",
"feflood" => "feFlood",
"fefunca" => "feFuncA",
"fefuncb" => "feFuncB",
"fefuncg" => "feFuncG",
"fefuncr" => "feFuncR",
"fegaussianblur" => "feGaussianBlur",
"feimage" => "feImage",
"femerge" => "feMerge",
"femergenode" => "feMergeNode",
"femorphology" => "feMorphology",
"feoffset" => "feOffset",
"fepointlight" => "fePointLight",
"fespecularlighting" => "feSpecularLighting",
"fespotlight" => "feSpotLight",
"fetile" => "feTile",
"feturbulence" => "feTurbulence",
"foreignobject" => "foreignObject",
"glyphref" => "glyphRef",
"lineargradient" => "linearGradient",
"radialgradient" => "radialGradient",
"textpath" => "textPath",
_ => name,
}
}
fn build_attribute(name: &str, value: &str) -> Attribute {
if name.starts_with('\u{0}') {
let rest = &name[3..]; let mut parts = rest.splitn(3, '\u{0}');
let prefix = parts.next().unwrap_or("");
let local_name = parts.next().unwrap_or("");
let ns_uri = parts.next().unwrap_or("");
let prefix = if prefix.is_empty() {
None
} else {
Some(prefix.to_string())
};
let namespace_uri = if ns_uri.is_empty() {
None
} else {
Some(ns_uri.to_string())
};
Attribute {
prefix,
namespace_uri,
local_name: local_name.to_string(),
value: value.to_string(),
}
} else {
Attribute::new(name, value)
}
}
pub fn insert_foreign_element(
parser: &mut HtmlTreeConstructor,
token: &TagToken,
namespace: Namespace,
only_add_to_element_stack: bool,
) -> Rc<RefCell<Node>> {
let attrs: Vec<Attribute> = token
.attrs
.iter()
.map(|(name, value)| build_attribute(name, value))
.collect();
let element =
Node::new_element_ns(token.name.clone(), namespace, None, attrs, &parser.document);
if !only_add_to_element_stack {
helpers::insert_node(parser, &element);
}
helpers::push_open_element(parser, element.clone());
element
}
pub fn process_in_foreign_content(
parser: &mut HtmlTreeConstructor,
token: &Token,
tokenizer: &mut dyn Tokenizer,
) -> super::dispatch::Step {
use super::dispatch::Step;
match token {
Token::Character('\0') => {
parser
.errors
.push(ParseError::Generic("unexpected-null-character"));
helpers::insert_character(parser, '\u{FFFD}');
Step::Done
}
Token::Character(c) if matches!(c, '\t' | '\n' | '\u{000C}' | '\r' | ' ') => {
helpers::insert_character(parser, *c);
Step::Done
}
Token::Character(c) => {
helpers::insert_character(parser, *c);
parser.frameset_ok = false;
Step::Done
}
Token::Comment(data) => {
helpers::insert_comment(parser, data);
Step::Done
}
Token::ProcessingInstruction { target, data } => {
helpers::insert_processing_instruction(parser, target, data);
Step::Done
}
Token::Doctype(_) => {
parser
.errors
.push(ParseError::Generic("unexpected-doctype-in-foreign-content"));
Step::Done
}
Token::Tag(tag) => {
if tag.kind == TagKind::Start {
process_start_tag_in_foreign(parser, tag, tokenizer)
} else {
process_end_tag_in_foreign(parser, tag, tokenizer)
}
}
Token::EOF => {
Step::Done
}
}
}
fn process_start_tag_in_foreign(
parser: &mut HtmlTreeConstructor,
tag: &TagToken,
_tokenizer: &mut dyn Tokenizer,
) -> super::dispatch::Step {
use super::dispatch::Step;
let name = tag.name.as_str();
let is_html_breakout = matches!(
name,
"b" | "big"
| "blockquote"
| "body"
| "br"
| "center"
| "code"
| "dd"
| "div"
| "dl"
| "dt"
| "em"
| "embed"
| "h1"
| "h2"
| "h3"
| "h4"
| "h5"
| "h6"
| "head"
| "hr"
| "i"
| "img"
| "li"
| "listing"
| "menu"
| "meta"
| "nobr"
| "ol"
| "p"
| "pre"
| "ruby"
| "s"
| "small"
| "span"
| "strong"
| "strike"
| "sub"
| "sup"
| "table"
| "tt"
| "u"
| "ul"
| "var"
) || (name == "font"
&& tag
.attrs
.iter()
.any(|(n, _)| matches!(n.as_str(), "color" | "face" | "size")));
if is_html_breakout {
parser
.errors
.push(ParseError::Generic("html-element-in-foreign-content"));
loop {
let current = parser.current_node();
let should_stop = {
let n = current.borrow();
match &n.kind {
NodeKind::Element(e) if e.namespace == Namespace::Html => true,
_ => {
is_mathml_text_integration_point(¤t)
|| is_html_integration_point(¤t)
}
}
};
if should_stop {
break;
}
parser.open_elements.pop();
}
parser.skip_foreign_dispatch_once = true;
return Step::Reprocess;
}
let current = parser.current_node();
let current_ns = {
let n = current.borrow();
match &n.kind {
NodeKind::Element(e) => e.namespace,
_ => Namespace::Html,
}
};
let mut adjusted_tag = tag.clone();
if current_ns == Namespace::MathMl {
adjust_mathml_attributes(&mut adjusted_tag);
}
if current_ns == Namespace::Svg {
let new_name = adjust_svg_tag_name(&adjusted_tag.name).to_string();
adjusted_tag.name = new_name;
adjust_svg_attributes(&mut adjusted_tag);
}
adjust_foreign_attributes(&mut adjusted_tag);
let new_element = insert_foreign_element(parser, &adjusted_tag, current_ns, false);
if tag.self_closing {
let is_svg_script = {
let n = new_element.borrow();
matches!(&n.kind, NodeKind::Element(e) if e.namespace == Namespace::Svg && e.local_name == "script")
};
if is_svg_script {
parser.open_elements.pop();
} else {
parser.open_elements.pop();
}
}
Step::Done
}
fn process_end_tag_in_foreign(
parser: &mut HtmlTreeConstructor,
tag: &TagToken,
tokenizer: &mut dyn Tokenizer,
) -> super::dispatch::Step {
use super::dispatch::Step;
let name = tag.name.as_str();
if name == "br" || name == "p" {
parser
.errors
.push(ParseError::Generic("html-element-in-foreign-content"));
loop {
let current = parser.current_node();
let should_stop = {
let n = current.borrow();
match &n.kind {
NodeKind::Element(e) if e.namespace == Namespace::Html => true,
_ => {
is_mathml_text_integration_point(¤t)
|| is_html_integration_point(¤t)
}
}
};
if should_stop {
break;
}
parser.open_elements.pop();
}
parser.skip_foreign_dispatch_once = true;
return Step::Reprocess;
}
if name == "script" {
let current = parser.current_node();
let is_svg_script = {
let n = current.borrow();
matches!(&n.kind, NodeKind::Element(e) if e.namespace == Namespace::Svg && e.local_name == "script")
};
if is_svg_script {
parser.open_elements.pop();
let _ = tokenizer; return Step::Done;
}
}
let mut idx = parser.open_elements.len();
if idx == 0 {
return Step::Done;
}
idx -= 1;
{
let node = &parser.open_elements[idx];
let n = node.borrow();
if let NodeKind::Element(e) = &n.kind {
let node_lower = e.local_name.to_ascii_lowercase();
let token_lower = name.to_ascii_lowercase();
if node_lower != token_lower {
parser.errors.push(ParseError::Generic(
"end-tag-name-mismatch-in-foreign-content",
));
}
}
}
loop {
if idx == 0 {
return Step::Done;
}
let node_lower = {
let node = &parser.open_elements[idx];
let n = node.borrow();
match &n.kind {
NodeKind::Element(e) => Some(e.local_name.to_ascii_lowercase()),
_ => None,
}
};
if node_lower.as_deref() == Some(&name.to_ascii_lowercase()) {
while parser.open_elements.len() > idx {
parser.open_elements.pop();
}
return Step::Done;
}
idx -= 1;
let is_html = {
let node = &parser.open_elements[idx];
let n = node.borrow();
matches!(&n.kind, NodeKind::Element(e) if e.namespace == Namespace::Html)
};
if !is_html {
continue;
}
let token = Token::Tag(tag.clone());
return super::dispatch::dispatch_in_current_mode(parser, &token, tokenizer);
}
}