Coverage for phml\utilities\transform\extract.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-04-06 14:05 -0500

1from phml.nodes import Literal, Node, Parent 

2 

3__all__ = ["to_string"] 

4 

5 

6def to_string(node: Node) -> str: 

7 """Get the raw text content of the element. Works similar to 

8 the DOMs Node#textContent getter. 

9 

10 Args: 

11 node (Root | Element | Text): Node to get the text content from 

12 

13 Returns: 

14 str: Raw inner text without formatting. 

15 """ 

16 

17 if isinstance(node, Literal): 

18 return node.content 

19 

20 def concat_text(element: Parent) -> list[str]: 

21 result = [] 

22 

23 for child in element: 

24 if isinstance(child, Parent): 

25 result.extend(concat_text(child)) 

26 elif Literal.is_text(child): 

27 result.append(child.content) 

28 return result 

29 

30 if isinstance(node, Parent): 

31 # Recursive concat 

32 return " ".join(concat_text(node)) 

33 

34 return ""