Skip to content

Commit 5cb90f5

Browse files
Fix anchor lookup with nested components (#155)
1 parent 9411d42 commit 5cb90f5

2 files changed

Lines changed: 417 additions & 5 deletions

File tree

collagraph/fragment.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,15 +110,15 @@ def register_child(self, child: Fragment) -> None:
110110

111111
def first(self) -> Any | None:
112112
"""
113-
Returns the first DOM element (if any), from either itself, or its direct
114-
decendants, in case of virtual fragments. Should not be deeper since an
115-
anchor lives in the same depth in the tree.
113+
Returns the first DOM element (if any), from either itself, or its
114+
descendants. This recursively searches through children to find the
115+
first actual DOM element.
116116
"""
117117
if self.element:
118118
return self.element
119119
for child in self.children:
120-
if child.element:
121-
return child.element
120+
if element := child.first():
121+
return element
122122

123123
def anchor(self) -> Any | None:
124124
"""
@@ -146,6 +146,12 @@ def anchor(self) -> Any | None:
146146
if element := parent.slot_contents[idx].first():
147147
return element
148148

149+
# No sibling anchor found at this level. If the parent doesn't have
150+
# its own element (e.g., ComponentFragment, ControlFlowFragment), climb
151+
# up the tree to find an anchor from the parent's siblings.
152+
if not parent.element and parent.parent:
153+
return parent.anchor()
154+
149155
return None
150156

151157
def set_attribute(self, attr: str, value: Any):

0 commit comments

Comments
 (0)