-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathNodePrintExtensions.cs
More file actions
83 lines (71 loc) · 2.31 KB
/
Copy pathNodePrintExtensions.cs
File metadata and controls
83 lines (71 loc) · 2.31 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Text;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html;
using AngleSharp.Text;
using Bunit.Diffing;
namespace Bunit;
/// <summary>
/// Helper methods for pretty printing markup from <see cref="INode"/> and <see cref="INodeList"/>.
/// </summary>
internal static class NodePrintExtensions
{
/// <summary>
/// Writes the serialization of the node guided by the formatter.
/// </summary>
/// <param name="nodes">The nodes to serialize.</param>
/// <param name="writer">The output target of the serialization.</param>
/// <param name="formatter">The formatter to use.</param>
public static void ToHtml(this IEnumerable<INode> nodes, TextWriter writer, IMarkupFormatter formatter)
{
ArgumentNullException.ThrowIfNull(nodes);
foreach (var node in nodes)
{
node.ToHtml(writer, formatter);
}
}
/// <summary>
/// Uses the <see cref="DiffMarkupFormatter"/> to generate a HTML markup string
/// from a <see cref="IMarkupFormattable"/> <paramref name="markupFormattable"/>.
/// The generated HTML markup will NOT include the internal Blazor attributes
/// added to elements.
/// </summary>
public static string ToDiffMarkup(this IMarkupFormattable markupFormattable)
{
ArgumentNullException.ThrowIfNull(markupFormattable);
using var sw = new StringWriter();
markupFormattable.ToHtml(sw, new DiffMarkupFormatter());
return sw.ToString();
}
/// <summary>
/// Converts an <see cref="IElement"/> into a HTML markup string,
/// with only its tag and attributes included in the output. All
/// child nodes are skipped.
/// </summary>
public static string ToMarkupElementOnly(this IElement element)
{
ArgumentNullException.ThrowIfNull(element);
var diffMarkupFormatter = new DiffMarkupFormatter();
var result = new StringBuilder();
result.Append(Symbols.LessThan);
var prefix = element.Prefix;
var name = element.LocalName;
var tag = !string.IsNullOrEmpty(prefix) ? string.Concat(prefix, ":", name) : name;
result.Append(tag);
foreach (var attribute in element.Attributes)
{
result.Append(' ').Append(diffMarkupFormatter.ConvertToString(attribute));
}
if (element.HasChildNodes)
{
result.Append(Symbols.GreaterThan);
result.Append("...");
result.Append("</").Append(tag).Append('>');
}
else
{
result.Append(" />");
}
return result.ToString();
}
}