Skip to content

Truly independent web browser

LibWeb: Resolve implicit anchors for popovers and pseudo-elements

sideshowbarkerb37aee3d4d33
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index 213241808e0..79f0d62f261 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -3213,6 +3213,12 @@ void Element::set_style_node_id(CSS::StyleNodeID style_node_id)
auto old_style_node_id = m_style_node_id;
m_style_node_id = style_node_id;
Layout::Node::dom_node_style_node_changed(*this, old_style_node_id);
+ if (auto* rare_data = element_rare_data()) {
+ if (rare_data->implicit_anchor_element)
+ publish_implicit_anchor_element();
+ for (auto& dependent : rare_data->implicit_anchor_dependents)
+ dependent.publish_implicit_anchor_element();
+ }
if (created_hyperlink()) {
if (old_style_node_id != 0)
document().hover_link_reporter().set_link(old_style_node_id.value(), {});
@@ -3243,6 +3249,37 @@ void Element::set_style_node_id(CSS::StyleNodeID style_node_id)
// still hold: the render side styles the element as it arrives, and swaps in what it computed.
}
+GC::Ptr<Element> Element::implicit_anchor_element() const
+{
+ auto* rare_data = element_rare_data();
+ return rare_data ? rare_data->implicit_anchor_element.ptr() : nullptr;
+}
+
+void Element::set_implicit_anchor_element(GC::Ptr<Element> anchor)
+{
+ auto previous = implicit_anchor_element();
+ if (previous == anchor)
+ return;
+ if (previous)
+ previous->ensure_element_rare_data().implicit_anchor_dependents.remove(*this);
+ ensure_element_rare_data().implicit_anchor_element = anchor;
+ if (anchor) {
+ anchor->ensure_element_rare_data().implicit_anchor_dependents.set(*this);
+ anchor->set_needs_layout_update(SetNeedsLayoutReason::ImplicitAnchorChange);
+ }
+ publish_implicit_anchor_element();
+ document().set_needs_layout_update(SetNeedsLayoutReason::ImplicitAnchorChange);
+}
+
+void Element::publish_implicit_anchor_element()
+{
+ if (style_node_id() == 0)
+ return;
+ auto anchor = implicit_anchor_element();
+ auto anchor_id = anchor && &anchor->document() == &document() ? anchor->style_node_id().value() : 0;
+ Layout::RustFFI::render_state_set_implicit_anchor_element(document().layout_node_arena().host(), style_node_id().value(), anchor_id);
+}
+
// The top layer is one of the few element facts the tree build reads that moves during the element's lifetime, so the
// style mirror is told here rather than where the element arrives.
void Element::set_rendered_in_top_layer(bool rendered_in_top_layer)
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index d0c87b566b0..9307acca852 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -362,6 +362,9 @@ public:
// elements keep 0, which is what makes them free.
[[nodiscard]] CSS::StyleNodeID style_node_id() const { return m_style_node_id; }
void set_style_node_id(CSS::StyleNodeID);
+
+ GC::Ptr<Element> implicit_anchor_element() const;
+ void set_implicit_anchor_element(GC::Ptr<Element>);
// Tells the hover of the render clock what link this element is, as its href or style node changed.
void update_hover_link();
void record_style_environment_change();
@@ -978,6 +981,7 @@ protected:
struct RareData;
private:
+ void publish_implicit_anchor_element();
void bump_dom_tree_version_for_attribute_change();
void clear_custom_highlight_styles();
// The attributes of an element, in order, in the same allocation as their count and capacity.
diff --git a/Libraries/LibWeb/DOM/ElementRareData.h b/Libraries/LibWeb/DOM/ElementRareData.h
index 38dfce094d4..778827c274d 100644
--- a/Libraries/LibWeb/DOM/ElementRareData.h
+++ b/Libraries/LibWeb/DOM/ElementRareData.h
@@ -6,6 +6,7 @@
#pragma once
+#include <LibGC/WeakHashSet.h>
#include <LibWeb/CSS/CustomPropertyData.h>
#include <LibWeb/CSS/ParkedRandomBaseValues.h>
#include <LibWeb/CSS/StylePropertyMap.h>
@@ -36,6 +37,10 @@ struct Element::RareData
Optional<CSS::PseudoElement> associated_shadow_host_pseudo_element;
Vector<Utf16FlyString> parts;
+ // https://drafts.csswg.org/css-anchor-position-1/#implicit-anchor-element
+ GC::Weak<Element> implicit_anchor_element;
+ GC::WeakHashSet<Element> implicit_anchor_dependents;
+
// https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-reaction-queue
// All elements have an associated custom element reaction queue, initially empty. Each item in the custom element reaction queue is of one of two types:
// NOTE: See the structs at the top of Element.h.
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index 14ff0f72c8d..6b1ade2149a 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -90,6 +90,7 @@ enum class RootNodeComposed {
X(HTMLObjectElementContentDocumentResized) \
X(HTMLVideoElementNaturalDimensionsChanged) \
X(HTMLVideoElementSetVideoTrack) \
+ X(ImplicitAnchorChange) \
X(KeyframeEffect) \
X(LayoutTreeUpdate) \
X(MathMLAttributeChange) \
diff --git a/Libraries/LibWeb/HTML/HTMLElement.cpp b/Libraries/LibWeb/HTML/HTMLElement.cpp
index faaf847fbbd..97da5573fc0 100644
--- a/Libraries/LibWeb/HTML/HTMLElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLElement.cpp
@@ -2004,7 +2004,8 @@ WebIDL::ExceptionOr<void> HTMLElement::show_popover(ThrowExceptions throw_except
set_popover_visibility_state(PopoverVisibilityState::Showing);
// 23. Set element's popover trigger to source.
rare_data.popover_trigger = source;
- // FIXME: 24. Set element's implicit anchor element to source.
+ // 24. Set element's implicit anchor element to source.
+ set_implicit_anchor_element(source);
// 25. Run the popover focusing steps given element.
run_popover_focusing_steps(*this);
// 26. If shouldRestoreFocus is true and element's popover attribute is not in the No Popover state, then set element's previously focused element to originallyFocusedElement.
@@ -2101,10 +2102,14 @@ WebIDL::ExceptionOr<void> HTMLElement::hide_popover(FocusPreviousElement focus_p
}
// 9.4. Request an element to be removed from the top layer given element.
document.request_an_element_to_be_remove_from_the_top_layer(*this);
+
+ // 9.5. Set element's implicit anchor element to null.
+ set_implicit_anchor_element(nullptr);
}
// 10. Otherwise, remove an element from the top layer immediately given element.
else {
document.remove_an_element_from_the_top_layer_immediately(*this);
+ set_implicit_anchor_element(nullptr);
}
// AD-HOC: The following block of code is all ad-hoc.
diff --git a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
index faabc135ef9..27de2680842 100644
--- a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
+++ b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
@@ -412,6 +412,23 @@ struct AnchorCalcCallbackContext<'pass> {
}
impl AbsposEngine<'_> {
+ // https://drafts.csswg.org/css-anchor-position-1/#default-anchor
+ fn default_anchor(&self, positioned_box: Node) -> Option<Node> {
+ let style = self.style(positioned_box);
+ match style.anchor().position_anchor_type {
+ 3 => self.anchor_lookup(positioned_box, style.position_anchor_name()),
+ 0 if style.anchor().position_area.as_slice().is_empty() => None,
+ 0 | 2 => {
+ let arena = self.pass.arena();
+ let anchor = arena.bound_row(arena.implicit_anchor_element(positioned_box)?);
+ let containing_block = arena.node_containing_block_if_live(positioned_box)?;
+ self.anchor_is_acceptable(anchor, positioned_box, containing_block)
+ .then_some(anchor)
+ }
+ _ => None,
+ }
+ }
+
/// The box `anchor_name` names for `positioned_box`.
///
/// https://drafts.csswg.org/css-shadow-1/#tree-scoped-name
@@ -785,12 +802,7 @@ impl AbsposEngine<'_> {
return (None, AnchorResolutionState::NO_SCROLL_SHIFT);
}
let containing_block_geometry = *entry_containing_block_geometry;
- let default_anchor_box = if style.has_position_anchor() {
- self.anchor_lookup(node, style.position_anchor_name())
- .unwrap_or(NodeSlotId::INVALID)
- } else {
- NodeSlotId::INVALID
- };
+ let default_anchor_box = self.default_anchor(node).unwrap_or(NodeSlotId::INVALID);
let mut resolution_state = AnchorResolutionState {
default_anchor_box,
compensates_for_horizontal_scroll: false,
@@ -986,13 +998,10 @@ impl AbsposEngine<'_> {
&& insets_are_both_auto_or_both_not(style.inset_left(), style.inset_right());
let centers_block = style.align_self() == align_self::ANCHOR_CENTER
&& insets_are_both_auto_or_both_not(style.inset_top(), style.inset_bottom());
- if (!centers_inline && !centers_block)
- || !style.has_position_anchor()
- || !self.facts(positioned_box).is_absolutely_positioned()
- {
+ if (!centers_inline && !centers_block) || !self.facts(positioned_box).is_absolutely_positioned() {
return;
}
- let Some(anchor_box) = self.anchor_lookup(positioned_box, style.position_anchor_name()) else {
+ let Some(anchor_box) = self.default_anchor(positioned_box) else {
return;
};
let anchor_rect = self.anchor_rect(anchor_box, containing_block_geometry, entry_coordinate_space_box);
@@ -1076,7 +1085,7 @@ impl AbsposEngine<'_> {
// https://drafts.csswg.org/css-anchor-position-1/#position-area
// If the box does not have a default anchor box, or is not an absolutely positioned box, this value has no
// effect.
- if !style.has_position_anchor() || !self.facts(positioned_box).is_absolutely_positioned() {
+ if !self.facts(positioned_box).is_absolutely_positioned() {
return None;
}
let containing_block_style = self.style(containing_block);
@@ -1093,7 +1102,7 @@ impl AbsposEngine<'_> {
)?
.in_frame(self.pass.frame);
- let anchor_box = self.anchor_lookup(positioned_box, style.position_anchor_name())?;
+ let anchor_box = self.default_anchor(positioned_box)?;
let anchor_rect = self.anchor_rect(anchor_box, containing_block_geometry, entry_coordinate_space_box);
// anchor_rect() is padding-box-relative, while containing_block_info.rect is content-box-relative. Normalize
@@ -1495,18 +1504,14 @@ unsafe extern "C" fn resolve_anchor_non_math_function(context: *mut c_void, shel
return std::ptr::null();
};
- let style = engine.style(context.positioned_box);
let bound_anchor_name = has_anchor_name.then(|| explicit_anchor_name.to_fly_string());
- let anchor_name = if let Some(name) = &bound_anchor_name {
- Some(name.raw())
- } else if style.has_position_anchor() {
- Some(style.position_anchor_name())
+ let anchor_box = if let Some(name) = &bound_anchor_name {
+ engine.anchor_lookup(context.positioned_box, name.raw())
} else {
- None
+ engine.default_anchor(context.positioned_box)
};
if engine.facts(context.positioned_box).is_absolutely_positioned()
- && let Some(anchor_name) = anchor_name
- && let Some(anchor_box) = engine.anchor_lookup(context.positioned_box, anchor_name)
+ && let Some(anchor_box) = anchor_box
{
let rect = engine.anchor_rect(
anchor_box,
diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
index ffddf4e3a86..5fdab561e8b 100644
--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
@@ -561,7 +561,7 @@ pub(crate) fn place_child(
offset_from_relatively_positioned_inline_ancestors,
),
);
- let own_anchor_candidate_border_box_rect = (node_facts.is_box() && node_facts.has_anchor_names()).then(|| {
+ let own_anchor_candidate_border_box_rect = (node_facts.is_box() && node_facts.is_anchor_candidate()).then(|| {
let metrics = &geometry.cells;
let collapsed = metrics.uses_collapsing_borders_model();
CssPixelRect {
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
index 2e8ddc59b56..6e075b0d057 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
@@ -2890,7 +2890,7 @@ impl<'context> InlineFormattingContext<'context> {
let mut candidates = Vec::<(Node, CssPixelRect)>::new();
let mut indices = HashMap::<Node, usize>::default();
for piece in &self.line_data().inline_box_pieces {
- if !self.facts(piece.node).has_anchor_names() {
+ if !self.facts(piece.node).is_anchor_candidate() {
continue;
}
let rect = CssPixelRect::from(piece.border_box_rect).translated_by(piece.relpos_delta.into());
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs b/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
index c416164c59d..756abbdec84 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
@@ -66,6 +66,10 @@ pub(crate) enum LayoutChange {
anchor_name: usize,
elements: Box<[StyleNodeID]>,
},
+ SetImplicitAnchorElement {
+ element: StyleNodeID,
+ anchor: Option<StyleNodeID>,
+ },
/// What the element has scrolled to.
SetElementScrollOffset {
element: StyleNodeID,
@@ -189,6 +193,7 @@ impl LayoutChange {
| Self::ApplyLayoutTreeUpdateMark { .. }
| Self::RecordPartialRelayoutEscape
| Self::SetAnchorNameElements { .. }
+ | Self::SetImplicitAnchorElement { .. }
| Self::SetElementScrollOffset { .. }
| Self::SetWritingSuggestion(_)
| Self::SetPseudoElementScrollOffset { .. }
@@ -279,6 +284,7 @@ impl LayoutChange {
anchor_name,
elements,
} => arena.set_anchor_name_elements(scope_host, anchor_name, elements.iter().copied()),
+ Self::SetImplicitAnchorElement { element, anchor } => arena.set_implicit_anchor_element(element, anchor),
Self::SetElementScrollOffset { element, offset } => arena.set_element_scroll_offset(element, offset),
Self::SetWritingSuggestion(suggestion) => arena.set_writing_suggestion(suggestion),
Self::SetPseudoElementScrollOffset {
@@ -590,6 +596,19 @@ pub extern "C" fn render_state_set_anchor_name_elements(
queue(host, change);
}
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_set_implicit_anchor_element(host: &DocumentHost, element: u32, anchor: u32) {
+ if let Some(element) = StyleNodeID::from_raw(element) {
+ queue(
+ host,
+ LayoutChange::SetImplicitAnchorElement {
+ element,
+ anchor: StyleNodeID::from_raw(anchor),
+ },
+ );
+ }
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn render_state_set_element_scroll_offset(host: &DocumentHost, element: u32, offset: FfiCssPixelPoint) {
let Some(element) = StyleNodeID::from_raw(element) else {
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index 6542b51bb31..c271ac92890 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -971,6 +971,9 @@ struct StyleNodeTables {
/// The elements carrying each anchor name, in tree order. The DOM's registry republishes a
/// name's list whenever it changes.
anchor_name_elements: CowMap<ScopedAnchorName, Vec<StyleNodeID>>,
+ implicit_anchor_elements: CowMap<StyleNodeID, StyleNodeID>,
+ /// Elements that have served as implicit anchors retain their geometry until their identity is retired.
+ implicit_anchor_candidates: CowSet<StyleNodeID>,
/// The nodes sitting in the user agent shadow tree of the focused text control, which is what
/// a caret is painted inside. At most one control is focused, so this holds one control's
/// shadow tree and is empty the rest of the time.
@@ -2048,6 +2051,40 @@ impl LayoutNodeArena {
}
}
+ pub(crate) fn set_implicit_anchor_element(&mut self, element: StyleNodeID, anchor: Option<StyleNodeID>) {
+ if let Some(anchor) = anchor {
+ self.style_node_tables.implicit_anchor_elements.insert(element, anchor);
+ self.style_node_tables.implicit_anchor_candidates.insert(anchor);
+ } else {
+ self.style_node_tables.implicit_anchor_elements.remove(&element);
+ }
+ }
+
+ pub(crate) fn implicit_anchor_element(&self, node: NodeSlotId) -> Option<StyleNodeID> {
+ if self.node_is_generated_for_pseudo_element(node) {
+ return self.node_style_node(node);
+ }
+ let element = self.dom_node_style_node(node)?;
+ self.style_node_tables.implicit_anchor_elements.get(&element).copied()
+ }
+
+ pub(crate) fn node_is_anchor_candidate(&self, node: NodeSlotId) -> bool {
+ super::node_facts::has_flag(self.data(node), NodeFlag::HasAnchorNames)
+ || self.dom_node_style_node(node).is_some_and(|element| {
+ self.style_node_tables.implicit_anchor_candidates.contains(&element)
+ || self.bound_rows.pseudo_elements.get(&element).is_some_and(|rows| {
+ rows.0.iter().any(|&row| {
+ self.node_style_if_live(row).is_some_and(|style| {
+ style.is_absolutely_positioned()
+ && (style.anchor().position_anchor_type == 2
+ || (style.anchor().position_anchor_type == 0
+ && !style.anchor().position_area.as_slice().is_empty()))
+ })
+ })
+ })
+ })
+ }
+
/// Replaces the elements registered under `anchor_name` in the tree scope hosted by
/// `scope_host`, in tree order. An empty list forgets the name.
pub(crate) fn set_anchor_name_elements(
@@ -2261,6 +2298,8 @@ impl LayoutNodeArena {
math_attribute_facts,
svg_points,
anchor_name_elements,
+ implicit_anchor_elements,
+ implicit_anchor_candidates,
identities_in_focused_text_control,
element_scroll_offsets,
pseudo_element_scroll_offsets,
@@ -2271,6 +2310,8 @@ impl LayoutNodeArena {
let removed_svg_attribute_facts = svg_attribute_facts.remove(&style_node);
svg_points.remove(&style_node);
math_attribute_facts.remove(&style_node);
+ implicit_anchor_elements.retain(|element, anchor| *element != style_node && *anchor != style_node);
+ let removed_implicit_anchor = implicit_anchor_candidates.remove(&style_node);
identities_in_focused_text_control.remove(&style_node);
element_scroll_offsets.remove(&style_node);
pseudo_element_scroll_offsets.remove(&style_node);
@@ -2283,6 +2324,9 @@ impl LayoutNodeArena {
// A retired shadow host takes its tree scope with it. The registry withdraws no names from a
// scope it can no longer name.
anchor_name_elements.retain(|name, _| name.scope_host != Some(style_node));
+ if removed_implicit_anchor {
+ self.record_partial_relayout_escape();
+ }
// The SVG facts let go of the reference atoms they hold as they leave.
if let Some(removed) = removed_svg_attribute_facts {
self.retain_published_reference_atoms(
diff --git a/Libraries/LibWeb/Rust/src/layout/node_facts.rs b/Libraries/LibWeb/Rust/src/layout/node_facts.rs
index bbacbc4f545..cbbf0db79af 100644
--- a/Libraries/LibWeb/Rust/src/layout/node_facts.rs
+++ b/Libraries/LibWeb/Rust/src/layout/node_facts.rs
@@ -1193,8 +1193,8 @@ impl<'pass> NodeFacts<'pass> {
has_flag(self.data(), NodeFlag::Anonymous)
}
- pub(crate) fn has_anchor_names(&self) -> bool {
- has_flag(self.data(), NodeFlag::HasAnchorNames)
+ pub(crate) fn is_anchor_candidate(&self) -> bool {
+ self.pass.arena().node_is_anchor_candidate(self.node)
}
pub(crate) fn can_have_children(&self) -> bool {
diff --git a/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs b/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs
index 187ecb3253d..c721b9b4fcd 100644
--- a/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs
+++ b/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs
@@ -311,8 +311,10 @@ impl LayoutNodeArena {
self.for_each_node_in_layout_subtree_in_pre_order_with_pruning(root, |node| {
let data = self.data(node);
affects_anchor_positioning = affects_anchor_positioning
- || node_facts::has_flag(data, NodeFlag::HasAnchorNames)
- || (will_relayout_subtree && node_facts::node_uses_anchor_positioning(data));
+ || self.node_is_anchor_candidate(node)
+ || (will_relayout_subtree
+ && (node_facts::node_uses_anchor_positioning(data)
+ || self.implicit_anchor_element(node).is_some()));
!affects_anchor_positioning
});
affects_anchor_positioning
@@ -574,6 +576,7 @@ impl LayoutNodeArena {
let anchor = style.anchor();
if style.position() != positioning::ABSOLUTE
|| style.has_position_anchor()
+ || self.implicit_anchor_element(node).is_some()
|| anchor.position_area.length != 0
|| anchor.position_try_fallbacks.length != 0
{
diff --git a/Tests/LibWeb/Text/expected/popover-implicit-anchor-lifecycle.txt b/Tests/LibWeb/Text/expected/popover-implicit-anchor-lifecycle.txt
new file mode 100644
index 00000000000..a21be99ce55
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/popover-implicit-anchor-lifecycle.txt
@@ -0,0 +1,20 @@
+popovertarget: 120,120 60x20
+different source: 320,220 60x20
+source moved: 420,220 60x20
+source display none: 0,0 60x20
+source display restored: 420,220 60x20
+source removed: 0,0 60x20
+source reinserted: 420,220 60x20
+position-anchor none: 7,9 60x20
+anchor functions: 400,220 100x20
+normal without position-area: 7,9 60x20
+hidden clears anchor: 7,9 60x20
+shown without source: 7,9 60x20
+shown with first source: 100,120 100x20
+named anchor overrides source: 100,120 100x20
+anchor-center: 420,190 60x20
+inline source across shadow root: true, true
+inline source reconnected: true
+relative implicit anchor: true, true
+pseudo anchor initially disabled: 7px
+pseudo anchor enabled: true, true
diff --git a/Tests/LibWeb/Text/expected/popover-implicit-anchor-source-removal.txt b/Tests/LibWeb/Text/expected/popover-implicit-anchor-source-removal.txt
new file mode 100644
index 00000000000..98df6e08072
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/popover-implicit-anchor-source-removal.txt
@@ -0,0 +1,3 @@
+before removal: 100,70
+after removal: 5,7
+still open: true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.txt
new file mode 100644
index 00000000000..1aad25ae202
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass The implicit anchor element of a pseudo-element is its originating element
+Pass Anchored position after moving
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/popover-implicit-anchor.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/popover-implicit-anchor.txt
new file mode 100644
index 00000000000..4514d72db33
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/popover-implicit-anchor.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Popover invokers form an implicit anchor reference
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/the-button-element/command-and-commandfor/on-popover-behavior.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/the-button-element/command-and-commandfor/on-popover-behavior.txt
index 9a11d3dc583..4fcff7d02ab 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/the-button-element/command-and-commandfor/on-popover-behavior.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/the-button-element/command-and-commandfor/on-popover-behavior.txt
@@ -2,8 +2,7 @@ Harness status: OK
Found 28 tests
-27 Pass
-1 Fail
+28 Pass
Pass changing command attribute inside invokeevent doesn't impact the invocation
Pass invoking (as toggle-popover) closed popover opens
Pass invoking (as toggle-popover) closed popover with preventDefault does not open
@@ -31,4 +30,4 @@ Pass invoking (as hIdE-pOpOvEr) from within open popover closes
Pass invoking (as hIdE-pOpOvEr) from within open popover with preventDefault does not close
Pass invoking (as show-popover) open popover is noop
Pass invoking (as hide-popover) closed popover is noop
-Fail invoking (as show-popover) should create an implicit anchor reference for anchor positioning.
\ No newline at end of file
+Pass invoking (as show-popover) should create an implicit anchor reference for anchor positioning.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/popover-implicit-anchor-lifecycle.html b/Tests/LibWeb/Text/input/popover-implicit-anchor-lifecycle.html
new file mode 100644
index 00000000000..5aa46c4c407
--- /dev/null
+++ b/Tests/LibWeb/Text/input/popover-implicit-anchor-lifecycle.html
@@ -0,0 +1,117 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<style>
+body { margin: 0; }
+#out { position: absolute; }
+#origin { width: 100px; height: 50px; margin-left: 200px; }
+#origin::before { content: ""; position: absolute; width: 20px; height: 20px; position-anchor: none; left: anchor(left, 7px); top: anchor(bottom, 9px); }
+#origin.enabled::before { position-anchor: auto; }
+button { position: absolute; left: 100px; top: 80px; width: 100px; height: 40px; }
+#second { left: 300px; top: 180px; }
+[popover] { position: absolute; inset: auto; margin: 0; border: 0; padding: 0; width: 60px; height: 20px; position-area: bottom; }
+</style>
+<button id="first" popovertarget="popup">First</button>
+<button id="second" popovertarget="popup">Second</button>
+<div id="popup" popover="manual"></div>
+<script>
+test(() => {
+ const first = document.getElementById("first");
+ const second = document.getElementById("second");
+ const popup = document.getElementById("popup");
+ function report(label) {
+ const r = popup.getBoundingClientRect();
+ println(`${label}: ${r.x},${r.y} ${r.width}x${r.height}`);
+ }
+ first.click();
+ report("popovertarget");
+ popup.hidePopover();
+ popup.showPopover({ source: second });
+ report("different source");
+ second.style.left = "400px";
+ report("source moved");
+ second.style.display = "none";
+ report("source display none");
+ second.style.display = "";
+ report("source display restored");
+ second.remove();
+ report("source removed");
+ document.body.append(second);
+ report("source reinserted");
+ popup.style.positionAnchor = "none";
+ popup.style.left = "7px";
+ popup.style.top = "9px";
+ report("position-anchor none");
+ popup.style.positionArea = "none";
+ popup.style.positionAnchor = "auto";
+ popup.style.left = "anchor(left, 7px)";
+ popup.style.top = "anchor(bottom, 9px)";
+ popup.style.width = "anchor-size(width, 60px)";
+ report("anchor functions");
+ popup.style.positionAnchor = "normal";
+ report("normal without position-area");
+ popup.style.positionAnchor = "auto";
+ popup.hidePopover();
+ popup.style.display = "block";
+ report("hidden clears anchor");
+ popup.showPopover();
+ report("shown without source");
+ popup.hidePopover();
+ popup.showPopover({ source: first });
+ report("shown with first source");
+ first.style.anchorName = "--first";
+ popup.style.positionAnchor = "--first";
+ popup.hidePopover();
+ popup.showPopover({ source: second });
+ report("named anchor overrides source");
+ popup.hidePopover();
+ popup.style.positionAnchor = "auto";
+ popup.style.width = "60px";
+ popup.style.left = "auto";
+ popup.style.top = "auto";
+ popup.style.justifySelf = "anchor-center";
+ popup.style.alignSelf = "anchor-center";
+ popup.showPopover({ source: second });
+ report("anchor-center");
+ popup.hidePopover();
+ const host = document.createElement("div");
+ host.style.cssText = "position: absolute; left: 200px; top: 280px;";
+ document.body.append(host);
+ const shadow = host.attachShadow({ mode: "open" });
+ const inline = document.createElement("span");
+ inline.textContent = "Inline anchor";
+ shadow.append(inline);
+ popup.style.positionArea = "bottom";
+ popup.style.alignSelf = "normal";
+ popup.showPopover({ source: inline });
+ let anchorRect = inline.getBoundingClientRect();
+ let popupRect = popup.getBoundingClientRect();
+ println(`inline source across shadow root: ${popupRect.y === anchorRect.bottom}, ${Math.abs(popupRect.x + popupRect.width / 2 - anchorRect.x - anchorRect.width / 2) < 0.1}`);
+ popup.hidePopover();
+ shadow.removeChild(inline);
+ shadow.append(inline);
+ popup.showPopover({ source: inline });
+ anchorRect = inline.getBoundingClientRect();
+ popupRect = popup.getBoundingClientRect();
+ println(`inline source reconnected: ${popupRect.y === anchorRect.bottom && Math.abs(popupRect.x + popupRect.width / 2 - anchorRect.x - anchorRect.width / 2) < 0.1}`);
+ popup.hidePopover();
+ first.style.position = "relative";
+ popup.style.positionArea = "top left";
+ popup.style.justifySelf = "normal";
+ popup.showPopover({ source: first });
+ function reportRelative(label) {
+ const a = first.getBoundingClientRect();
+ const p = popup.getBoundingClientRect();
+ println(`${label}: ${p.right === a.left}, ${p.bottom === a.top}`);
+ }
+ reportRelative("relative implicit anchor");
+ popup.hidePopover();
+ const origin = document.createElement("div");
+ origin.id = "origin";
+ document.body.append(origin);
+ println(`pseudo anchor initially disabled: ${getComputedStyle(origin, "::before").left}`);
+ origin.className = "enabled";
+ const originRect = origin.getBoundingClientRect();
+ const pseudoStyle = getComputedStyle(origin, "::before");
+ println(`pseudo anchor enabled: ${parseFloat(pseudoStyle.left) === originRect.left}, ${parseFloat(pseudoStyle.top) === originRect.bottom}`);
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/popover-implicit-anchor-source-removal.html b/Tests/LibWeb/Text/input/popover-implicit-anchor-source-removal.html
new file mode 100644
index 00000000000..1ed97bdf976
--- /dev/null
+++ b/Tests/LibWeb/Text/input/popover-implicit-anchor-source-removal.html
@@ -0,0 +1,42 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<style>
+ body { margin: 0; }
+ #stage { position: relative; width: 400px; height: 300px; }
+ #boundary { position: absolute; left: 30px; top: 40px; width: 200px; height: 150px; }
+ #source { position: absolute; left: 20px; top: 30px; width: 50px; height: 20px; }
+ #popup {
+ position: absolute;
+ position-anchor: auto;
+ inset: auto;
+ left: anchor(right, 5px);
+ top: anchor(top, 7px);
+ width: 60px;
+ height: 25px;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ }
+</style>
+<div id="stage">
+ <!-- The wrapper keeps the source's parent distinct from its containing block. -->
+ <div id="boundary"><div><div id="source"></div></div></div>
+</div>
+<div id="popup" popover="manual"></div>
+<script>
+ test(() => {
+ const source = document.getElementById("source");
+ const popup = document.getElementById("popup");
+ const position = () => {
+ const rect = popup.getBoundingClientRect();
+ return `${rect.x},${rect.y}`;
+ };
+ popup.showPopover({ source });
+ const before = position();
+ source.remove();
+ const after = position();
+ println(`before removal: ${before}`);
+ println(`after removal: ${after}`);
+ println(`still open: ${popup.matches(":popover-open")}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.html b/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.html
new file mode 100644
index 00000000000..91409e46077
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/anchor-function-pseudo-element-implicit-anchor.html
@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<title>Implicit anchor element for pseudo-elements using anchor functions</title>
+<link rel="help" href="https://drafts.csswg.org/css-anchor-position-1/#implicit">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+body { margin: 0 }
+#target {
+ margin-top: 100px;
+ margin-left: 50px;
+ width: 100px;
+ height: 100px;
+ background: blue;
+}
+#target::before, #target::after {
+ width: 100px;
+ height: 100px;
+ position: absolute;
+ position-anchor: auto;
+}
+#target.moved {
+ margin-top: 200px;
+ margin-left: 200px;
+}
+#target::before {
+ left: anchor(right);
+ top: anchor(top);
+ background: green;
+ content:'';
+}
+#target::after {
+ left: anchor(left);
+ top: anchor(bottom);
+ background: green;
+ content:'';
+}
+</style>
+<div id=target></div>
+<script>
+test(() => {
+ assert_equals(getComputedStyle(target, '::before').top, '100px');
+ assert_equals(getComputedStyle(target, '::before').left, '150px');
+ assert_equals(getComputedStyle(target, '::after').top, '200px');
+ assert_equals(getComputedStyle(target, '::after').left, '50px');
+}, "The implicit anchor element of a pseudo-element is its originating element");
+
+test(() => {
+ target.classList.add("moved");
+ assert_equals(getComputedStyle(target, '::before').top, '200px');
+ assert_equals(getComputedStyle(target, '::before').left, '300px');
+ assert_equals(getComputedStyle(target, '::after').top, '300px');
+ assert_equals(getComputedStyle(target, '::after').left, '200px');
+}, "Anchored position after moving");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/popover-implicit-anchor.html b/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/popover-implicit-anchor.html
new file mode 100644
index 00000000000..24193bd5a34
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-anchor-position/popover-implicit-anchor.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<title>Popover invokers form an implicit anchor reference</title>
+<link rel="author" href="mailto:[email protected]">
+<link rel="help" href="https://www.w3.org/TR/css-anchor-position-1/#implicit">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../resources/testdriver.js"></script>
+<script src="../../resources/testdriver-actions.js"></script>
+<script src="../../resources/testdriver-vendor.js"></script>
+<script src="../../html/semantics/popovers/resources/popover-utils.js"></script>
+
+<button id=button popovertarget=popover>Button</button>
+<div popover id=popover>Popover</div>
+
+<style>
+#button {
+ position:relative;
+ top:100px;
+ left:100px;
+}
+#popover {
+ border:1px solid black;
+ inset: auto;
+ margin:0;
+ padding:0;
+ position-area: top left;
+}
+body { margin: 0; }
+</style>
+
+<script>
+promise_test(async (t) => {
+ assert_false(popover.matches(':popover-open'));
+ await clickOn(button);
+ assert_true(popover.matches(':popover-open'));
+ // Popover should be anchored to the button.
+ assert_equals(popover.offsetLeft + popover.offsetWidth, button.offsetLeft);
+ assert_equals(popover.offsetTop + popover.offsetHeight, button.offsetTop);
+}, 'Popover invokers form an implicit anchor reference');
+</script>