Refactor: Create a g_tag_is_unmergeable

Both `mergeSiblingGroupsWithCommonAttributes` and `removeNestedGroups`
used the same code in different forms.  Extract it into its own
function.

Signed-off-by: Niels Thykier <niels@thykier.net>
This commit is contained in:
Niels Thykier 2020-05-17 19:04:53 +00:00
parent 7a83e7148d
commit 0c50bc72ea
No known key found for this signature in database
GPG key ID: A65B78DBE67C7AAC

View file

@ -1022,6 +1022,15 @@ def removeDescriptiveElements(doc, options):
return num return num
def g_tag_is_unmergeable(node):
"""Check if a <g> tag can be merged or not
<g> tags with a title or descriptions should generally be left alone.
"""
return any(True for n in node.childNodes if n.nodeType == Node.ELEMENT_NODE
and n.nodeName in ('title', 'desc') and n.namespaceURI == NS['SVG'])
def removeNestedGroups(node): def removeNestedGroups(node):
""" """
This walks further and further down the tree, removing groups This walks further and further down the tree, removing groups
@ -1038,11 +1047,7 @@ def removeNestedGroups(node):
for child in node.childNodes: for child in node.childNodes:
if child.nodeName == 'g' and child.namespaceURI == NS['SVG'] and len(child.attributes) == 0: if child.nodeName == 'g' and child.namespaceURI == NS['SVG'] and len(child.attributes) == 0:
# only collapse group if it does not have a title or desc as a direct descendant, # only collapse group if it does not have a title or desc as a direct descendant,
for grandchild in child.childNodes: if not g_tag_is_unmergeable(child):
if grandchild.nodeType == Node.ELEMENT_NODE and grandchild.namespaceURI == NS['SVG'] and \
grandchild.nodeName in ['title', 'desc']:
break
else:
groupsToRemove.append(child) groupsToRemove.append(child)
for g in groupsToRemove: for g in groupsToRemove:
@ -1169,11 +1174,7 @@ def mergeSiblingGroupsWithCommonAttributes(elem):
if nextNode.nodeName != 'g' or nextNode.namespaceURI != NS['SVG']: if nextNode.nodeName != 'g' or nextNode.namespaceURI != NS['SVG']:
break break
nextAttributes = {a.nodeName: a.nodeValue for a in nextNode.attributes.values()} nextAttributes = {a.nodeName: a.nodeValue for a in nextNode.attributes.values()}
hasNoMergeTags = (True for n in nextNode.childNodes if attributes != nextAttributes or g_tag_is_unmergeable(nextNode):
if n.nodeType == Node.ELEMENT_NODE
and n.nodeName in ('title', 'desc')
and n.namespaceURI == NS['SVG'])
if attributes != nextAttributes or any(hasNoMergeTags):
break break
else: else:
runElements += 1 runElements += 1