refactor(html): share effective attribute traversal across frame boundaries

This commit is contained in:
ldm0
2026-11-13 19:26:46 +08:00
committed by Donough Liu
parent 195ed413d1
commit 20fc626aa5
4 changed files with 209 additions and 52 deletions
@@ -0,0 +1,78 @@
use super::{Attribute, HtmlSerializationPolicy, NativeNodeId};
pub(super) enum EmbeddedAttribute {
Srcdoc,
FrameUrl,
}
impl EmbeddedAttribute {
pub(super) fn for_attribute(attribute: &Attribute) -> Option<Self> {
if !attribute.namespace().is_empty() {
return None;
}
match attribute.local_name() {
"srcdoc" => Some(Self::Srcdoc),
"data-moli-frame-url" => Some(Self::FrameUrl),
_ => None,
}
}
}
/// A borrowed view; only the index must survive an embedded Document traversal.
pub(super) struct EffectiveAttributes<'a> {
owner: NativeNodeId,
original: &'a [Attribute],
overrides: &'a [Attribute],
filter: Option<&'a dyn HtmlSerializationPolicy>,
}
impl<'a> EffectiveAttributes<'a> {
pub(super) fn new(
owner: NativeNodeId,
original: &'a [Attribute],
overrides: &'a [Attribute],
filter: Option<&'a dyn HtmlSerializationPolicy>,
) -> Self {
Self {
owner,
original,
overrides,
filter,
}
}
#[inline]
pub(super) fn next(&self, index: &mut usize, embedded: bool) -> Option<&'a Attribute> {
loop {
let position = *index;
let attribute = if let Some(original) = self.original.get(position) {
*index += 1;
self.overrides
.iter()
.find(|a| same_key(a, original))
.unwrap_or(original)
} else {
let added = self.overrides.get(position - self.original.len())?;
*index += 1;
if self.original.iter().any(|a| same_key(a, added)) {
continue;
}
added
};
// Live frame output always replaces these values, even when a
// source-attribute filter would exclude them. Ordinary attributes
// are filtered after overrides in both traversal paths.
if embedded && EmbeddedAttribute::for_attribute(attribute).is_some()
|| self
.filter
.is_none_or(|p| p.include_attribute(self.owner, attribute))
{
return Some(attribute);
}
}
}
}
fn same_key(a: &Attribute, b: &Attribute) -> bool {
a.namespace() == b.namespace() && a.local_name() == b.local_name()
}
@@ -361,3 +361,105 @@ fn namespaced_frame_attributes_do_not_replace_the_null_namespace_export_values()
);
}
}
#[test]
fn effective_attribute_order_and_filtering_match_with_and_without_embedded_documents() {
struct Policy {
owner: NativeNodeId,
overrides: Vec<Attribute>,
filtering: bool,
}
impl HtmlSerializationPolicy for Policy {
fn has_filters(&self) -> bool {
self.filtering
}
fn attribute_overrides(&self, node: NativeNodeId) -> &[Attribute] {
if node == self.owner {
&self.overrides
} else {
&[]
}
}
fn include_attribute(&self, _: NativeNodeId, attribute: &Attribute) -> bool {
assert!(self.filtering, "inactive filters must not be called");
attribute.value() != "drop"
}
}
for existing_srcdoc in [false, true] {
let mut host = host();
let root = host.document_handle();
let owner = child(&mut host, root, "iframe");
assert!(host.set_attribute(owner, "title", "old"));
assert!(host.set_attribute(owner, "data-removed", "drop"));
if existing_srcdoc {
assert!(host.set_attribute(owner, "srcdoc", "stale"));
}
assert!(host.set_attribute_ns(owner, Some("urn:code"), Some("before"), "code", "old"));
assert!(host.set_attribute(owner, "data-after", "kept"));
let document = host.create_detached_html_document();
let b = child(&mut host, document, "b");
text(&mut host, b, "live");
let docs = Documents {
entries: vec![(owner, document, "about:blank".into())],
..Default::default()
};
let mut policy = Policy {
owner,
overrides: vec![
Attribute::new("title".into(), "".into(), None, "new & title".into()),
Attribute::new(
"code".into(),
"urn:code".into(),
Some("after".into()),
"new".into(),
),
Attribute::new("srcdoc".into(), "".into(), None, "override".into()),
Attribute::new("data-added-drop".into(), "".into(), None, "drop".into()),
Attribute::new("code".into(), "".into(), None, "plain".into()),
Attribute::new("data-extra".into(), "".into(), None, "last".into()),
],
filtering: true,
};
let before = host.dom().serialize_document();
for filtering in [true, false] {
policy.filtering = filtering;
for embedded in [false, true] {
let output = host
.get_html_for_export(
root,
&|_| true,
Some(&policy),
embedded.then_some(&docs as &dyn HtmlEmbeddedDocumentProvider),
None,
)
.unwrap();
let srcdoc = if embedded {
" srcdoc=\"&lt;b&gt;live&lt;/b&gt;\""
} else {
" srcdoc=\"override\""
};
let mut expected = "<iframe title=\"new &amp; title\"".to_owned();
if !filtering {
expected.push_str(" data-removed=\"drop\"");
}
if existing_srcdoc {
expected.push_str(srcdoc);
}
expected.push_str(" after:code=\"new\" data-after=\"kept\"");
if !existing_srcdoc {
expected.push_str(srcdoc);
}
if !filtering {
expected.push_str(" data-added-drop=\"drop\"");
}
expected.push_str(" code=\"plain\" data-extra=\"last\"");
if embedded {
expected.push_str(" data-moli-frame-url=\"about:blank\"");
}
expected.push_str("></iframe>");
assert_eq!(output, expected);
assert_eq!(host.dom().serialize_document(), before);
}
}
}
}
@@ -1,5 +1,6 @@
use super::super::NativeDom;
use super::super::node::{NativeNodeId, Node, NodeData};
use super::attributes::{EffectiveAttributes, EmbeddedAttribute};
use super::{
HtmlEmbeddedDocument, HtmlEmbeddedDocumentProvider, HtmlInsertionPoint, HtmlSerializationError,
HtmlSerializationInsertion, HtmlSerializationLimitExceeded, HtmlSerializationPolicy,
@@ -500,23 +501,16 @@ impl<'dom, S: HtmlSerializationSink, const EMBEDDED: bool, const POLICY: bool>
self.out.attribute(attribute);
}
} else {
for attribute in element.attributes() {
let attributes =
EffectiveAttributes::new(id, element.attributes(), overrides, filter);
let mut index = 0;
loop {
if self.out.limit_exceeded() {
return Ok(());
}
let output = replacement_attribute(attribute, overrides);
if filter.is_none_or(|p| p.include_attribute(id, output)) {
self.out.attribute(output);
}
}
}
for attribute in overrides {
if !element
.attributes()
.iter()
.any(|a| attribute_key_eq(a, attribute))
&& filter.is_none_or(|p| p.include_attribute(id, attribute))
{
let Some(attribute) = attributes.next(&mut index, false) else {
break;
};
self.out.attribute(attribute);
}
}
@@ -608,34 +602,28 @@ impl<'dom, S: HtmlSerializationSink, const EMBEDDED: bool, const POLICY: bool>
.options
.policy
.filter(|_| POLICY && self.options.filtering);
while state.next_attribute < element.attributes().len() + overrides.len() {
let index = state.next_attribute;
state.next_attribute += 1;
let attribute = if let Some(attribute) = element.attributes().get(index) {
replacement_attribute(attribute, overrides)
} else {
let attribute = &overrides[index - element.attributes().len()];
if element
.attributes()
.iter()
.any(|a| attribute_key_eq(a, attribute))
{
continue;
}
attribute
};
if attribute.namespace().is_empty() && attribute.local_name() == "srcdoc" {
state.wrote_srcdoc = true;
self.start_embedded(state)?;
let attributes =
EffectiveAttributes::new(state.owner, element.attributes(), overrides, filter);
loop {
if self.out.limit_exceeded() {
return Ok(());
}
if attribute.namespace().is_empty() && attribute.local_name() == "data-moli-frame-url" {
state.wrote_url = true;
self.out.push_str(" data-moli-frame-url=\"");
self.out.attribute_value(&state.embedded.url);
self.out.push('"');
} else if filter.is_none_or(|p| p.include_attribute(state.owner, attribute)) {
self.out.attribute(attribute);
let Some(attribute) = attributes.next(&mut state.next_attribute, true) else {
break;
};
match EmbeddedAttribute::for_attribute(attribute) {
Some(EmbeddedAttribute::Srcdoc) => {
state.wrote_srcdoc = true;
self.start_embedded(state)?;
return Ok(());
}
Some(EmbeddedAttribute::FrameUrl) => {
state.wrote_url = true;
self.out.push_str(" data-moli-frame-url=\"");
self.out.attribute_value(&state.embedded.url);
self.out.push('"');
}
None => self.out.attribute(attribute),
}
}
if !state.wrote_srcdoc {
@@ -674,18 +662,6 @@ impl<'dom, S: HtmlSerializationSink, const EMBEDDED: bool, const POLICY: bool>
}
}
fn attribute_key_eq(a: &super::super::Attribute, b: &super::super::Attribute) -> bool {
a.namespace() == b.namespace() && a.local_name() == b.local_name()
}
fn replacement_attribute<'a>(
attribute: &'a super::super::Attribute,
overrides: &'a [super::super::Attribute],
) -> &'a super::super::Attribute {
overrides
.iter()
.find(|a| attribute_key_eq(a, attribute))
.unwrap_or(attribute)
}
#[inline(always)]
fn serialize_attribute<S: HtmlSerializationSink>(attribute: &super::super::Attribute, out: &mut S) {
out.push(' ');
@@ -1,3 +1,4 @@
mod attributes;
mod engine;
#[cfg(test)]