-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathComponentBoundaryNodeExtractor.cs
More file actions
69 lines (54 loc) · 1.76 KB
/
ComponentBoundaryNodeExtractor.cs
File metadata and controls
69 lines (54 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using AngleSharp.Dom;
namespace Bunit.Rendering;
internal static class ComponentBoundaryNodeExtractor
{
private const string BoundaryStartPrefix = "bl:";
private const string BoundaryEndPrefix = "/bl:";
internal static string StartMarkerFor(int componentId) => $"{BoundaryStartPrefix}{componentId}";
internal static string EndMarkerFor(int componentId) => $"{BoundaryEndPrefix}{componentId}";
internal static INodeList Extract(INodeList rootNodes, int componentId)
{
var startMarker = StartMarkerFor(componentId);
var endMarker = EndMarkerFor(componentId);
var result = new List<INode>();
CollectNodesBetweenMarkers(rootNodes, startMarker, endMarker, result);
return new ReadOnlyNodeList(result);
}
private static bool CollectNodesBetweenMarkers(
INodeList nodes,
string startMarker,
string endMarker,
List<INode> result)
{
for (var i = 0; i < nodes.Length; i++)
{
var node = nodes[i];
if (node is IComment comment && string.Equals(comment.Data, startMarker, StringComparison.Ordinal))
{
for (var j = i + 1; j < nodes.Length; j++)
{
var sibling = nodes[j];
if (sibling is IComment endComment && string.Equals(endComment.Data, endMarker, StringComparison.Ordinal))
{
return true;
}
if (sibling is IComment nestedMarker && IsBoundaryComment(nestedMarker))
{
continue;
}
result.Add(sibling);
}
return true;
}
if (node.HasChildNodes
&& CollectNodesBetweenMarkers(node.ChildNodes, startMarker, endMarker, result))
{
return true;
}
}
return false;
}
private static bool IsBoundaryComment(IComment comment) =>
comment.Data.StartsWith(BoundaryStartPrefix, StringComparison.Ordinal)
|| comment.Data.StartsWith(BoundaryEndPrefix, StringComparison.Ordinal);
}