/
elemi.d
388 lines (261 loc) · 9 KB
/
elemi.d
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
module elemi;
import std.conv;
import std.string;
import std.algorithm;
/// Escape HTML elements.
///
/// Package level: input sanitization is done automatically by the library.
package string escapeHTML(const string text) {
return text.substitute!(
`<`, "<",
`>`, ">",
`&`, "&",
`"`, """,
`'`, "'",
).to!string;
}
/// Serialize attributes
package string serializeAttributes(string[string] attributes) {
// Generate attribute text
string attrHTML;
foreach (key, value; attributes) {
attrHTML ~= format!` %s="%s"`(key, value.escapeHTML);
}
return attrHTML;
}
/// Process the given content, sanitizing user input and passing in already created elements.
package string processContent(T...)(T content) {
string contentText;
static foreach (i, Type; T) {
// Given a string
static if (is(Type == string) || is(Type == wstring) || is(Type == dstring)) {
/// Escape it and add
contentText ~= content[i].escapeHTML;
}
// Given an element, just add it
else contentText ~= content[i];
}
return contentText;
}
/// Represents a HTML element.
///
/// Use [elem] to generate.
struct Element {
// Commonly used elements
/// Doctype info for HTML.
enum HTMLDoctype = "<!DOCTYPE html>";
/// A common head element for adjusting the viewport to mobile devices.
enum MobileViewport = elem!("meta", q{
name="viewport"
content="width=device-width, initial-scale=1"
});
package {
/// HTML of the element.
string html;
/// Added at the end
string postHTML;
}
package this(const string name, const string attributes = null, const string content = null) {
auto attrHTML = attributes.dup;
// Asserts on attributes
debug if (attributes.length) {
assert(attributes[0] == ' ', "The first character of attributes isn't a space");
assert(attributes[1] != ' ', "The second character of attributes cannot be a space");
}
// Create the ending tag
switch (name) {
// Empty elements
case "area", "base", "br", "col", "embed", "hr", "img", "input":
case "keygen", "link", "meta", "param", "source", "track", "wbr":
assert(content.length == 0, "Tag %s cannot have children, its content must be empty.".format(name));
// Instead of a tag end, add a slash at the end of the beginning tag
// Also add a space if there are any attributes
attrHTML ~= (attrHTML ? " " : "") ~ "/";
break;
// Containers
default:
// Add the end tag
postHTML = name.format!"</%s>";
}
html = format!"<%s%s>%s"(name, attrHTML, content);
}
string toString() const {
return html ~ postHTML;
}
/// Create a new element as a child
Element add(string name, string[string] attributes = null, T...)(T content) {
html ~= elem!(name, attributes)(content);
return this;
}
/// Ditto
Element add(string name, string attrHTML = null, T...)(string[string] attributes, T content) {
html ~= elem!(name, attrHTML)(attributes, content);
return this;
}
/// Ditto
Element add(string name, string attrHTML, T...)(T content) {
html ~= elem!(name, attrHTML)(null, content);
return this;
}
/// Add an element as a child
Element add(Element element) {
html ~= element;
return this;
}
/// Add text as a child.
///
/// The text will automatically be sanitized.
Element add(string text) {
html ~= text.escapeHTML;
return this;
}
// Yes. This is legal.
alias toString this;
}
/// Create a HTML element.
///
/// Params:
/// name = Name of the element.
/// attrHTML = Unsanitized attributes to insert.
/// attributes = Attributes for the element.
/// children = Children and text of the element.
/// Returns: a Element type, implictly castable to string.
Element elem(string name, string[string] attributes = null, T...)(T content)
if (!T.length || !is(T[0] == string[string])) {
// Ensure attribute HTML is generated compile-time.
enum attrHTML = attributes.serializeAttributes;
return Element(name, attrHTML, content.processContent);
}
/// Ditto
Element elem(string name, string attrHTML = null, T...)(string[string] attributes, T content) {
import std.stdio : writeln;
enum attrInput = attrHTML.splitter("\n")
.map!q{a.strip}
.filter!q{a.length}
.join(" ");
enum prefix = attrHTML.length ? " " : "";
return Element(
name,
prefix ~ attrInput ~ attributes.serializeAttributes,
content.processContent
);
}
/// Ditto
Element elem(string name, string attrHTML, T...)(T content)
if (!T.length || !is(T[0] == typeof(null)) ) {
return elem!(name, attrHTML)(null, content);
}
///
unittest {
import std.stdio : writeln;
// Compile-time empty type detection
assert(elem!"input" == "<input/>");
assert(elem!"hr" == "<hr/>");
assert(elem!"p" == "<p></p>");
// Content
assert(elem!"p"("Hello, World!") == "<p>Hello, World!</p>");
// Compile-time attributes — variant A
assert(
elem!("a", [ "href": "about:blank", "title": "Destroy this page" ])("Hello, World!")
== `<a href="about:blank" title="Destroy this page">Hello, World!</a>`
);
// Compile-time attributes — variant B
assert(
elem!("a", q{
href="about:blank"
title="Destroy this page" })(
"Hello, World!"
)
== `<a href="about:blank" title="Destroy this page">Hello, World!</a>`
);
// Nesting and input sanitization
assert(
elem!"div"(
elem!"p"("Hello, World!"),
"-> Sanitized"
)
== "<div><p>Hello, World!</p>-> Sanitized</div>"
);
// Sanitized user input in attributes
assert(
elem!"input"(["value": `"XSS!"`])
== `<input value=""XSS!"" />`
);
// Alternative method of nesting
assert(
elem!("div", q{ style="background:#500" })
.add!"p"("Hello, World!")
.add("-> Sanitized")
== `<div style="background:#500"><p>Hello, World!</p>-> Sanitized</div>`
);
}
/// A general example page
unittest {
import std.stdio : writeln;
import std.base64 : Base64;
enum page = Element.HTMLDoctype ~ elem!"html"(
elem!"head"(
elem!("title")("An example document"),
// Metadata
Element.MobileViewport,
elem!("style")(`
html, body {
height: 100%;
font-family: sans-serif;
padding: 0;
margin: 0;
}
.header {
background: #f7a;
font-size: 1.5em;
margin: 0;
padding: 5px;
}
.article {
padding-left: 2em;
}
`.split("\n").map!"a.strip".filter!"a.length".join),
),
elem!"body"(
elem!("header", q{ class="header" })(
elem!"h1"("Example website")
),
elem!"h1"("Welcome to my website!"),
elem!"p"("Hello there,",
elem!"br", "may you want to read some of my articles?"),
elem!("div", q{ class="article" })(
elem!"h2"("Stuff"),
elem!"p"("Description")
)
)
);
enum target = cast(string) Base64.decode([
"PCFET0NUWVBFIGh0bWw+PGh0bWw+PGhlYWQ+PHRpdGxlPkFuIGV4YW1wbGUgZG9jdW",
"1lbnQ8L3RpdGxlPjxtZXRhIG5hbWU9InZpZXdwb3J0IiBjb250ZW50PSJ3aWR0aD1k",
"ZXZpY2Utd2lkdGgsIGluaXRpYWwtc2NhbGU9MSIgLz48c3R5bGU+aHRtbCwgYm9keS",
"B7aGVpZ2h0OiAxMDAlO2ZvbnQtZmFtaWx5OiBzYW5zLXNlcmlmO3BhZGRpbmc6IDA7",
"bWFyZ2luOiAwO30uaGVhZGVyIHtiYWNrZ3JvdW5kOiAjZjdhO2ZvbnQtc2l6ZTogMS",
"41ZW07bWFyZ2luOiAwO3BhZGRpbmc6IDVweDt9LmFydGljbGUge3BhZGRpbmctbGVm",
"dDogMmVtO308L3N0eWxlPjwvaGVhZD48Ym9keT48aGVhZGVyIGNsYXNzPSJoZWFkZX",
"IiPjxoMT5FeGFtcGxlIHdlYnNpdGU8L2gxPjwvaGVhZGVyPjxoMT5XZWxjb21lIHRv",
"IG15IHdlYnNpdGUhPC9oMT48cD5IZWxsbyB0aGVyZSw8YnIvPm1heSB5b3Ugd2FudC",
"B0byByZWFkIHNvbWUgb2YgbXkgYXJ0aWNsZXM/PC9wPjxkaXYgY2xhc3M9ImFydGlj",
"bGUiPjxoMj5TdHVmZjwvaDI+PHA+RGVzY3JpcHRpb248L3A+PC9kaXY+PC9ib2R5Pj",
"wvaHRtbD4="
].join);
assert(page == target);
}
// README example
unittest {
import elemi : elem, Element;
auto document = Element.HTMLDoctype ~ elem!"html"(
elem!"head"(
elem!"title"("Hello, World!"),
Element.MobileViewport,
),
elem!"body"(
// All input is sanitized.
"<Welcome to my website!>"
),
);
}