This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
TagHelperOutputExtensions.cs
428 lines (374 loc) · 16.9 KB
/
TagHelperOutputExtensions.cs
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
428
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
/// <summary>
/// Utility related extensions for <see cref="TagHelperOutput"/>.
/// </summary>
public static class TagHelperOutputExtensions
{
private static readonly char[] SpaceChars = { '\u0020', '\u0009', '\u000A', '\u000C', '\u000D' };
/// <summary>
/// Copies a user-provided attribute from <paramref name="context"/>'s
/// <see cref="TagHelperContext.AllAttributes"/> to <paramref name="tagHelperOutput"/>'s
/// <see cref="TagHelperOutput.Attributes"/>.
/// </summary>
/// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param>
/// <param name="attributeName">The name of the bound attribute.</param>
/// <param name="context">The <see cref="TagHelperContext"/>.</param>
/// <remarks>
/// <para>
/// Only copies the attribute if <paramref name="tagHelperOutput"/>'s
/// <see cref="TagHelperOutput.Attributes"/> does not contain an attribute with the given
/// <paramref name="attributeName"/>.
/// </para>
/// <para>
/// Duplicate attributes same name in <paramref name="context"/>'s <see cref="TagHelperContext.AllAttributes"/>
/// or <paramref name="tagHelperOutput"/>'s <see cref="TagHelperOutput.Attributes"/> may result in copied
/// attribute order not being maintained.
/// </para></remarks>
public static void CopyHtmlAttribute(
this TagHelperOutput tagHelperOutput,
string attributeName,
TagHelperContext context)
{
if (tagHelperOutput == null)
{
throw new ArgumentNullException(nameof(tagHelperOutput));
}
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!tagHelperOutput.Attributes.ContainsName(attributeName))
{
var copiedAttribute = false;
// We iterate context.AllAttributes backwards since we prioritize TagHelperOutput values occurring
// before the current context.AllAttribtes[i].
for (var i = context.AllAttributes.Count - 1; i >= 0; i--)
{
// We look for the original attribute so we can restore the exact attribute name the user typed in
// approximately the same position where the user wrote it in the Razor source.
if (string.Equals(
attributeName,
context.AllAttributes[i].Name,
StringComparison.OrdinalIgnoreCase))
{
CopyHtmlAttribute(i, tagHelperOutput, context);
copiedAttribute = true;
}
}
if (!copiedAttribute)
{
throw new ArgumentException(
Resources.FormatTagHelperOutput_AttributeDoesNotExist(attributeName, nameof(TagHelperContext)),
nameof(attributeName));
}
}
}
/// <summary>
/// Merges the given <paramref name="tagBuilder"/>'s <see cref="TagBuilder.Attributes"/> into the
/// <paramref name="tagHelperOutput"/>.
/// </summary>
/// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param>
/// <param name="tagBuilder">The <see cref="TagBuilder"/> to merge attributes from.</param>
/// <remarks>Existing <see cref="TagHelperOutput.Attributes"/> on the given <paramref name="tagHelperOutput"/>
/// are not overridden; "class" attributes are merged with spaces.</remarks>
public static void MergeAttributes(this TagHelperOutput tagHelperOutput, TagBuilder tagBuilder)
{
if (tagHelperOutput == null)
{
throw new ArgumentNullException(nameof(tagHelperOutput));
}
if (tagBuilder == null)
{
throw new ArgumentNullException(nameof(tagBuilder));
}
foreach (var attribute in tagBuilder.Attributes)
{
if (!tagHelperOutput.Attributes.ContainsName(attribute.Key))
{
tagHelperOutput.Attributes.Add(attribute.Key, attribute.Value);
}
else if (string.Equals(attribute.Key, "class", StringComparison.OrdinalIgnoreCase))
{
TagHelperAttribute classAttribute;
var found = tagHelperOutput.Attributes.TryGetAttribute("class", out classAttribute);
Debug.Assert(found);
var newAttribute = new TagHelperAttribute(
classAttribute.Name,
new ClassAttributeHtmlContent(classAttribute.Value, attribute.Value),
classAttribute.ValueStyle);
tagHelperOutput.Attributes.SetAttribute(newAttribute);
}
}
}
/// <summary>
/// Removes the given <paramref name="attributes"/> from <paramref name="tagHelperOutput"/>'s
/// <see cref="TagHelperOutput.Attributes"/>.
/// </summary>
/// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param>
/// <param name="attributes">Attributes to remove.</param>
public static void RemoveRange(
this TagHelperOutput tagHelperOutput,
IEnumerable<TagHelperAttribute> attributes)
{
if (tagHelperOutput == null)
{
throw new ArgumentNullException(nameof(tagHelperOutput));
}
if (attributes == null)
{
throw new ArgumentNullException(nameof(attributes));
}
foreach (var attribute in attributes.ToArray())
{
tagHelperOutput.Attributes.Remove(attribute);
}
}
/// <summary>
/// Adds the given <paramref name="classValue"/> to the <paramref name="tagHelperOutput"/>'s
/// <see cref="TagHelperOutput.Attributes"/>.
/// </summary>
/// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param>
/// <param name="classValue">The class value to add.</param>
/// <param name="htmlEncoder">The current HTML encoder.</param>
public static void AddClass(
this TagHelperOutput tagHelperOutput,
string classValue,
HtmlEncoder htmlEncoder)
{
if (tagHelperOutput == null)
{
throw new ArgumentNullException(nameof(tagHelperOutput));
}
if (string.IsNullOrEmpty(classValue))
{
return;
}
var encodedSpaceChars = SpaceChars.Where(x => !x.Equals('\u0020')).Select(x => htmlEncoder.Encode(x.ToString())).ToArray();
if (SpaceChars.Any(classValue.Contains) || encodedSpaceChars.Any(value => classValue.IndexOf(value, StringComparison.Ordinal) >= 0))
{
throw new ArgumentException(Resources.ArgumentCannotContainHtmlSpace, nameof(classValue));
}
if (!tagHelperOutput.Attributes.TryGetAttribute("class", out TagHelperAttribute classAttribute))
{
tagHelperOutput.Attributes.Add("class", classValue);
}
else
{
var currentClassValue = ExtractClassValue(classAttribute, htmlEncoder);
var encodedClassValue = htmlEncoder.Encode(classValue);
if (string.Equals(currentClassValue, encodedClassValue, StringComparison.Ordinal))
{
return;
}
var arrayOfClasses = currentClassValue.Split(SpaceChars, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(perhapsEncoded => perhapsEncoded.Split(encodedSpaceChars, StringSplitOptions.RemoveEmptyEntries))
.ToArray();
if (arrayOfClasses.Contains(encodedClassValue, StringComparer.Ordinal))
{
return;
}
var newClassAttribute = new TagHelperAttribute(
classAttribute.Name,
new HtmlString($"{currentClassValue} {encodedClassValue}"),
classAttribute.ValueStyle);
tagHelperOutput.Attributes.SetAttribute(newClassAttribute);
}
}
/// <summary>
/// Removes the given <paramref name="classValue"/> from the <paramref name="tagHelperOutput"/>'s
/// <see cref="TagHelperOutput.Attributes"/>.
/// </summary>
/// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param>
/// <param name="classValue">The class value to remove.</param>
/// <param name="htmlEncoder">The current HTML encoder.</param>
public static void RemoveClass(
this TagHelperOutput tagHelperOutput,
string classValue,
HtmlEncoder htmlEncoder)
{
if (tagHelperOutput == null)
{
throw new ArgumentNullException(nameof(tagHelperOutput));
}
var encodedSpaceChars = SpaceChars.Where(x => !x.Equals('\u0020')).Select(x => htmlEncoder.Encode(x.ToString())).ToArray();
if (SpaceChars.Any(classValue.Contains) || encodedSpaceChars.Any(value => classValue.IndexOf(value, StringComparison.Ordinal) >= 0))
{
throw new ArgumentException(Resources.ArgumentCannotContainHtmlSpace, nameof(classValue));
}
if (!tagHelperOutput.Attributes.TryGetAttribute("class", out TagHelperAttribute classAttribute))
{
return;
}
var currentClassValue = ExtractClassValue(classAttribute, htmlEncoder);
if (string.IsNullOrEmpty(currentClassValue))
{
return;
}
var encodedClassValue = htmlEncoder.Encode(classValue);
if (string.Equals(currentClassValue, encodedClassValue, StringComparison.Ordinal))
{
tagHelperOutput.Attributes.Remove(tagHelperOutput.Attributes["class"]);
return;
}
if (!currentClassValue.Contains(encodedClassValue))
{
return;
}
var listOfClasses = currentClassValue.Split(SpaceChars, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(perhapsEncoded => perhapsEncoded.Split(encodedSpaceChars, StringSplitOptions.RemoveEmptyEntries))
.ToList();
if (!listOfClasses.Contains(encodedClassValue))
{
return;
}
listOfClasses.RemoveAll(x => x.Equals(encodedClassValue));
if (listOfClasses.Any())
{
var joinedClasses = new HtmlString(string.Join(" ", listOfClasses));
tagHelperOutput.Attributes.SetAttribute(classAttribute.Name, joinedClasses);
}
else
{
tagHelperOutput.Attributes.Remove(tagHelperOutput.Attributes["class"]);
}
}
private static string ExtractClassValue(
TagHelperAttribute classAttribute,
HtmlEncoder htmlEncoder)
{
string extractedClassValue;
switch (classAttribute.Value)
{
case string valueAsString:
extractedClassValue = htmlEncoder.Encode(valueAsString);
break;
case HtmlString valueAsHtmlString:
extractedClassValue = valueAsHtmlString.Value;
break;
case IHtmlContent htmlContent:
using (var stringWriter = new StringWriter())
{
htmlContent.WriteTo(stringWriter, htmlEncoder);
extractedClassValue = stringWriter.ToString();
}
break;
default:
extractedClassValue = htmlEncoder.Encode(classAttribute.Value?.ToString());
break;
}
var currentClassValue = extractedClassValue ?? string.Empty;
return currentClassValue;
}
private static void CopyHtmlAttribute(
int allAttributeIndex,
TagHelperOutput tagHelperOutput,
TagHelperContext context)
{
var existingAttribute = context.AllAttributes[allAttributeIndex];
// Move backwards through context.AllAttributes from the provided index until we find a familiar attribute
// in tagHelperOutput where we can insert the copied value after the familiar one.
for (var i = allAttributeIndex - 1; i >= 0; i--)
{
var previousName = context.AllAttributes[i].Name;
var index = IndexOfFirstMatch(previousName, tagHelperOutput.Attributes);
if (index != -1)
{
tagHelperOutput.Attributes.Insert(index + 1, existingAttribute);
return;
}
}
// Move forward through context.AllAttributes from the provided index until we find a familiar attribute in
// tagHelperOutput where we can insert the copied value.
for (var i = allAttributeIndex + 1; i < context.AllAttributes.Count; i++)
{
var nextName = context.AllAttributes[i].Name;
var index = IndexOfFirstMatch(nextName, tagHelperOutput.Attributes);
if (index != -1)
{
tagHelperOutput.Attributes.Insert(index, existingAttribute);
return;
}
}
// Couldn't determine the attribute's location, add it to the end.
tagHelperOutput.Attributes.Add(existingAttribute);
}
private static int IndexOfFirstMatch(string name, TagHelperAttributeList attributes)
{
for (var i = 0; i < attributes.Count; i++)
{
if (string.Equals(name, attributes[i].Name, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
return -1;
}
private class ClassAttributeHtmlContent : IHtmlContent
{
private readonly object _left;
private readonly string _right;
public ClassAttributeHtmlContent(object left, string right)
{
_left = left;
_right = right;
}
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
// Write out "{left} {right}" in the common nothing-empty case.
var wroteLeft = false;
if (_left != null)
{
var htmlContent = _left as IHtmlContent;
if (htmlContent != null)
{
// Ignore case where htmlContent is HtmlString.Empty. At worst, will add a leading space to the
// generated attribute value.
htmlContent.WriteTo(writer, encoder);
wroteLeft = true;
}
else
{
var stringValue = _left.ToString();
if (!string.IsNullOrEmpty(stringValue))
{
encoder.Encode(writer, stringValue);
wroteLeft = true;
}
}
}
if (!string.IsNullOrEmpty(_right))
{
if (wroteLeft)
{
writer.Write(' ');
}
encoder.Encode(writer, _right);
}
}
}
}
}