fix(dom): preserve namespaced attribute UTF-16 values

Keep lone surrogates through setAttributeNS and SVG href writes, with
rare values keyed by namespace and local name. Preserve them through
native and windowless cloning, and refresh native receivers after value
conversion can adopt the element into another document.

Cover independent namespace values, cache cleanup, clone/import, href
fallback, reentrant conversion, native brands and allocation behavior.

Validation: cargo fmt --all; strict workspace/all-targets/all-features
clippy; cargo nextest run --no-fail-fast (32 threads, CI retry profile).
Summary [ 128.190s] 20618 tests run: 20618 passed (9 slow), 16 skipped
This commit is contained in:
ldm0
2026-11-19 00:50:29 +08:00
parent 806b36eed1
commit 3b101b3650
16 changed files with 499 additions and 94 deletions
+48 -7
View File
@@ -26,7 +26,7 @@ impl NativeDom {
})?;
Some(
element
.attribute_utf16_units(&attribute.name())
.attribute_ns_utf16_units(attribute.namespace(), attribute.local_name())
.map_or_else(
|| attribute.value().encode_utf16().collect(),
<[u16]>::to_vec,
@@ -152,6 +152,37 @@ impl NativeDom {
prefix: Option<&str>,
local_name: &str,
value: &str,
) -> bool {
self.set_attribute_ns_with_utf16_units(node_id, namespace, prefix, local_name, value, None)
}
pub fn set_attribute_ns_utf16_units(
&mut self,
node_id: NativeNodeId,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
value: &str,
units: Vec<u16>,
) -> bool {
self.set_attribute_ns_with_utf16_units(
node_id,
namespace,
prefix,
local_name,
value,
Some(units),
)
}
fn set_attribute_ns_with_utf16_units(
&mut self,
node_id: NativeNodeId,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
value: &str,
units: Option<Vec<u16>>,
) -> bool {
#[cfg(any(test, feature = "test-support"))]
super::serialization_probe::record(super::serialization_probe::Access::Mutation);
@@ -162,12 +193,22 @@ impl NativeDom {
.node_mut(node_id)
.and_then(|node| node.data_mut().as_element_mut())
.is_some_and(|element| {
element.set_attribute_ns(
local_name.to_owned(),
namespace.to_owned(),
prefix.map(str::to_owned),
value.to_owned(),
)
if let Some(units) = units {
element.set_attribute_ns_utf16_units(
local_name.to_owned(),
namespace.to_owned(),
prefix.map(str::to_owned),
value.to_owned(),
units,
)
} else {
element.set_attribute_ns(
local_name.to_owned(),
namespace.to_owned(),
prefix.map(str::to_owned),
value.to_owned(),
)
}
});
if changed && let Some(document) = base_document {
self.process_base_element(document, false);
+53 -22
View File
@@ -220,12 +220,18 @@ impl Element {
}
pub fn attribute_utf16_units(&self, name: &str) -> Option<&[u16]> {
let qualified_name = self
let attribute = self
.attributes
.iter()
.find(|attribute| attribute.name_matches(name))
.map(Attribute::name)?;
self.rare_data.attribute_utf16_units(&qualified_name)
.find(|attribute| attribute.name_matches(name))?;
self.rare_data.attribute_utf16_units(attribute)
}
pub fn attribute_ns_utf16_units(&self, namespace: &str, local_name: &str) -> Option<&[u16]> {
let attribute = self.attributes.iter().find(|attribute| {
attribute.namespace() == namespace && attribute.local_name() == local_name
})?;
self.rare_data.attribute_utf16_units(attribute)
}
pub fn attribute_ns(&self, namespace: &str, local_name: &str) -> Option<&str> {
@@ -1338,18 +1344,17 @@ impl Element {
// insertion paths). Once an attribute is matched by its existing qualified name, we
// preserve its current namespace/prefix and only update the value. Callers that need
// namespace/local-name replacement semantics must go through `set_attribute_ns()`.
let qualified_name = self.attributes[index].name();
if self.attributes[index].value() == value
&& self
.rare_data
.attribute_utf16_units(&qualified_name)
.attribute_utf16_units(&self.attributes[index])
.is_none()
{
return false;
}
self.attributes[index].value = value.into_boxed_str();
self.rare_data
.set_attribute_utf16_units(qualified_name, None);
.set_attribute_utf16_units(&self.attributes[index], None);
let attribute_local_name = self.attributes[index].local_name.clone();
self.sync_control_state_from_attribute(
attribute_local_name.as_ref(),
@@ -1386,16 +1391,17 @@ impl Element {
.iter()
.position(|attribute| attribute.name_matches(&local_name))
{
let qualified_name = self.attributes[index].name();
if self.attributes[index].value.as_ref() == value
&& self.rare_data.attribute_utf16_units(&qualified_name)
&& self
.rare_data
.attribute_utf16_units(&self.attributes[index])
== value_utf16_units.as_deref()
{
return false;
}
self.attributes[index].value = value.into_boxed_str();
self.rare_data
.set_attribute_utf16_units(qualified_name, value_utf16_units);
.set_attribute_utf16_units(&self.attributes[index], value_utf16_units);
let attribute_local_name = self.attributes[index].local_name.clone();
self.sync_control_state_from_attribute(
attribute_local_name.as_ref(),
@@ -1411,13 +1417,12 @@ impl Element {
prefix: prefix.map(Prefix::from),
value: value.into_boxed_str(),
});
let qualified_name = self
let attribute = self
.attributes
.last()
.expect("new attribute must be present")
.name();
.expect("new attribute must be present");
self.rare_data
.set_attribute_utf16_units(qualified_name, value_utf16_units);
.set_attribute_utf16_units(attribute, value_utf16_units);
self.sync_control_state_from_attribute(attribute_local_name.as_ref(), Some(&next_value));
true
}
@@ -1428,24 +1433,47 @@ impl Element {
namespace: String,
prefix: Option<String>,
value: String,
) -> bool {
self.set_attribute_ns_with_utf16_units(local_name, namespace, prefix, value, None)
}
pub fn set_attribute_ns_utf16_units(
&mut self,
local_name: String,
namespace: String,
prefix: Option<String>,
value: String,
units: Vec<u16>,
) -> bool {
let units =
utf16_units_contain_unpaired_surrogate(&units).then(|| units.into_boxed_slice());
self.set_attribute_ns_with_utf16_units(local_name, namespace, prefix, value, units)
}
fn set_attribute_ns_with_utf16_units(
&mut self,
local_name: String,
namespace: String,
prefix: Option<String>,
value: String,
units: Option<Box<[u16]>>,
) -> bool {
self.synchronize_element_reference_attribute(&namespace, &local_name);
let next_value = value.clone();
if let Some(index) = self.attributes.iter().position(|attribute| {
attribute.local_name() == local_name && attribute.namespace() == namespace
}) {
let qualified_name = self.attributes[index].name();
if self.attributes[index].value() == value
&& self
.rare_data
.attribute_utf16_units(&qualified_name)
.is_none()
.attribute_utf16_units(&self.attributes[index])
== units.as_deref()
{
return false;
}
self.attributes[index].value = value.into_boxed_str();
self.rare_data
.set_attribute_utf16_units(qualified_name, None);
.set_attribute_utf16_units(&self.attributes[index], units);
self.sync_control_state_from_attribute(&local_name, Some(&next_value));
return true;
}
@@ -1457,6 +1485,11 @@ impl Element {
prefix: prefix.map(Prefix::from),
value: value.into_boxed_str(),
});
let attribute = self
.attributes
.last()
.expect("new attribute must be present");
self.rare_data.set_attribute_utf16_units(attribute, units);
self.sync_control_state_from_attribute(attribute_local_name.as_ref(), Some(&next_value));
true
}
@@ -1484,8 +1517,7 @@ impl Element {
};
let attribute = self.attributes.remove(index);
self.invalidate_dialog_modal_opening_for_removed_attribute(&attribute);
self.rare_data
.set_attribute_utf16_units(attribute.name(), None);
self.rare_data.set_attribute_utf16_units(&attribute, None);
self.sync_control_state_from_attribute(attribute.local_name.as_ref(), None);
true
}
@@ -1499,8 +1531,7 @@ impl Element {
};
let attribute = self.attributes.remove(index);
self.invalidate_dialog_modal_opening_for_removed_attribute(&attribute);
self.rare_data
.set_attribute_utf16_units(attribute.name(), None);
self.rare_data.set_attribute_utf16_units(&attribute, None);
self.sync_control_state_from_attribute(attribute.local_name.as_ref(), None);
true
}
+25 -10
View File
@@ -1,5 +1,7 @@
use std::sync::LazyLock;
use html5ever::{LocalName, Namespace};
use super::{Attribute, CustomElementState, ElementControlState};
use crate::forms::{InputType, InputValueSanitizationContext};
use crate::native::NativeNodeId;
@@ -30,7 +32,8 @@ struct ElementRareDataPayload {
custom_element_is_name: Option<String>,
parser_associated_form_owner: Option<NativeNodeId>,
template_contents: Option<NativeNodeId>,
attribute_utf16_units: Vec<(String, Box<[u16]>)>,
// Different namespaces can use the same qualified name on one element.
attribute_utf16_units: Vec<(Namespace, LocalName, Box<[u16]>)>,
}
impl ElementRareDataPayload {
@@ -70,36 +73,48 @@ impl ElementRareData {
}
}
pub(super) fn attribute_utf16_units(&self, qualified_name: &str) -> Option<&[u16]> {
pub(super) fn attribute_utf16_units(&self, attribute: &Attribute) -> Option<&[u16]> {
self.payload
.as_deref()?
.attribute_utf16_units
.iter()
.find(|(name, _)| name == qualified_name)
.map(|(_, units)| units.as_ref())
.find(|(namespace, local_name, _)| {
AsRef::<str>::as_ref(namespace) == attribute.namespace()
&& AsRef::<str>::as_ref(local_name) == attribute.local_name()
})
.map(|(_, _, units)| units.as_ref())
}
pub(super) fn set_attribute_utf16_units(
&mut self,
qualified_name: String,
attribute: &Attribute,
units: Option<Box<[u16]>>,
) -> bool {
if self.attribute_utf16_units(&qualified_name) == units.as_deref() {
if self.attribute_utf16_units(attribute) == units.as_deref() {
return false;
}
if let Some(units) = units {
let values = &mut self.payload_mut().attribute_utf16_units;
if let Some((_, current)) = values.iter_mut().find(|(name, _)| name == &qualified_name)
{
if let Some((_, _, current)) = values.iter_mut().find(|(namespace, local_name, _)| {
AsRef::<str>::as_ref(namespace) == attribute.namespace()
&& AsRef::<str>::as_ref(local_name) == attribute.local_name()
}) {
*current = units;
} else {
values.push((qualified_name, units));
values.push((
Namespace::from(attribute.namespace()),
LocalName::from(attribute.local_name()),
units,
));
}
} else if let Some(payload) = self.payload.as_deref_mut() {
payload
.attribute_utf16_units
.retain(|(name, _)| name != &qualified_name);
.retain(|(namespace, local_name, _)| {
AsRef::<str>::as_ref(namespace) != attribute.namespace()
|| AsRef::<str>::as_ref(local_name) != attribute.local_name()
});
}
self.release_empty_payload();
true
+39
View File
@@ -27,6 +27,45 @@ fn ordinary_elements_keep_control_state_unmaterialized_until_needed() {
assert!(div.rare_data.is_materialized());
}
#[test]
fn namespaced_utf16_values_track_code_unit_changes_and_release_rare_data() {
let mut element = Element::new_html("div");
let write = |element: &mut Element, units: Vec<u16>| {
element.set_attribute_ns_utf16_units(
"value".to_owned(),
"urn:value".to_owned(),
Some("p".to_owned()),
String::from_utf16_lossy(&units),
units,
)
};
// Valid pairs need no sidecar; both lone surrogates serialize to U+FFFD but
// are distinct DOMString values and must count as separate native writes.
assert!(write(&mut element, vec![0xD800, 0xDC00]));
assert!(!element.rare_data.is_materialized());
assert!(write(&mut element, vec![0xD800]));
assert!(element.rare_data.is_materialized());
assert!(!write(&mut element, vec![0xD800]));
assert!(write(&mut element, vec![0xDC00]));
assert_eq!(
element.attribute_ns_utf16_units("urn:value", "value"),
Some([0xDC00].as_slice())
);
assert!(element.set_attribute_ns(
"value".to_owned(),
"urn:value".to_owned(),
Some("p".to_owned()),
"\u{FFFD}".to_owned(),
));
assert_eq!(element.attribute_ns_utf16_units("urn:value", "value"), None);
assert!(!element.rare_data.is_materialized());
assert!(write(&mut element, vec![0xD800]));
assert!(element.remove_attribute_ns("urn:value", "value"));
assert!(!element.rare_data.is_materialized());
}
#[test]
fn stateful_element_kinds_materialize_control_state_during_construction() {
for local_name in ["input", "textarea", "option", "audio", "video", "script"] {
+20 -6
View File
@@ -544,12 +544,26 @@ impl DomHost {
return;
};
for attribute in element.attributes() {
let _ = clone_element.set_attribute(
attribute.local_name().to_owned(),
attribute.namespace().to_owned(),
attribute.prefix().map(str::to_owned),
attribute.value().to_owned(),
);
// A qualified name can occur in more than one namespace. Preserve
// each expanded name and its DOMString instead of merging by name.
if let Some(units) =
element.attribute_ns_utf16_units(attribute.namespace(), attribute.local_name())
{
clone_element.set_attribute_ns_utf16_units(
attribute.local_name().to_owned(),
attribute.namespace().to_owned(),
attribute.prefix().map(str::to_owned),
attribute.value().to_owned(),
units.to_vec(),
);
} else {
clone_element.set_attribute_ns(
attribute.local_name().to_owned(),
attribute.namespace().to_owned(),
attribute.prefix().map(str::to_owned),
attribute.value().to_owned(),
);
}
}
let _ =
clone_element.set_cryptographic_nonce(element.cryptographic_nonce().map(str::to_owned));
@@ -337,6 +337,39 @@ impl DomHost {
prefix: Option<&str>,
local_name: &str,
value: &str,
) -> DomAttributeMutationOutcome {
self.set_attribute_ns_mutation_outcome_with_utf16_units(
handle, namespace, prefix, local_name, value, None,
)
}
pub fn set_attribute_ns_utf16_units_mutation_outcome(
&mut self,
handle: DomHandle,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
value: &str,
units: Vec<u16>,
) -> DomAttributeMutationOutcome {
self.set_attribute_ns_mutation_outcome_with_utf16_units(
handle,
namespace,
prefix,
local_name,
value,
Some(units),
)
}
fn set_attribute_ns_mutation_outcome_with_utf16_units(
&mut self,
handle: DomHandle,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
value: &str,
units: Option<Vec<u16>>,
) -> DomAttributeMutationOutcome {
let namespace = namespace.filter(|namespace| !namespace.is_empty());
if namespace.is_none() && local_name.eq_ignore_ascii_case("form") {
@@ -346,9 +379,13 @@ impl DomHost {
let prior_value = self
.get_attribute_ns(handle, namespace, local_name)
.map(Arc::from);
let changed = self
.dom
.set_attribute_ns(handle, namespace, prefix, local_name, value);
let changed = if let Some(units) = units {
self.dom
.set_attribute_ns_utf16_units(handle, namespace, prefix, local_name, value, units)
} else {
self.dom
.set_attribute_ns(handle, namespace, prefix, local_name, value)
};
if changed {
self.invalidate_shadow_slot_name_index_for_attribute(handle, namespace, local_name);
// Namespace-aware calls can still target HTML id/name by local name.
@@ -1214,6 +1214,7 @@ impl DocumentRuntime {
local_name,
qualified_name,
value,
None,
AttributeChangedReactionPolicy::DispatchNow,
)
}
@@ -1238,6 +1239,33 @@ impl DocumentRuntime {
local_name,
qualified_name,
value,
None,
AttributeChangedReactionPolicy::EnqueueInCurrentQueue,
)
}
pub(crate) fn set_attribute_ns_utf16_units_appending_to_current_reaction_queue(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
handle: DomHandle,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
qualified_name: &str,
value: &str,
units: Vec<u16>,
) -> bool {
self.set_attribute_ns_with_reaction_policy(
scope,
host_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
Some(units),
AttributeChangedReactionPolicy::EnqueueInCurrentQueue,
)
}
@@ -1252,6 +1280,7 @@ impl DocumentRuntime {
local_name: &str,
qualified_name: &str,
value: &str,
units: Option<Vec<u16>>,
reaction_policy: AttributeChangedReactionPolicy,
) -> bool {
let started = dom_binding_timing_started();
@@ -1274,10 +1303,15 @@ impl DocumentRuntime {
let derived_old_style_states = self.retained_derived_old_style_states_for_attribute_impact(
host_ptr, handle, namespace, local_name, state,
);
let (effects, old_value) = self
.dom_host
.set_attribute_ns_mutation_outcome(handle, namespace, prefix, local_name, value)
.into_parts();
let outcome = if let Some(units) = units {
self.dom_host.set_attribute_ns_utf16_units_mutation_outcome(
handle, namespace, prefix, local_name, value, units,
)
} else {
self.dom_host
.set_attribute_ns_mutation_outcome(handle, namespace, prefix, local_name, value)
};
let (effects, old_value) = outcome.into_parts();
if style_impact.affects_layout_metric() && old_value.as_deref() != Some(value) {
self.note_attribute_layout_activity(host_ptr, handle, local_name);
}
@@ -1373,6 +1407,7 @@ impl DocumentRuntime {
attribute.local_name(),
&qualified_name,
attribute.value(),
None,
AttributeChangedReactionPolicy::EnqueueInCurrentQueue,
)
}
@@ -400,6 +400,26 @@ fn set_cloned_native_element_attribute<'s>(
cloned: v8::Local<'s, v8::Object>,
attribute: &DetachedNativeAttributeSnapshot,
) {
if let Some(units) = attribute.value_utf16_units.as_ref()
&& let Ok((runtime_ptr, handle)) =
node_runtime_and_handle_from_object_or_detached(scope, cloned)
{
custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
unsafe { &mut *runtime_ptr }
.set_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
attribute.namespace_uri.as_deref(),
attribute.prefix.as_deref(),
&attribute.local_name,
&attribute.name,
&attribute.value,
units.clone(),
);
});
return;
}
let has_namespace_metadata = attribute.namespace_uri.is_some()
|| attribute
.prefix
@@ -217,6 +217,9 @@ fn live_native_attribute_snapshot<'s>(
.map(|attribute| DetachedNativeAttributeSnapshot {
name: attribute.name(),
value: attribute.value().to_owned(),
value_utf16_units: element
.attribute_ns_utf16_units(attribute.namespace(), attribute.local_name())
.map(<[u16]>::to_vec),
namespace_uri: (!attribute.namespace().is_empty())
.then(|| attribute.namespace().to_owned()),
prefix: attribute.prefix().map(str::to_owned),
@@ -968,6 +968,7 @@ pub(crate) fn read_detached_native_attribute_names<'s>(
pub(crate) struct DetachedNativeAttributeSnapshot {
pub(crate) name: String,
pub(in crate::native_bridge::document) value: String,
pub(in crate::native_bridge::document) value_utf16_units: Option<Vec<u16>>,
pub(in crate::native_bridge::document) namespace_uri: Option<String>,
pub(in crate::native_bridge::document) prefix: Option<String>,
pub(in crate::native_bridge::document) local_name: String,
@@ -988,6 +989,9 @@ pub(crate) fn read_detached_native_attribute_snapshot<'s>(
.map(|attribute| DetachedNativeAttributeSnapshot {
name: attribute.name(),
value: attribute.value().to_owned(),
value_utf16_units: element
.attribute_ns_utf16_units(attribute.namespace(), attribute.local_name())
.map(<[u16]>::to_vec),
namespace_uri: (!attribute.namespace().is_empty())
.then(|| attribute.namespace().to_owned()),
prefix: attribute.prefix().map(str::to_owned),
@@ -320,7 +320,7 @@ pub(in crate::native_bridge) fn bridge_detached_set_attribute_ns_callback<'a>(
return;
}
let runtime_and_handle = detached_surface_runtime_and_handle(scope, args.this(), element);
let Some(value) = super::super::super::element::trusted_attribute_value_string(
let Some(units) = super::super::super::element::trusted_attribute_value_string16(
scope,
runtime_and_handle,
namespace.as_deref(),
@@ -330,6 +330,7 @@ pub(in crate::native_bridge) fn bridge_detached_set_attribute_ns_callback<'a>(
) else {
return;
};
let value = String::from_utf16_lossy(&units);
with_detached_surface_attribute_reaction_scope(scope, args.this(), element, |scope| {
if read_detached_native_has_attribute_ns(scope, element, namespace.as_deref(), &local_name)
.is_some()
@@ -345,6 +346,7 @@ pub(in crate::native_bridge) fn bridge_detached_set_attribute_ns_callback<'a>(
&local_name,
&qualified_name,
&value,
units,
)
.unwrap_or(false)
{
@@ -365,7 +367,10 @@ pub(in crate::native_bridge) fn bridge_detached_set_attribute_ns_callback<'a>(
{
detached_map_delete(scope, attributes, &old_name);
}
detached_map_set(scope, attributes, &qualified_name, &value);
let Some(js_value) = crate::util::v8_string_from_utf16_units(scope, &units) else {
return;
};
detached_map_set_value(scope, attributes, &qualified_name, js_value.into());
let _ = sync_detached_surface_set_attribute_ns(
scope,
args.this(),
@@ -375,11 +380,12 @@ pub(in crate::native_bridge) fn bridge_detached_set_attribute_ns_callback<'a>(
&local_name,
&qualified_name,
&value,
units,
);
let record = DetachedSurfaceNamespaceAttributeRecordDeclaration {
name: v8_string(scope, &qualified_name).unwrap_or_else(|| v8::String::empty(scope)),
value: v8_string(scope, &value).unwrap_or_else(|| v8::String::empty(scope)),
value: js_value,
namespace_uri: namespace
.as_deref()
.and_then(|namespace| v8_string(scope, namespace))
@@ -597,9 +603,10 @@ fn sync_detached_surface_set_attribute_ns<'s>(
local_name: &str,
qualified_name: &str,
value: &str,
units: Vec<u16>,
) -> Option<bool> {
let (runtime_ptr, handle) = detached_surface_runtime_and_handle(scope, bridge, element)?;
Some(crate::native_bridge::element::set_live_element_attribute_ns_appending_to_current_reaction_queue(
Some(crate::native_bridge::element::set_live_element_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
@@ -608,6 +615,7 @@ fn sync_detached_surface_set_attribute_ns<'s>(
local_name,
qualified_name,
value,
units,
))
}
+73 -12
View File
@@ -102,8 +102,7 @@ pub(crate) use script_execution::{
inline_script_source_for_execution, prepare_inline_classic_frame_script_job_for_execution,
};
pub(in crate::native_bridge) use trusted_types::{
TrustedAttributeSetter, trusted_attribute_string_value, trusted_attribute_value_string,
trusted_attribute_value_string16,
TrustedAttributeSetter, trusted_attribute_string_value, trusted_attribute_value_string16,
};
use trusted_types::{
TrustedHtmlSink, TrustedScriptElementSink, trusted_html_sink_string,
@@ -849,6 +848,54 @@ pub(in crate::native_bridge) fn set_live_element_attribute_ns_appending_to_curre
local_name: &str,
qualified_name: &str,
value: &str,
) -> bool {
set_live_element_attribute_ns_with_utf16_units(
scope,
runtime_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
None,
)
}
pub(in crate::native_bridge) fn set_live_element_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut PageScriptHost,
handle: DomHandle,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
qualified_name: &str,
value: &str,
units: Vec<u16>,
) -> bool {
set_live_element_attribute_ns_with_utf16_units(
scope,
runtime_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
Some(units),
)
}
fn set_live_element_attribute_ns_with_utf16_units(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut PageScriptHost,
handle: DomHandle,
namespace: Option<&str>,
prefix: Option<&str>,
local_name: &str,
qualified_name: &str,
value: &str,
units: Option<Vec<u16>>,
) -> bool {
if namespace.is_none() {
clear_detached_iframe_context_before_navigation_attribute_change(
@@ -865,16 +912,30 @@ pub(in crate::native_bridge) fn set_live_element_attribute_ns_appending_to_curre
Default::default()
};
let runtime = unsafe { &mut *runtime_ptr };
let did_set = runtime.set_attribute_ns_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
);
let did_set = if let Some(units) = units {
runtime.set_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
units,
)
} else {
runtime.set_attribute_ns_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
namespace,
prefix,
local_name,
qualified_name,
value,
)
};
if did_set && namespace.is_none() && local_name.eq_ignore_ascii_case("style") {
runtime.set_element_inline_style_current_base_url(handle);
}
@@ -11,10 +11,9 @@ use super::super::{
TrustedAttributeSetter, element_has_attribute,
remove_live_element_attribute_appending_to_current_reaction_queue,
remove_live_element_attribute_ns_appending_to_current_reaction_queue,
set_live_element_attribute_ns_appending_to_current_reaction_queue,
set_live_element_attribute_ns_utf16_units_appending_to_current_reaction_queue,
set_live_element_attribute_utf16_units_appending_to_current_reaction_queue,
trusted_attribute_value_string, trusted_attribute_value_string16,
update_iframe_snapshot_navigation,
trusted_attribute_value_string16, update_iframe_snapshot_navigation,
};
use super::{
AttributeNameArgs, AttributeNamespaceNameArgs, SetAttributeArgs, SetAttributeNsArgs,
@@ -121,8 +120,7 @@ pub(in crate::native_bridge) fn node_set_attribute_ns_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttributeNS")
else {
let Some((runtime_ptr, _)) = element_method_receiver(scope, &args, "setAttributeNS") else {
rv.set_undefined();
return;
};
@@ -143,7 +141,11 @@ pub(in crate::native_bridge) fn node_set_attribute_ns_callback<'s>(
return;
}
};
let Some(value) = trusted_attribute_value_string(
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttributeNS")
else {
return;
};
let Some(units) = trusted_attribute_value_string16(
scope,
Some((runtime_ptr, handle)),
namespace.as_deref(),
@@ -154,8 +156,14 @@ pub(in crate::native_bridge) fn node_set_attribute_ns_callback<'s>(
rv.set_undefined();
return;
};
let value = String::from_utf16_lossy(&units);
// Conversion may adopt the element into another native document.
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttributeNS")
else {
return;
};
custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
let _ = set_live_element_attribute_ns_appending_to_current_reaction_queue(
let _ = set_live_element_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
@@ -164,6 +172,7 @@ pub(in crate::native_bridge) fn node_set_attribute_ns_callback<'s>(
&local_name,
&parsed.qualified_name,
&value,
units,
);
});
rv.set_undefined();
@@ -417,23 +417,25 @@ pub(crate) fn set_svg_animated_string_base_value<'s>(
crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, owner).ok()?;
let namespace =
svg_animated_string_attribute_namespace(unsafe { &*runtime_ptr }, handle, attribute);
if attribute == "href" {
let _ = unsafe { &mut *runtime_ptr }.set_attribute_ns(
scope,
runtime_ptr,
handle,
namespace,
namespace.map(|_| "xlink"),
attribute,
if namespace.is_some() {
"xlink:href"
} else {
attribute
},
&value,
);
} else {
crate::custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
crate::custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
if attribute == "href" {
let _ = unsafe { &mut *runtime_ptr }
.set_attribute_ns_utf16_units_appending_to_current_reaction_queue(
scope,
runtime_ptr,
handle,
namespace,
namespace.map(|_| "xlink"),
attribute,
if namespace.is_some() {
"xlink:href"
} else {
attribute
},
&value,
units,
);
} else {
let _ = unsafe { &mut *runtime_ptr }
.set_attribute_utf16_units_appending_to_current_reaction_queue(
scope,
@@ -443,8 +445,8 @@ pub(crate) fn set_svg_animated_string_base_value<'s>(
&value,
units,
);
});
}
}
});
Some(value)
}
@@ -4155,3 +4155,13 @@ fn svg_animated_values_follow_native_attribute_mutations() {
"true"
);
}
#[test]
fn namespaced_attribute_values_preserve_utf16_and_namespace_identity() {
let mut vm = new_parsed_test_vm("https://namespace-utf16.test/", "<body></body>");
assert_eq!(
vm.eval(include_str!("namespace_attribute_string_values.js"))
.expect("namespaced attribute string fixture should evaluate"),
"true"
);
}
@@ -0,0 +1,76 @@
(() => {
const check = (value, message) => {if (!value) throw new Error(message);};
const svg = 'http://www.w3.org/2000/svg', xlink = 'http://www.w3.org/1999/xlink';
const frame = document.createElement('iframe'); document.body.append(frame);
const documents = [document, document.implementation.createHTMLDocument(),
document.implementation.createDocument('urn:xml', 'root'), frame.contentDocument];
const values = ['', 'plain', '\uD800', '\uDC00', '\uFFFD', 'x\uD800\uDC00\uDC00y'];
for (const doc of documents) {
for (const ns of [svg, 'http://www.w3.org/1999/xhtml', 'urn:xml']) {
const element = doc.createElementNS(ns, 'item');
for (const value of values) {
let conversions = 0;
element.setAttributeNS('urn:value', 'p:value', {toString() {conversions++; return value;}});
check(conversions === 1, 'convert namespaced value once');
check(element.getAttributeNS('urn:value', 'value') === value, 'namespace lookup preserves UTF-16');
check(element.getAttribute('p:value') === value, 'qualified lookup preserves UTF-16');
element.setAttributeNS(null, 'data-value', value);
check(element.getAttribute('data-value') === value, 'null namespace write preserves UTF-16');
element.setAttributeNS('', 'data-empty', value);
check(element.getAttributeNS(null, 'data-empty') === value, 'empty namespace normalizes to null');
}
element.setAttributeNS('urn:first', 'p:shared', '\uD800');
element.setAttributeNS('urn:second', 'p:shared', '\uDC00');
check(element.getAttributeNS('urn:first', 'shared') === '\uD800' &&
element.getAttributeNS('urn:second', 'shared') === '\uDC00', 'same qualified name has independent namespace values');
element.setAttribute('p:shared', 'first\uD800');
check(element.getAttributeNS('urn:first', 'shared') === 'first\uD800' &&
element.getAttributeNS('urn:second', 'shared') === '\uDC00', 'qualified write changes only first matching attribute');
for (const [operation, copy] of [['cloneNode', element.cloneNode()], ['importNode', document.importNode(element)]]) {
check(copy.getAttributeNS('urn:first', 'shared') === 'first\uD800' &&
copy.getAttributeNS('urn:second', 'shared') === '\uDC00', operation + ' preserves independent code units in document ' + documents.indexOf(doc) + ' / ' + ns);
}
element.setAttributeNS('urn:second', 'q:shared', '\uFFFD');
check(element.getAttributeNS('urn:first', 'shared') === 'first\uD800', 'UTF-8 replacement clears only matching namespace units');
element.removeAttributeNS('urn:second', 'shared');
check(element.getAttributeNS('urn:first', 'shared') === 'first\uD800', 'namespace removal preserves other code units');
element.setAttributeNS('urn:second', 'p:shared', '\uDC00');
element.removeAttribute('p:shared');
check(element.getAttributeNS('urn:first', 'shared') === null && element.getAttribute('p:shared') === '\uDC00', 'qualified removal reveals second namespace value');
const sentinel = {};
try {element.setAttributeNS('urn:second', 'p:shared', {toString() {throw sentinel;}}); throw Error('missing exception');}
catch (error) {check(error === sentinel && element.getAttributeNS('urn:second', 'shared') === '\uDC00', 'conversion failure is atomic');}
element.setAttributeNS('urn:second', 'p:shared', 'ordinary');
check(element.getAttributeNS('urn:second', 'shared') === 'ordinary', 'ordinary write clears stale units');
}
for (const tag of ['use', 'feImage', 'mpath']) {
const element = doc.createElementNS(svg, tag), href = element.href;
for (const value of values) {
href.baseVal = value;
check(href.baseVal === value && href.animVal === value && element.getAttribute('href') === value, tag + ' href setter preserves UTF-16');
}
element.removeAttribute('href');
element.setAttributeNS(xlink, 'ref:href', '#initial');
href.baseVal = '#\uD800';
check(!element.hasAttribute('href') && element.getAttributeNS(xlink, 'href') === '#\uD800', tag + ' update existing xlink attribute');
element.setAttribute('href', '');
href.baseVal = '#\uDC00';
check(element.getAttribute('href') === '#\uDC00' && element.getAttributeNS(xlink, 'href') === '#\uD800', tag + ' independent href and xlink');
element.removeAttribute('href');
check(href.animVal === '#\uD800', tag + ' fallback preserves code units');
href.baseVal = {toString() {element.setAttribute('href', '#created-during-conversion'); return '#\uDC00';}};
check(element.getAttribute('href') === '#\uDC00' && element.getAttributeNS(xlink, 'href') === '#\uD800', tag + ' reevaluate namespace after conversion');
}
}
const element = document.createElementNS(svg, 'g'); document.body.append(element);
element.setAttributeNS('urn:adopt', 'p:adopt', {toString() {frame.contentDocument.adoptNode(element); return '\uD800';}});
check(element.ownerDocument === frame.contentDocument && element.getAttributeNS('urn:adopt', 'adopt') === '\uD800', 'value conversion may adopt receiver');
element.setAttributeNS({toString() {document.adoptNode(element); return 'urn:adopt';}}, 'p:adopt', '\uDC00');
check(element.ownerDocument === document && element.getAttributeNS('urn:adopt', 'adopt') === '\uDC00', 'namespace conversion may adopt receiver');
const setter = Element.prototype.setAttributeNS;
let conversions = 0;
try {setter.call(new Proxy(element, {}), null, 'data-value', {toString() {conversions++; return 'bad';}}); throw Error('missing brand exception');}
catch (error) {check(error instanceof TypeError && conversions === 0, 'receiver check precedes conversion');}
frame.remove();
return true;
})()