From 22e397b1f415b04f9d871cda71defb0fac8a570c Mon Sep 17 00:00:00 2001 From: iska Date: Mon, 30 Mar 2015 23:30:41 +0200 Subject: [PATCH] Add a tree-description method for HTML Node The tree description method dumps the HTML tree rooted at this node in the same style as the HTML5Lib tests --- HTMLKit/HTMLNode.h | 2 ++ HTMLKit/HTMLNode.m | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/HTMLKit/HTMLNode.h b/HTMLKit/HTMLNode.h index 70bbdfe..4699522 100644 --- a/HTMLKit/HTMLNode.h +++ b/HTMLKit/HTMLNode.h @@ -80,4 +80,6 @@ typedef NS_ENUM(short, HTMLNodeType) - (NSEnumerator *)treeEnumerator; - (NSEnumerator *)reverseTreeEnumerator; +- (NSString *)treeDescription; + @end diff --git a/HTMLKit/HTMLNode.m b/HTMLKit/HTMLNode.m index 3d0c6f4..f46d77b 100644 --- a/HTMLKit/HTMLNode.m +++ b/HTMLKit/HTMLNode.m @@ -353,6 +353,36 @@ NS_INLINE void CheckInvalidCombination(HTMLNode *parent, HTMLNode *node, NSStrin return copy; } +#pragma mark - Description + +- (NSString *)treeDescription +{ + NSMutableString *string = [NSMutableString string]; + + __weak __block void (^ weakAccumulator) (HTMLNode *, NSUInteger); + void (^ accumulator) (HTMLNode *, NSUInteger); + static NSString *prefix = @"| "; + + weakAccumulator = accumulator = ^ (HTMLNode *node, NSUInteger level) { + + NSString *indent = [prefix stringByPaddingToLength:level * 2 + prefix.length + withString:@" " + startingAtIndex:0]; + if (level > 0) { + [string appendString:@"\n"]; + } + + [string appendString:indent]; + [string appendString:node.description]; + + for (HTMLNode *child in node.childNodes) { + weakAccumulator(child, level + 1); + } + }; + accumulator(self, 0); + + return string; +} - (NSString *)description {