Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(v8): fix custom elements reaction pipeline

SpringCorel8b9c53d467f9
diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/custom_elements_registry.rs b/moli-renderer-v8/src/context_bootstrap/constructors/custom_elements_registry.rs
index c07f9462e..cabbb6088 100644
--- a/moli-renderer-v8/src/context_bootstrap/constructors/custom_elements_registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/constructors/custom_elements_registry.rs
@@ -300,22 +300,26 @@ pub(in crate::context_bootstrap) fn custom_elements_upgrade_callback<'s>(
parsed.root,
) {
let registry_key = custom_elements::registry_store_key(scope, args.this());
- let _ = custom_elements::upgrade_subtree_if_defined_for_registry(
- scope,
- host_ptr,
- root_handle,
- registry_key,
- );
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ let _ = custom_elements::upgrade_subtree_if_defined_for_registry(
+ scope,
+ host_ptr,
+ root_handle,
+ registry_key,
+ );
+ });
return;
}
if let Ok((host_ptr, root_handle)) = node_runtime_and_handle_from_object(scope, parsed.root) {
let registry_key = custom_elements::registry_store_key(scope, args.this());
- let _ = custom_elements::upgrade_subtree_if_defined_for_registry(
- scope,
- host_ptr,
- root_handle,
- registry_key,
- );
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ let _ = custom_elements::upgrade_subtree_if_defined_for_registry(
+ scope,
+ host_ptr,
+ root_handle,
+ registry_key,
+ );
+ });
return;
}
throw_type_error(scope, "customElements.upgrade(root) requires a Node root");
@@ -382,12 +386,14 @@ pub(in crate::context_bootstrap) fn custom_elements_initialize_callback<'s>(
scope.throw_exception(exception);
return;
}
- let _ = custom_elements::initialize_registry_for_subtree(
- scope,
- host_ptr,
- root_handle,
- registry_key,
- );
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ let _ = custom_elements::initialize_registry_for_subtree(
+ scope,
+ host_ptr,
+ root_handle,
+ registry_key,
+ );
+ });
}
fn invalid_custom_element_name_promise<'s>(
diff --git a/moli-renderer-v8/src/custom_elements.rs b/moli-renderer-v8/src/custom_elements.rs
index 8dc9627dd..6fc1ebaf3 100644
--- a/moli-renderer-v8/src/custom_elements.rs
+++ b/moli-renderer-v8/src/custom_elements.rs
@@ -1,7 +1,6 @@
mod adopted_lifecycle;
mod attribute_lifecycle;
mod connected_lifecycle;
-mod connected_lifecycle_initial_attributes;
mod connected_subtree_lifecycle;
mod construction;
mod construction_failure;
@@ -27,7 +26,8 @@ pub(crate) use construction_failure::throw_already_constructed_custom_element_er
use construction_failure::{ConstructionFailure, report_custom_element_construction_failure};
pub(crate) use construction_result::set_wrapper_custom_element_constructor_prototype;
use construction_result::{
- FailedExistingConstructionPrototype, validate_custom_element_construction_result,
+ FailedExistingConstructionPrototype, synchronize_wrapper_custom_element_prototype,
+ validate_custom_element_construction_result,
};
use construction_runtime::construct_custom_element_directly;
use definition::PendingInitialAttribute;
diff --git a/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs b/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs
index 838bcd1a9..4987e591b 100644
--- a/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs
+++ b/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs
@@ -1,4 +1,3 @@
-use super::connected_lifecycle_initial_attributes::enqueue_pending_initial_attribute_callbacks;
use super::reactions::{enqueue_custom_element_reaction, with_custom_element_reaction_scope};
use super::{CustomElementReaction, has_pending_upgrade_reaction};
@@ -38,17 +37,13 @@ pub(crate) fn enqueue_connected_callback(
if has_pending_upgrade_reaction(host_ptr, handle) {
return false;
}
- let mut enqueued = enqueue_pending_initial_attribute_callbacks(scope, host_ptr, handle);
- if enqueue_lifecycle_callback(
+ enqueue_lifecycle_callback(
scope,
host_ptr,
handle,
"connectedCallback",
CustomElementReaction::Connected,
- ) {
- enqueued = true;
- }
- enqueued
+ )
}
pub(crate) fn enqueue_disconnected_callback(
diff --git a/moli-renderer-v8/src/custom_elements/connected_lifecycle_initial_attributes.rs b/moli-renderer-v8/src/custom_elements/connected_lifecycle_initial_attributes.rs
deleted file mode 100644
index c614ba79c..000000000
--- a/moli-renderer-v8/src/custom_elements/connected_lifecycle_initial_attributes.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-use super::super::{document_runtime::DomHandle, native_bridge::JsContextHost};
-use super::PendingInitialAttribute;
-use super::attribute_lifecycle::enqueue_attribute_changed_callback;
-
-pub(super) fn enqueue_pending_initial_attribute_callbacks(
- scope: &mut v8::PinScope<'_, '_>,
- host_ptr: *mut JsContextHost,
- handle: DomHandle,
-) -> bool {
- let pending_attributes = unsafe { &mut *host_ptr }
- .custom_elements_mut_for_node_handle(handle)
- .take_pending_initial_attributes(handle);
- let mut enqueued = false;
- for PendingInitialAttribute {
- name,
- namespace,
- value,
- } in pending_attributes
- {
- if enqueue_attribute_changed_callback(
- scope,
- host_ptr,
- handle,
- &name,
- namespace.as_deref(),
- None,
- Some(&value),
- ) {
- enqueued = true;
- }
- }
- enqueued
-}
diff --git a/moli-renderer-v8/src/custom_elements/construction_result.rs b/moli-renderer-v8/src/custom_elements/construction_result.rs
index 7e45c02ce..8223876da 100644
--- a/moli-renderer-v8/src/custom_elements/construction_result.rs
+++ b/moli-renderer-v8/src/custom_elements/construction_result.rs
@@ -113,6 +113,64 @@ pub(crate) fn set_wrapper_custom_element_constructor_prototype<'s>(
}
}
+pub(super) fn synchronize_wrapper_custom_element_prototype<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+) {
+ synchronize_custom_element_prototype_between_wrappers(scope, wrapper, wrapper);
+}
+
+pub(super) fn synchronize_custom_element_prototype_between_wrappers<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+ target: v8::Local<'s, v8::Object>,
+) {
+ let Some(prototype) = source
+ .get_prototype(scope)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ else {
+ return;
+ };
+ set_wrapper_custom_element_prototype(scope, target, prototype);
+ if let Some(foreign) = get_private_object(scope, target, DOM_PARSER_FOREIGN_NODE_SLOT) {
+ set_wrapper_custom_element_prototype(scope, foreign, prototype);
+ }
+}
+
+pub(super) fn finalize_wrapper_custom_element_prototype<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+ constructor: v8::Local<'s, v8::Function>,
+) {
+ let current = wrapper.get_prototype(scope);
+ let definition_prototype = custom_element_constructor_prototype(scope, constructor).ok();
+ let definition_parent =
+ definition_prototype.and_then(|prototype| prototype.get_prototype(scope));
+ let uses_definition_chain = current.is_some_and(|current| {
+ definition_prototype.is_some_and(|prototype| current.strict_equals(prototype.into()))
+ || definition_parent.is_some_and(|parent| current.strict_equals(parent))
+ });
+ let prototype_constructor_name = current
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .and_then(|prototype| prototype.get(scope, crate::util::v8str(scope, "constructor").into()))
+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
+ .map(|function| function.get_name(scope).to_rust_string_lossy(scope));
+ let constructor_name = constructor.get_name(scope).to_rust_string_lossy(scope);
+ let uses_native_fallback = prototype_constructor_name.as_deref().is_none_or(|name| {
+ name.is_empty()
+ || name == "undefined"
+ || name == "Object"
+ || (name.starts_with("HTML") && name.ends_with("Element"))
+ });
+ let uses_definition_prototype =
+ prototype_constructor_name.as_deref() == Some(constructor_name.as_str());
+ if uses_definition_chain || uses_definition_prototype || uses_native_fallback {
+ set_wrapper_custom_element_constructor_prototype(scope, wrapper, constructor);
+ } else {
+ synchronize_wrapper_custom_element_prototype(scope, wrapper);
+ }
+}
+
fn set_wrapper_custom_element_prototype<'s>(
scope: &mut v8::PinScope<'s, '_>,
wrapper: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/custom_elements/construction_runtime.rs b/moli-renderer-v8/src/custom_elements/construction_runtime.rs
index 545a23b0c..febfbe446 100644
--- a/moli-renderer-v8/src/custom_elements/construction_runtime.rs
+++ b/moli-renderer-v8/src/custom_elements/construction_runtime.rs
@@ -4,7 +4,9 @@ use super::construction_invocation::{
CustomElementConstructorInvocation, invoke_custom_element_constructor,
};
use super::construction_result::{
- set_wrapper_custom_element_constructor_prototype, validate_custom_element_construction_result,
+ finalize_wrapper_custom_element_prototype,
+ synchronize_custom_element_prototype_between_wrappers,
+ validate_custom_element_construction_result,
};
use super::element_state::{
create_element_with_owner_document, set_dom_custom_element_is_name,
@@ -15,7 +17,6 @@ use super::{
dispatch_form_association_callback_if_needed, dispatch_form_disabled_callback_if_needed,
};
use crate::dom::native::CustomElementState;
-use crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections;
use super::super::{document_runtime::DomHandle, native_bridge::JsContextHost};
@@ -79,14 +80,42 @@ pub(super) fn create_custom_element_for_registry_key<'s>(
if let Some(prefix) = post_construction_prefix {
set_dom_element_prefix(host_ptr, handle, Some(prefix.to_owned()));
}
+ finalize_wrapper_custom_element_prototype(scope, created, constructor);
+ if let Some(canonical) = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)
+ {
+ if canonical.strict_equals(created.into()) {
+ synchronize_custom_element_prototype_between_wrappers(
+ scope, created, canonical,
+ );
+ } else {
+ super::construction_result::set_wrapper_custom_element_constructor_prototype(
+ scope,
+ canonical,
+ constructor,
+ );
+ }
+ }
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.mark_upgraded_handle(handle, definition_name);
- set_wrapper_custom_element_constructor_prototype(scope, created, constructor);
set_dom_custom_element_state(host_ptr, handle, CustomElementState::Custom);
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.finish_construction(handle);
+ finalize_wrapper_custom_element_prototype(scope, created, constructor);
+ if let Some(canonical) = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)
+ && !canonical.strict_equals(created.into())
+ {
+ super::construction_result::set_wrapper_custom_element_constructor_prototype(
+ scope,
+ canonical,
+ constructor,
+ );
+ }
dispatch_form_association_callback_if_needed(scope, host_ptr, handle);
dispatch_form_disabled_callback_if_needed(scope, host_ptr, handle);
Some(created)
@@ -125,10 +154,6 @@ pub(super) fn construct_custom_element_directly<'s>(
) -> std::result::Result<DomHandle, ConstructionFailure<'s>> {
match invoke_custom_element_constructor(scope, host_ptr, constructor) {
CustomElementConstructorInvocation::Created(created) => {
- // Parser-created construction runs a checkpoint before validation so
- // constructor-scheduled microtasks can still invalidate the result
- // before parser attributes or children are transferred.
- perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
let created = v8::Local::new(scope, &created);
validate_custom_element_construction_result(
scope,
diff --git a/moli-renderer-v8/src/custom_elements/definition.rs b/moli-renderer-v8/src/custom_elements/definition.rs
index 56ba952e2..bb111e827 100644
--- a/moli-renderer-v8/src/custom_elements/definition.rs
+++ b/moli-renderer-v8/src/custom_elements/definition.rs
@@ -44,7 +44,6 @@ pub(crate) struct CustomElementStore {
pub(super) definitions: HashMap<String, CustomElementDefinition>,
pub(super) upgraded_handles: HashSet<DomHandle>,
pub(super) upgraded_definition_names: HashMap<DomHandle, String>,
- pub(super) pending_initial_attributes: HashMap<DomHandle, Vec<PendingInitialAttribute>>,
pub(super) form_association_states: HashMap<DomHandle, Option<DomHandle>>,
pub(super) form_disabled_states: HashMap<DomHandle, bool>,
pub(super) pending_when_defined: HashMap<String, PendingWhenDefined>,
diff --git a/moli-renderer-v8/src/custom_elements/definition_callback_lookup.rs b/moli-renderer-v8/src/custom_elements/definition_callback_lookup.rs
index 1f16940af..aa1415df0 100644
--- a/moli-renderer-v8/src/custom_elements/definition_callback_lookup.rs
+++ b/moli-renderer-v8/src/custom_elements/definition_callback_lookup.rs
@@ -63,4 +63,15 @@ impl CustomElementStore {
let callback = definition.callbacks.form_reset.as_ref()?;
Some(v8::Local::new(scope, callback))
}
+
+ pub(super) fn form_state_restore_callback_for_handle<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ ) -> Option<v8::Local<'s, v8::Function>> {
+ let definition = self.definition_for_handle(host_ptr, handle)?;
+ let callback = definition.callbacks.form_state_restore.as_ref()?;
+ Some(v8::Local::new(scope, callback))
+ }
}
diff --git a/moli-renderer-v8/src/custom_elements/definition_state.rs b/moli-renderer-v8/src/custom_elements/definition_state.rs
index 7ad33f3bd..a32d3b20f 100644
--- a/moli-renderer-v8/src/custom_elements/definition_state.rs
+++ b/moli-renderer-v8/src/custom_elements/definition_state.rs
@@ -1,18 +1,15 @@
use super::super::document_runtime::DomHandle;
use super::PendingCustomElementConstruction;
-use super::definition::{CustomElementStore, PendingInitialAttribute};
+use super::definition::CustomElementStore;
impl CustomElementStore {
/// Returns true when there is nothing for the upgrade / lifecycle pipeline
/// to do for newly inserted subtrees: no constructors are registered, no
- /// elements have been upgraded, and there are no pending initial-attribute
- /// observations. The vast majority of pages never call
+ /// elements have been upgraded. The vast majority of pages never call
/// `customElements.define(...)` at all, in which case every appendChild /
/// insertBefore can skip the recursive subtree scan entirely.
pub(crate) fn is_subtree_lifecycle_quiescent(&self) -> bool {
- self.definitions.is_empty()
- && self.upgraded_handles.is_empty()
- && self.pending_initial_attributes.is_empty()
+ self.definitions.is_empty() && self.upgraded_handles.is_empty()
}
pub(crate) fn begin_construction(
@@ -91,7 +88,6 @@ impl CustomElementStore {
pub(crate) fn owns_custom_element_handle(&self, handle: DomHandle) -> bool {
self.upgraded_handles.contains(&handle)
|| self.upgraded_definition_names.contains_key(&handle)
- || self.pending_initial_attributes.contains_key(&handle)
|| self.form_association_states.contains_key(&handle)
|| self.form_disabled_states.contains_key(&handle)
|| self.construction_stack.owns_handle(handle)
@@ -117,26 +113,6 @@ impl CustomElementStore {
self.form_disabled_states.insert(handle, disabled);
}
- pub(super) fn mark_pending_initial_attributes(
- &mut self,
- handle: DomHandle,
- attributes: Vec<PendingInitialAttribute>,
- ) {
- if attributes.is_empty() {
- return;
- }
- self.pending_initial_attributes.insert(handle, attributes);
- }
-
- pub(super) fn take_pending_initial_attributes(
- &mut self,
- handle: DomHandle,
- ) -> Vec<PendingInitialAttribute> {
- self.pending_initial_attributes
- .remove(&handle)
- .unwrap_or_default()
- }
-
pub(super) fn mark_upgraded_handle(&mut self, handle: DomHandle, definition_name: &str) {
self.construction_stack.clear_failed(handle);
self.upgraded_handles.insert(handle);
diff --git a/moli-renderer-v8/src/custom_elements/definition_upgrade.rs b/moli-renderer-v8/src/custom_elements/definition_upgrade.rs
index a8add73de..c1663200b 100644
--- a/moli-renderer-v8/src/custom_elements/definition_upgrade.rs
+++ b/moli-renderer-v8/src/custom_elements/definition_upgrade.rs
@@ -1,14 +1,11 @@
-use super::connected_lifecycle::dispatch_connected_callback;
use super::element_state::definition_name_for_handle;
-use super::existing_upgrade::upgrade_handle_if_defined;
+use super::reactions::{CustomElementReaction, enqueue_custom_element_reaction};
use super::registry_roots::{
is_shadow_including_rooted_in_browsing_context_document, shadow_including_root_document_handle,
};
use super::traversal::shadow_including_subtree_handles;
+use super::with_custom_element_reaction_scope;
use super::{CustomElementRegistryAssociation, CustomElementRegistryKey};
-use super::{
- dispatch_form_association_callback_if_needed, dispatch_form_disabled_callback_if_needed,
-};
use crate::{document_runtime::DomHandle, native_bridge::JsContextHost};
use std::collections::HashSet;
@@ -31,17 +28,16 @@ pub(crate) fn upgrade_existing_definition_for_child(
};
let mut handles = Vec::new();
collect_matching_definition_handles(host_ptr, document_handle, definition_name, &mut handles);
- for handle in handles {
- let was_connected = unsafe { &*host_ptr }.dom_host().is_connected(handle);
- if !upgrade_handle_if_defined(scope, host_ptr, handle) {
- continue;
+ with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ for handle in handles {
+ enqueue_custom_element_reaction(
+ scope,
+ host_ptr,
+ handle,
+ CustomElementReaction::Upgrade,
+ );
}
- if was_connected {
- dispatch_connected_callback(scope, host_ptr, handle);
- }
- dispatch_form_association_callback_if_needed(scope, host_ptr, handle);
- dispatch_form_disabled_callback_if_needed(scope, host_ptr, handle);
- }
+ });
}
pub(crate) fn upgrade_existing_definition_for_registry(
@@ -55,23 +51,16 @@ pub(crate) fn upgrade_existing_definition_for_registry(
registry_key,
definition_name,
);
- for handle in handles {
- let was_upgraded = unsafe { &*host_ptr }
- .custom_elements_for_node_handle(handle)
- .is_some_and(|store| store.is_upgraded_handle(handle));
- if !upgrade_handle_if_defined(scope, host_ptr, handle) {
- continue;
- }
- if !was_upgraded
- && unsafe { &*host_ptr }
- .custom_elements_for_node_handle(handle)
- .is_some_and(|store| store.is_upgraded_handle(handle))
- {
- dispatch_connected_callback(scope, host_ptr, handle);
- dispatch_form_association_callback_if_needed(scope, host_ptr, handle);
- dispatch_form_disabled_callback_if_needed(scope, host_ptr, handle);
+ with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ for handle in handles {
+ enqueue_custom_element_reaction(
+ scope,
+ host_ptr,
+ handle,
+ CustomElementReaction::Upgrade,
+ );
}
- }
+ });
}
fn matching_definition_handles_for_registry_in_upgrade_order(
diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_completion.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_completion.rs
index 648266273..f0c10e51b 100644
--- a/moli-renderer-v8/src/custom_elements/existing_upgrade_completion.rs
+++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_completion.rs
@@ -1,6 +1,7 @@
-use super::construction_result::set_wrapper_custom_element_constructor_prototype;
+use super::PendingInitialAttribute;
use super::element_state::set_dom_custom_element_state;
-use super::{PendingInitialAttribute, dispatch_attribute_changed_callback};
+use super::reactions::{CustomElementReaction, enqueue_custom_element_reaction};
+use super::registry_roots::is_shadow_including_rooted_in_document;
use crate::{
document_runtime::DomHandle,
dom::native::{CustomElementState, Node},
@@ -8,27 +9,46 @@ use crate::{
};
pub(super) fn complete_existing_custom_element_upgrade<'s>(
- scope: &mut v8::PinScope<'s, '_>,
+ _scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut JsContextHost,
handle: DomHandle,
- wrapper: v8::Local<'s, v8::Object>,
- constructor: v8::Local<'s, v8::Function>,
definition_name: &str,
- initial_attributes: Vec<PendingInitialAttribute>,
) {
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.mark_upgraded_handle(handle, definition_name);
- set_wrapper_custom_element_constructor_prototype(scope, wrapper, constructor);
set_dom_custom_element_state(host_ptr, handle, CustomElementState::Custom);
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.finish_construction(handle);
- if !initial_attributes.is_empty() {
- unsafe { &mut *host_ptr }
- .custom_elements_mut_for_node_handle(handle)
- .mark_pending_initial_attributes(handle, initial_attributes);
- deliver_pending_initial_attribute_callbacks(scope, host_ptr, handle);
+}
+
+pub(super) fn enqueue_existing_upgrade_callbacks(
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ initial_attributes: Vec<PendingInitialAttribute>,
+) {
+ for PendingInitialAttribute {
+ name,
+ namespace,
+ value,
+ } in initial_attributes
+ {
+ enqueue_custom_element_reaction(
+ scope,
+ host_ptr,
+ handle,
+ CustomElementReaction::AttributeChanged {
+ name,
+ namespace,
+ old_value: None,
+ new_value: Some(value),
+ },
+ );
+ }
+ if is_shadow_including_rooted_in_document(unsafe { &*host_ptr }.dom_host(), handle) {
+ enqueue_custom_element_reaction(scope, host_ptr, handle, CustomElementReaction::Connected);
}
}
@@ -66,29 +86,3 @@ pub(super) fn observed_attributes_with_current_values(
})
.collect()
}
-
-fn deliver_pending_initial_attribute_callbacks(
- scope: &mut v8::PinScope<'_, '_>,
- host_ptr: *mut JsContextHost,
- handle: DomHandle,
-) {
- let pending_attributes = unsafe { &mut *host_ptr }
- .custom_elements_mut_for_node_handle(handle)
- .take_pending_initial_attributes(handle);
- for PendingInitialAttribute {
- name,
- namespace,
- value,
- } in pending_attributes
- {
- dispatch_attribute_changed_callback(
- scope,
- host_ptr,
- handle,
- &name,
- namespace.as_deref(),
- None,
- Some(&value),
- );
- }
-}
diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
index 09aac81af..df8769877 100644
--- a/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
+++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
@@ -1,9 +1,7 @@
use super::construction_failure::{
ConstructionFailure, report_custom_element_construction_failure,
};
-use super::construction_result::{
- FailedExistingConstructionPrototype, set_wrapper_custom_element_constructor_prototype,
-};
+use super::construction_result::FailedExistingConstructionPrototype;
use super::element_state::set_dom_custom_element_state;
use crate::dom::native::CustomElementState;
@@ -25,9 +23,6 @@ pub(super) fn fail_existing_custom_element_construction<'s>(
let wrapper = unsafe { &mut *host_ptr }
.native_bridge_mut()
.wrap_handle(scope, host_ptr, handle);
- let consumed_pending_wrapper = unsafe { &*host_ptr }
- .custom_elements_for_node_handle(handle)
- .is_some_and(|store| store.pending_construction_is_already_constructed(handle));
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.discard_pending_construction(handle);
@@ -43,9 +38,6 @@ pub(super) fn fail_existing_custom_element_construction<'s>(
FailedExistingConstructionPrototype::ResetToUnknown => {
set_wrapper_failed_custom_element_prototype(scope, wrapper);
}
- FailedExistingConstructionPrototype::PreserveCurrent if consumed_pending_wrapper => {
- set_wrapper_custom_element_constructor_prototype(scope, wrapper, constructor);
- }
FailedExistingConstructionPrototype::PreserveCurrent => {}
}
}
diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs
index 1bf3af5a4..b95fc6e51 100644
--- a/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs
+++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs
@@ -3,9 +3,13 @@ use super::construction_failure::ConstructionFailure;
use super::construction_invocation::{
CustomElementConstructorInvocation, invoke_custom_element_constructor,
};
-use super::construction_result::FailedExistingConstructionPrototype;
+use super::construction_result::{
+ FailedExistingConstructionPrototype, finalize_wrapper_custom_element_prototype,
+ synchronize_custom_element_prototype_between_wrappers,
+};
use super::existing_upgrade_completion::{
- complete_existing_custom_element_upgrade, observed_attributes_with_current_values,
+ complete_existing_custom_element_upgrade, enqueue_existing_upgrade_callbacks,
+ observed_attributes_with_current_values,
};
use super::existing_upgrade_failure::fail_existing_custom_element_construction;
use super::existing_upgrade_reentry::already_constructed_reentry_consumed_pending_handle;
@@ -22,6 +26,7 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
) -> bool {
let initial_attributes =
observed_attributes_with_current_values(host_ptr, handle, definition_name);
+ enqueue_existing_upgrade_callbacks(scope, host_ptr, handle, initial_attributes);
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.begin_construction(scope, constructor, wrapper, handle);
@@ -40,20 +45,31 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
),
failure_prototype,
);
+ finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
return true;
}
- complete_existing_custom_element_upgrade(
- scope,
- host_ptr,
- handle,
- wrapper,
- constructor,
- definition_name,
- initial_attributes,
- );
+ finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
+ complete_existing_custom_element_upgrade(scope, host_ptr, handle, definition_name);
true
}
CustomElementConstructorInvocation::Exception(exception) => {
+ finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
+ if let Some(canonical) = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)
+ {
+ if canonical.strict_equals(wrapper.into()) {
+ synchronize_custom_element_prototype_between_wrappers(
+ scope, wrapper, canonical,
+ );
+ } else {
+ super::construction_result::set_wrapper_custom_element_constructor_prototype(
+ scope,
+ canonical,
+ constructor,
+ );
+ }
+ }
let exception = v8::Local::new(scope, &exception);
if already_constructed_reentry_consumed_pending_handle(
scope,
@@ -63,15 +79,7 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
constructor,
definition_name,
) {
- complete_existing_custom_element_upgrade(
- scope,
- host_ptr,
- handle,
- wrapper,
- constructor,
- definition_name,
- initial_attributes,
- );
+ complete_existing_custom_element_upgrade(scope, host_ptr, handle, definition_name);
return true;
}
fail_existing_custom_element_construction(
@@ -82,12 +90,16 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
ConstructionFailure::Exception(exception),
failure_prototype,
);
+ finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
true
}
CustomElementConstructorInvocation::Empty => {
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.discard_pending_construction(handle);
+ unsafe { &mut *host_ptr }
+ .custom_element_reactions_mut()
+ .clear_reactions(handle);
false
}
}
diff --git a/moli-renderer-v8/src/custom_elements/form_lifecycle.rs b/moli-renderer-v8/src/custom_elements/form_lifecycle.rs
index 3508698bd..56feb5a72 100644
--- a/moli-renderer-v8/src/custom_elements/form_lifecycle.rs
+++ b/moli-renderer-v8/src/custom_elements/form_lifecycle.rs
@@ -1,5 +1,6 @@
use super::element_state::is_form_associated_custom_element_handle;
use super::existing_upgrade::has_pending_upgrade_reaction;
+use super::reaction_types::FormStateRestoreMode;
use super::reactions::{
CustomElementReaction, enqueue_custom_element_reaction, with_custom_element_reaction_scope,
};
@@ -127,3 +128,23 @@ pub(crate) fn dispatch_form_disabled_callback_if_needed(
enqueue_form_disabled_callback_if_needed(scope, host_ptr, handle);
});
}
+
+// The session-history/autofill owner calls this once restoration is implemented.
+// Keep the reaction path here so callback invocation cannot bypass CE ordering.
+#[allow(dead_code)]
+pub(crate) fn dispatch_form_state_restore_callback(
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ value: String,
+ mode: FormStateRestoreMode,
+) {
+ with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ enqueue_custom_element_reaction(
+ scope,
+ host_ptr,
+ handle,
+ CustomElementReaction::FormStateRestore { value, mode },
+ );
+ });
+}
diff --git a/moli-renderer-v8/src/custom_elements/form_lifecycle_callbacks.rs b/moli-renderer-v8/src/custom_elements/form_lifecycle_callbacks.rs
index 756cbf532..887c32591 100644
--- a/moli-renderer-v8/src/custom_elements/form_lifecycle_callbacks.rs
+++ b/moli-renderer-v8/src/custom_elements/form_lifecycle_callbacks.rs
@@ -104,3 +104,42 @@ pub(super) fn call_form_reset_callback(
&[],
);
}
+
+pub(super) fn call_form_state_restore_callback(
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ value: &str,
+ mode: super::reaction_types::FormStateRestoreMode,
+) {
+ if !unsafe { &*host_ptr }
+ .custom_elements_for_node_handle(handle)
+ .is_some_and(|store| store.is_upgraded_handle(handle))
+ {
+ return;
+ }
+ let Some(wrapper) = custom_element_callback_receiver(scope, host_ptr, handle) else {
+ return;
+ };
+ let Some(callback) = unsafe { &*host_ptr }
+ .custom_elements_for_node_handle(handle)
+ .and_then(|store| store.form_state_restore_callback_for_handle(scope, host_ptr, handle))
+ else {
+ return;
+ };
+ let Some(value) = v8::String::new(scope, value) else {
+ return;
+ };
+ let Some(mode) = v8::String::new(scope, mode.as_str()) else {
+ return;
+ };
+ let _reaction = enter_custom_element_reaction(host_ptr);
+ invoke_custom_element_callback(
+ scope,
+ host_ptr,
+ "custom element formStateRestoreCallback",
+ callback,
+ wrapper.into(),
+ &[value.into(), mode.into()],
+ );
+}
diff --git a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
index 288539fdd..d5b9fc8b3 100644
--- a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
+++ b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
@@ -79,6 +79,12 @@ pub(super) fn construct_parser_created_custom_element_direct(
with_custom_element_reaction_scope(scope, host_ptr, |scope| {
let invocation: CustomElementConstructorInvocation =
invoke_custom_element_constructor(scope, host_ptr, constructor);
+ // The parser invokes the constructor from a stack-empty boundary. Run
+ // the microtasks it queued before validating the constructed element,
+ // matching the HTML parser's custom-element construction algorithm.
+ // In particular, a constructor microtask can add an attribute and make
+ // the subsequent construction-result validation fail.
+ perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
let constructed_handle = handle_parser_direct_constructor_invocation(
scope,
host_ptr,
diff --git a/moli-renderer-v8/src/custom_elements/parser_handoff_direct_result.rs b/moli-renderer-v8/src/custom_elements/parser_handoff_direct_result.rs
index fe346d874..12146cc24 100644
--- a/moli-renderer-v8/src/custom_elements/parser_handoff_direct_result.rs
+++ b/moli-renderer-v8/src/custom_elements/parser_handoff_direct_result.rs
@@ -4,11 +4,10 @@ use super::{
ConstructionFailure, CustomElementRegistryKey, FailedExistingConstructionPrototype,
dispatch_form_association_callback_if_needed, dispatch_form_disabled_callback_if_needed,
fail_existing_custom_element_construction, set_dom_custom_element_state,
- set_wrapper_custom_element_constructor_prototype, validate_custom_element_construction_result,
+ synchronize_wrapper_custom_element_prototype, validate_custom_element_construction_result,
};
use crate::{
document_runtime::DomHandle, dom::native::CustomElementState, native_bridge::JsContextHost,
- script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections,
};
pub(super) struct ParserDirectConstructionContext<'s, 'a> {
@@ -61,10 +60,6 @@ fn handle_parser_direct_created_element<'s>(
created: v8::Global<v8::Object>,
context: ParserDirectConstructionContext<'s, '_>,
) -> DomHandle {
- // Parser-created construction runs a checkpoint before validation so
- // constructor-scheduled microtasks can still invalidate the result before
- // parser attributes or children are transferred.
- perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
let created = v8::Local::new(scope, &created);
match validate_custom_element_construction_result(
scope,
@@ -76,13 +71,12 @@ fn handle_parser_direct_created_element<'s>(
context.initial_owner_document,
) {
Ok(constructed_handle) => {
+ synchronize_wrapper_custom_element_prototype(scope, created);
mark_parser_direct_construction_success(
scope,
host_ptr,
context.original_handle,
constructed_handle,
- created,
- context.constructor,
context.registry_key,
context.definition_name,
);
@@ -111,8 +105,6 @@ fn mark_parser_direct_construction_success<'s>(
host_ptr: *mut JsContextHost,
original_handle: DomHandle,
constructed_handle: DomHandle,
- created: v8::Local<'s, v8::Object>,
- constructor: v8::Local<'s, v8::Function>,
registry_key: CustomElementRegistryKey,
definition_name: &str,
) {
@@ -128,7 +120,6 @@ fn mark_parser_direct_construction_success<'s>(
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.mark_upgraded_handle(constructed_handle, definition_name);
- set_wrapper_custom_element_constructor_prototype(scope, created, constructor);
set_dom_custom_element_state(host_ptr, constructed_handle, CustomElementState::Custom);
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
diff --git a/moli-renderer-v8/src/custom_elements/reaction_dispatcher.rs b/moli-renderer-v8/src/custom_elements/reaction_dispatcher.rs
index 99dd85251..e5276fc7b 100644
--- a/moli-renderer-v8/src/custom_elements/reaction_dispatcher.rs
+++ b/moli-renderer-v8/src/custom_elements/reaction_dispatcher.rs
@@ -3,6 +3,7 @@ use super::adopted_lifecycle::call_adopted_callback;
use super::attribute_lifecycle::call_attribute_changed_callback;
use super::form_lifecycle_callbacks::{
call_form_associated_callback, call_form_disabled_callback, call_form_reset_callback,
+ call_form_state_restore_callback,
};
use super::lifecycle::call_lifecycle_callback;
use super::reaction_upgrade::invoke_upgrade_reaction;
@@ -73,6 +74,9 @@ pub(super) fn invoke_custom_element_reactions_for_handle(
CustomElementReaction::FormReset => {
call_form_reset_callback(scope, host_ptr, handle);
}
+ CustomElementReaction::FormStateRestore { value, mode } => {
+ call_form_state_restore_callback(scope, host_ptr, handle, &value, mode);
+ }
}
}
}
diff --git a/moli-renderer-v8/src/custom_elements/reaction_types.rs b/moli-renderer-v8/src/custom_elements/reaction_types.rs
index de5b8dcd3..9f0693eb5 100644
--- a/moli-renderer-v8/src/custom_elements/reaction_types.rs
+++ b/moli-renderer-v8/src/custom_elements/reaction_types.rs
@@ -28,4 +28,25 @@ pub(super) enum CustomElementReaction {
disabled: bool,
},
FormReset,
+ #[allow(dead_code)]
+ FormStateRestore {
+ value: String,
+ mode: FormStateRestoreMode,
+ },
+}
+
+#[allow(dead_code)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum FormStateRestoreMode {
+ Restore,
+ Autocomplete,
+}
+
+impl FormStateRestoreMode {
+ pub(super) fn as_str(self) -> &'static str {
+ match self {
+ Self::Restore => "restore",
+ Self::Autocomplete => "autocomplete",
+ }
+ }
}
diff --git a/moli-renderer-v8/src/custom_elements/reaction_upgrade.rs b/moli-renderer-v8/src/custom_elements/reaction_upgrade.rs
index cdedb87a6..b32fc0977 100644
--- a/moli-renderer-v8/src/custom_elements/reaction_upgrade.rs
+++ b/moli-renderer-v8/src/custom_elements/reaction_upgrade.rs
@@ -1,4 +1,3 @@
-use super::connected_lifecycle::enqueue_connected_callback;
use super::form_lifecycle::{
enqueue_form_association_callback_if_needed, enqueue_form_disabled_callback_if_needed,
};
@@ -17,8 +16,7 @@ pub(super) fn invoke_upgrade_reaction(
let is_upgraded = unsafe { &*host_ptr }
.custom_elements_for_node_handle(handle)
.is_some_and(|store| store.is_upgraded_handle(handle));
- if !was_upgraded && is_upgraded && unsafe { &*host_ptr }.dom_host().is_connected(handle) {
- enqueue_connected_callback(scope, host_ptr, handle);
+ if !was_upgraded && is_upgraded {
enqueue_form_association_callback_if_needed(scope, host_ptr, handle);
enqueue_form_disabled_callback_if_needed(scope, host_ptr, handle);
}
diff --git a/moli-renderer-v8/src/custom_elements/subtree_upgrade.rs b/moli-renderer-v8/src/custom_elements/subtree_upgrade.rs
index 025c13a04..f47a3db96 100644
--- a/moli-renderer-v8/src/custom_elements/subtree_upgrade.rs
+++ b/moli-renderer-v8/src/custom_elements/subtree_upgrade.rs
@@ -34,16 +34,20 @@ pub(crate) fn upgrade_subtree_if_defined_for_registry(
registry_key: CustomElementRegistryKey,
) -> bool {
let target_association = CustomElementRegistryAssociation::Registry(registry_key);
- let mut stack = vec![root];
- while let Some(handle) = stack.pop() {
- let children = shadow_including_child_handles(host_ptr, handle);
+ let mut handles = Vec::new();
+ collect_shadow_including_subtree_handles(host_ptr, root, &mut handles);
+ for handle in handles {
if unsafe { &*host_ptr }.effective_custom_element_registry_association(handle)
== target_association
- && !upgrade_handle_with_immediate_form_lifecycle_if_defined(scope, host_ptr, handle)
+ && can_upgrade_handle(host_ptr, handle)
{
- return false;
+ enqueue_custom_element_reaction(
+ scope,
+ host_ptr,
+ handle,
+ CustomElementReaction::Upgrade,
+ );
}
- stack.extend(children.into_iter().rev());
}
true
}
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index 2eb62c808..41f31ad8b 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -629,10 +629,17 @@ impl DocumentRuntime {
if custom_element_upgrade_timing
== HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment
{
- for root in fragment_roots {
- if !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, root) {
- return None;
- }
+ let upgraded =
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ for root in fragment_roots {
+ if !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, root) {
+ return false;
+ }
+ }
+ true
+ });
+ if !upgraded {
+ return None;
}
}
unsafe { &mut *host_ptr }.capture_node_creation_stack_traces_since(scope, first_node_index);
diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs
index 0e21f44d7..605425618 100644
--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs
@@ -624,7 +624,11 @@ impl DocumentRuntime {
let registry_retargets =
custom_elements::registry_association_retargets_for_clone(host_ptr, handle, clone);
custom_elements::apply_registry_association_retargets(host_ptr, &registry_retargets);
- if !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, clone) {
+ let upgraded =
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ custom_elements::upgrade_subtree_if_defined(scope, host_ptr, clone)
+ });
+ if !upgraded {
return None;
}
Some(clone)
@@ -648,7 +652,11 @@ impl DocumentRuntime {
fallback_registry,
);
custom_elements::apply_registry_association_retargets(host_ptr, &registry_retargets);
- if !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, clone) {
+ let upgraded =
+ custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
+ custom_elements::upgrade_subtree_if_defined(scope, host_ptr, clone)
+ });
+ if !upgraded {
return None;
}
Some(clone)
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
index 3b38303c2..ffb59c59c 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
@@ -1313,6 +1313,89 @@ fn child_custom_elements_upgrade_accepts_child_document_node_root() {
);
}
+#[test]
+fn existing_upgrade_preserves_prototype_selected_by_wrapping_constructor() {
+ let mut vm = new_storage_test_vm("https://example.com/");
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const html = document.documentElement || document.appendChild(document.createElement("html"));
+ const body = document.body || html.appendChild(document.createElement("body"));
+ const element = document.createElement("wrapped-upgrade-element");
+ body.appendChild(element);
+ const log = [];
+
+ class RealElement extends HTMLElement {
+ polymerMethod() { return "available"; }
+ }
+ class WrappingElement extends HTMLElement {
+ constructor() {
+ super();
+ Object.setPrototypeOf(this, RealElement.prototype);
+ }
+ connectedCallback() {
+ log.push(this.polymerMethod());
+ }
+ }
+
+ customElements.define("wrapped-upgrade-element", WrappingElement);
+ return JSON.stringify({
+ realPrototype: Object.getPrototypeOf(element) === RealElement.prototype,
+ wrapperPrototype: Object.getPrototypeOf(element) === WrappingElement.prototype,
+ realInstance: element instanceof RealElement,
+ method: element.polymerMethod(),
+ log
+ });
+ })()
+ "#,
+ )
+ .expect("wrapping constructor prototype probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"realPrototype":true,"wrapperPrototype":false,"realInstance":true,"method":"available","log":["available"]}"#
+ );
+}
+
+#[test]
+fn synchronous_creation_preserves_prototype_selected_by_constructor() {
+ let mut vm = new_storage_test_vm("https://example.com/");
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ class RealElement extends HTMLElement {
+ polymerMethod() { return "available"; }
+ }
+ class WrappingElement extends HTMLElement {
+ constructor() {
+ super();
+ Object.setPrototypeOf(this, RealElement.prototype);
+ }
+ }
+
+ customElements.define("wrapped-created-element", WrappingElement);
+ const element = document.createElement("wrapped-created-element");
+ return JSON.stringify({
+ realPrototype: Object.getPrototypeOf(element) === RealElement.prototype,
+ wrapperPrototype: Object.getPrototypeOf(element) === WrappingElement.prototype,
+ realInstance: element instanceof RealElement,
+ method: element.polymerMethod()
+ });
+ })()
+ "#,
+ )
+ .expect("synchronous wrapping constructor prototype probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"realPrototype":true,"wrapperPrototype":false,"realInstance":true,"method":"available"}"#
+ );
+}
+
#[test]
fn detached_custom_elements_upgrade_uses_owner_document_registry() {
let mut vm = new_storage_test_vm("https://example.com/");