From 968a99a76c3861b8e86813db487f705e4aec355f Mon Sep 17 00:00:00 2001 From: Andrew Hayzen Date: Thu, 18 Jan 2024 16:55:14 +0000 Subject: [PATCH] block_builder: promotee tags might have siblings eg ```html
``` Needs to become ```html
``` Before it became ```html
``` This solves the following crash ValueError: Cannot replace one element with another when the element to be replaced is not part of a tree. Related #141 --- wagtail_wordpress_import/block_builder.py | 40 ++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/wagtail_wordpress_import/block_builder.py b/wagtail_wordpress_import/block_builder.py index e0d6a5a8..26081b84 100644 --- a/wagtail_wordpress_import/block_builder.py +++ b/wagtail_wordpress_import/block_builder.py @@ -51,7 +51,45 @@ def promote_child_tags(self): promotees = self.soup.findAll(promotee) for promotee in promotees: if promotee.parent.name in removee_tags: - promotee.parent.replace_with(promotee) + # Extract the promotee tag from a removee tag + # + #
+ #
+ # + #
+ #
+ # + # Needs to become + #
+ #
+ # + #
+ #
+ # + # Before this change it became + #
+ + # This is the only item to replace the parent + next_siblings_count = len(list(promotee.next_siblings)) + previous_siblings_count = len(list(promotee.previous_siblings)) + if next_siblings_count == 0 and previous_siblings_count == 0: + promotee.parent.replace_with(promotee) + # There are no more after this item move after the parent + elif next_siblings_count == 0: + promotee.parent.insert_after(promotee.extract()) + # There are no more before this item move after the parent + elif previous_siblings_count == 0: + promotee.parent.insert_before(promotee.extract()) + # This item is in the middle of a block so create a new block + else: + new_tag = self.soup.new_tag(promotee.parent.name, **promotee.parent.attrs) + while promotee.next_sibling is not None: + new_tag.append(promotee.next_sibling.extract()) + + promotee.parent.insert_after(new_tag) + # We want promotee to be before new_tag so insert second + promotee.parent.insert_after(promotee.extract()) + def get_builder_function(self, element): """