-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathTagBuilder.cs
More file actions
257 lines (222 loc) · 6.5 KB
/
TagBuilder.cs
File metadata and controls
257 lines (222 loc) · 6.5 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;
using ServiceStack.Text;
namespace ServiceStack.Html
{
public class TagBuilder
{
public const string IdAttributeDotReplacement = "_";
private const string AttributeFormat = @" {0}=""{1}""";
private const string ElementFormatEndTag = "</{0}>";
private const string ElementFormatNormal = "<{0}{1}>{2}</{0}>";
private const string ElementFormatSelfClosing = "<{0}{1} />";
private const string ElementFormatStartTag = "<{0}{1}>";
private string innerHtml;
public TagBuilder(string tagName)
{
if (String.IsNullOrEmpty(tagName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "tagName");
}
TagName = tagName;
Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);
}
public IDictionary<string, string> Attributes { get; private set; }
public string InnerHtml
{
get
{
return innerHtml ?? String.Empty;
}
set
{
innerHtml = value;
}
}
public string TagName { get; private set; }
public void AddCssClass(string value)
{
string currentValue;
if (Attributes.TryGetValue("class", out currentValue))
{
Attributes["class"] = value + " " + currentValue;
}
else
{
Attributes["class"] = value;
}
}
public static string CreateSanitizedId(string originalId)
{
return CreateSanitizedId(originalId, TagBuilder.IdAttributeDotReplacement);
}
internal static string CreateSanitizedId(string originalId, string invalidCharReplacement)
{
if (String.IsNullOrEmpty(originalId))
{
return null;
}
if (invalidCharReplacement == null) {
throw new ArgumentNullException("invalidCharReplacement");
}
char firstChar = originalId[0];
if (!Html401IdUtil.IsLetter(firstChar))
{
// the first character must be a letter
return null;
}
var sb = StringBuilderCache.Allocate();
sb.Append(firstChar);
for (int i = 1; i < originalId.Length; i++)
{
char thisChar = originalId[i];
if (Html401IdUtil.IsValidIdCharacter(thisChar))
{
sb.Append(thisChar);
}
else
{
sb.Append(invalidCharReplacement);
}
}
return StringBuilderCache.ReturnAndFree(sb);
}
public void GenerateId(string name)
{
if (!Attributes.ContainsKey("id")) {
string sanitizedId = CreateSanitizedId(name, IdAttributeDotReplacement);
if (!String.IsNullOrEmpty(sanitizedId)) {
Attributes["id"] = sanitizedId;
}
}
}
private void AppendAttributes(StringBuilder sb)
{
foreach (var attribute in Attributes) {
string key = attribute.Key;
if (String.Equals(key, "id", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value)) {
continue; // DevDiv Bugs #227595: don't output empty IDs
}
string value = PclExportClient.Instance.HtmlAttributeEncode(attribute.Value);
sb.Append(' ')
.Append(key)
.Append("=\"")
.Append(value)
.Append('"');
}
}
public void MergeAttribute(string key, string value)
{
MergeAttribute(key, value, false /* replaceExisting */);
}
public void MergeAttribute(string key, string value, bool replaceExisting)
{
if (String.IsNullOrEmpty(key))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "key");
}
if (replaceExisting || !Attributes.ContainsKey(key))
{
Attributes[key] = value;
}
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes)
{
MergeAttributes(attributes, false /* replaceExisting */);
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting)
{
if (attributes != null)
{
foreach (var entry in attributes)
{
string key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
string value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);
MergeAttribute(key, value, replaceExisting);
}
}
}
public void SetInnerText(string innerText)
{
InnerHtml = PclExportClient.Instance.HtmlEncode(innerText);
}
internal MvcHtmlString ToMvcHtmlString(TagRenderMode renderMode)
{
return ToHtmlString(renderMode);
}
internal MvcHtmlString ToHtmlString(TagRenderMode renderMode)
{
return MvcHtmlString.Create(ToString(renderMode));
}
public override string ToString()
{
return ToString(TagRenderMode.Normal);
}
public string ToString(TagRenderMode renderMode)
{
var sb = StringBuilderCache.Allocate();
switch (renderMode) {
case TagRenderMode.StartTag:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>');
break;
case TagRenderMode.EndTag:
sb.Append("</")
.Append(TagName)
.Append('>');
break;
case TagRenderMode.SelfClosing:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append(" />");
break;
default:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>')
.Append(InnerHtml)
.Append("</")
.Append(TagName)
.Append('>');
break;
}
return StringBuilderCache.ReturnAndFree(sb);
}
// Valid IDs are defined in http://www.w3.org/TR/html401/types.html#type-id
private static class Html401IdUtil
{
private static bool IsAllowableSpecialCharacter(char c)
{
switch (c)
{
case '-':
case '_':
case ':':
// note that we're specifically excluding the '.' character
return true;
default:
return false;
}
}
private static bool IsDigit(char c)
{
return ('0' <= c && c <= '9');
}
public static bool IsLetter(char c)
{
return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
}
public static bool IsValidIdCharacter(char c)
{
return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));
}
}
}
}