Skip to content

Commit

Permalink
Implements NodeBase.depth and node ordering w/o TagNode.location_path
Browse files Browse the repository at this point in the history
  • Loading branch information
funkyfuture committed Apr 15, 2024
1 parent d2429b3 commit ac92f3c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
9 changes: 6 additions & 3 deletions _delb/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1960,9 +1960,12 @@ def css_select(

@property
def depth(self) -> int:
if self.parent is None:
return 0
return self.location_path.count("/")
result = 0
node = self
while node.parent:
node = node.parent
result += 1
return result

@altered_default_filters()
def detach(self, retain_child_nodes: bool = False) -> _ElementWrappingNode:
Expand Down
20 changes: 15 additions & 5 deletions _delb/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,19 +362,29 @@ def _random_unused_prefix(namespaces: etree._NSMap) -> str:


def sort_nodes_in_document_order(nodes: Iterable[NodeBase]) -> Iterator[NodeBase]:
node_index_cache: dict[int, int] = {}
sorter = _NodesSorter()
for node in nodes:
if not _is_node_of_type(node, "TagNode"):
raise NotImplementedError(
"Support for sorting other node types than TagNodes isn't scheduled"
"yet."
)

node = cast("TagNode", node)
if node.parent is None:
path = []
else:
path = [int(x[2:-1]) for x in node.location_path.split("/")[1:]]
sorter.add(path, node)
ancestors_indexes = []

while node.parent is not None:
node_id = id(node)
if node_id in node_index_cache:
index = node_index_cache[node_id]
else:
assert node.index is not None
node_index_cache[node_id] = index = node.index
ancestors_indexes.append(index)
node = node.parent

sorter.add(tuple(reversed(ancestors_indexes)), node)
yield from sorter.emit()


Expand Down

0 comments on commit ac92f3c

Please sign in to comment.