-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathHtmlizer.cs
More file actions
427 lines (379 loc) · 11 KB
/
Htmlizer.cs
File metadata and controls
427 lines (379 loc) · 11 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// This code/file was originally copied from https://github.com/dotnet/aspnetcore/
// It's content has been modified from the original.
// See the NOTICE.md at the root of this repository for a copy
// of the license from the aspnetcore repository.
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Bunit.Rendering;
namespace Bunit;
/// <summary>
/// This file is based on
/// https://source.dot.net/#Microsoft.AspNetCore.Mvc.ViewFeatures/RazorComponents/HtmlRenderer.cs.
/// </summary>
internal static class Htmlizer
{
private const string BlazorInternalAttrPrefix = "__internal_";
private const string BlazorCssScopeAttrPrefix = "b-";
internal const string BlazorAttrPrefix = "blazor:";
internal const string ElementReferenceAttrName = BlazorAttrPrefix + "elementReference";
private static readonly HashSet<string> SelfClosingElements =
new(StringComparer.OrdinalIgnoreCase)
{
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"link",
"meta",
"param",
"source",
"track",
"wbr",
};
public static bool IsBlazorAttribute(string attributeName)
{
ArgumentNullException.ThrowIfNull(attributeName);
return attributeName.StartsWith(BlazorAttrPrefix, StringComparison.Ordinal)
|| attributeName.StartsWith(BlazorCssScopeAttrPrefix, StringComparison.Ordinal);
}
public static string ToBlazorAttribute(string attributeName)
{
return $"{BlazorAttrPrefix}{attributeName}";
}
public static string GetHtml(int componentId, BunitRenderer renderer)
{
var context = new HtmlRenderingContext(renderer);
var componentState = renderer.GetRenderedComponent(componentId);
var frames = context.GetRenderTreeFrames(componentId);
var newPosition = RenderFrames(context, frames, 0, frames.Count);
componentState.SetMarkupIndices(0, context.Result.Length);
Debug.Assert(
newPosition == frames.Count,
$"frames.Length = {frames.Count}. newPosition = {newPosition}"
);
return context.Result.ToString();
}
private static RenderTreeFrame RenderComponent(HtmlRenderingContext context, in RenderTreeFrame frame)
{
var startIndex = context.Result.Length;
var frames = context.GetRenderTreeFrames(frame.ComponentId);
RenderFrames(context, frames, 0, frames.Count);
var endIndex = context.Result.Length;
context.GetRenderedComponent(frame.ComponentId).SetMarkupIndices(startIndex, endIndex);
return frame;
}
private static int RenderFrames(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position,
int maxElements)
{
var nextPosition = position;
var endPosition = position + maxElements;
while (position < endPosition)
{
nextPosition = RenderCore(context, frames, position);
if (position == nextPosition)
{
throw new InvalidOperationException("We didn't consume any input.");
}
position = nextPosition;
}
return nextPosition;
}
private static int RenderCore(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position
)
{
var frame = frames.Array[position];
switch (frame.FrameType)
{
case RenderTreeFrameType.Element:
return RenderElement(context, frames, position);
case RenderTreeFrameType.Attribute:
throw new InvalidOperationException(
$"Attributes should only be encountered within {nameof(RenderElement)}"
);
case RenderTreeFrameType.Text:
AppendEscapeText(context, frame.TextContent);
return position + 1;
case RenderTreeFrameType.Markup:
context.Result.Append(frame.MarkupContent);
return position + 1;
case RenderTreeFrameType.Component:
return RenderChildComponent(context, frames, position);
case RenderTreeFrameType.Region:
return RenderFrames(context, frames, position + 1, frame.RegionSubtreeLength - 1);
case RenderTreeFrameType.ElementReferenceCapture:
case RenderTreeFrameType.ComponentReferenceCapture:
return position + 1;
#if NET8_0_OR_GREATER
case RenderTreeFrameType.NamedEvent:
return position + 1;
#endif
default:
throw new InvalidOperationException(
$"Invalid element frame type '{frame.FrameType}'."
);
}
}
private static int RenderChildComponent(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position)
{
var frame = frames.Array[position];
frame = RenderComponent(context, in frame);
return position + frame.ComponentSubtreeLength;
}
private static int RenderElement(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position
)
{
var frame = frames.Array[position];
var result = context.Result;
result.Append('<');
result.Append(frame.ElementName);
var afterAttributes = RenderAttributes(
context,
frames,
position + 1,
frame.ElementSubtreeLength - 1,
out var capturedValueAttribute
);
// When we see an <option> as a descendant of a <select>, and the option's "value" attribute matches the
// "value" attribute on the <select>, then we auto-add the "selected" attribute to that option. This is
// a way of converting Blazor's select binding feature to regular static HTML.
if (
context.ClosestSelectValueAsString != null
&& string.Equals(frame.ElementName, "option", StringComparison.OrdinalIgnoreCase)
&& string.Equals(
capturedValueAttribute,
context.ClosestSelectValueAsString,
StringComparison.Ordinal
)
)
{
result.Append(" selected");
}
var remainingElements = frame.ElementSubtreeLength + position - afterAttributes;
if (remainingElements > 0)
{
result.Append('>');
var isSelect = string.Equals(
frame.ElementName,
"select",
StringComparison.OrdinalIgnoreCase
);
if (isSelect)
{
context.ClosestSelectValueAsString = capturedValueAttribute;
}
var afterElement = RenderChildren(context, frames, afterAttributes, remainingElements);
if (isSelect)
{
// There's no concept of nested <select> elements, so as soon as we're exiting one of them,
// we can safely say there is no longer any value for this
context.ClosestSelectValueAsString = null;
}
result.Append("</");
result.Append(frame.ElementName);
result.Append('>');
return afterElement;
}
if (SelfClosingElements.Contains(frame.ElementName))
{
result.Append(" />");
}
else
{
result.Append('>');
result.Append("</");
result.Append(frame.ElementName);
result.Append('>');
}
Debug.Assert(
afterAttributes == position + frame.ElementSubtreeLength,
$"afterAttributes = {afterAttributes}. position = {position}. frame.ElementSubtreeLength = {frame.ElementSubtreeLength}"
);
return afterAttributes;
}
private static int RenderChildren(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position,
int maxElements
)
{
if (maxElements == 0)
{
return position;
}
return RenderFrames(context, frames, position, maxElements);
}
private static int RenderAttributes(
HtmlRenderingContext context,
ArrayRange<RenderTreeFrame> frames,
int position,
int maxElements,
out string? capturedValueAttribute
)
{
capturedValueAttribute = null;
if (maxElements == 0)
{
return position;
}
var result = context.Result;
for (var i = 0; i < maxElements; i++)
{
var candidateIndex = position + i;
var frame = frames.Array[candidateIndex];
// Added to write ElementReferenceCaptureId to DOM
if (frame.FrameType == RenderTreeFrameType.ElementReferenceCapture)
{
var value = $" {ElementReferenceAttrName}=\"{frame.ElementReferenceCaptureId}\"";
result.Append(value);
}
if (frame.FrameType != RenderTreeFrameType.Attribute)
{
return candidateIndex;
}
if (frame.AttributeName.Equals("value", StringComparison.OrdinalIgnoreCase))
{
capturedValueAttribute = frame.AttributeValue as string;
}
if (frame.AttributeEventHandlerId > 0)
{
// NOTE: this was changed to make it more obvious
// that this is a generated/special blazor attribute
// used for tracking event handler id's
result.Append(' ');
result.Append(BlazorAttrPrefix);
result.Append(frame.AttributeName);
result.Append('=');
result.Append('"');
result.Append(frame.AttributeEventHandlerId.ToString(CultureInfo.InvariantCulture));
result.Append('"');
continue;
}
switch (frame.AttributeValue)
{
case bool flag
when flag
&& frame.AttributeName.StartsWith(
BlazorInternalAttrPrefix,
StringComparison.Ordinal
):
// NOTE: This was added to make it more obvious
// that this is a generated/special blazor attribute
// for internal usage
var nameParts = frame.AttributeName.Split(
'_',
StringSplitOptions.RemoveEmptyEntries
);
result.Append(' ');
result.Append(BlazorAttrPrefix);
result.Append(nameParts[2]);
result.Append(':');
result.Append(nameParts[1]);
break;
case true:
result.Append(' ');
result.Append(frame.AttributeName);
break;
case string value:
result.Append(' ');
result.Append(frame.AttributeName);
result.Append('=');
result.Append('"');
AppendEscapeAttributeValue(context, value);
result.Append('"');
break;
default:
break;
}
}
return position + maxElements;
}
private static void AppendEscapeText(HtmlRenderingContext context, string value)
{
var valueSpan = value.AsSpan();
var copyFromIndex = 0;
for (var index = 0; index < valueSpan.Length; index++)
{
var c = valueSpan[index];
if (c is '<' or '>' or '&')
{
context.Result.Append(valueSpan.Slice(copyFromIndex, index - copyFromIndex));
switch (c)
{
case '<':
context.Result.Append("<");
break;
case '>':
context.Result.Append(">");
break;
case '&':
context.Result.Append("&");
break;
}
copyFromIndex = index + 1;
}
}
if (copyFromIndex < valueSpan.Length)
{
context.Result.Append(valueSpan.Slice(copyFromIndex));
}
}
private static void AppendEscapeAttributeValue(HtmlRenderingContext context, string value)
{
var valueSpan = value.AsSpan();
var copyFromIndex = 0;
for (var index = 0; index < valueSpan.Length; index++)
{
var c = valueSpan[index];
if (c is '"' or '&')
{
context.Result.Append(valueSpan.Slice(copyFromIndex, index - copyFromIndex));
switch (c)
{
case '"':
context.Result.Append(""");
break;
case '&':
context.Result.Append("&");
break;
}
copyFromIndex = index + 1;
}
}
if (copyFromIndex < valueSpan.Length)
{
context.Result.Append(valueSpan.Slice(copyFromIndex));
}
}
private sealed class HtmlRenderingContext
{
private readonly BunitRenderer renderer;
public HtmlRenderingContext(BunitRenderer renderer)
{
this.renderer = renderer;
}
public ArrayRange<RenderTreeFrame> GetRenderTreeFrames(int componentId)
=> renderer.GetCurrentRenderTreeFrames(componentId);
public IRenderedComponent GetRenderedComponent(int componentId)
=> renderer.GetRenderedComponent(componentId);
public StringBuilder Result { get; } = new();
public string? ClosestSelectValueAsString { get; set; }
}
}