-
Notifications
You must be signed in to change notification settings - Fork 128
/
html.d
2279 lines (1840 loc) · 56 KB
/
html.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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
This module includes functions to work with HTML and CSS in a more specialized manner than [arsd.dom]. Most of this is obsolete from my really old D web stuff, but there's still some useful stuff. View source before you decide to use it, as the implementations may suck more than you want to use.
It publically imports the DOM module to get started.
Then it adds a number of functions to enhance html
DOM documents and make other changes, like scripts
and stylesheets.
*/
module arsd.html;
import arsd.core : encodeUriComponent;
public import arsd.dom;
import arsd.color;
import std.array;
import std.string;
import std.variant;
import core.vararg;
import std.exception;
/// This is a list of features you can allow when using the sanitizedHtml function.
enum HtmlFeatures : uint {
images = 1, /// The <img> tag
links = 2, /// <a href=""> tags
css = 4, /// Inline CSS
cssLinkedResources = 8, // FIXME: implement this
video = 16, /// The html5 <video> tag. autoplay is always stripped out.
audio = 32, /// The html5 <audio> tag. autoplay is always stripped out.
objects = 64, /// The <object> tag, which can link to many things, including Flash.
iframes = 128, /// The <iframe> tag. sandbox and restrict attributes are always added.
classes = 256, /// The class="" attribute
forms = 512, /// HTML forms
}
/// The things to allow in links, images, css, and aother urls.
/// FIXME: implement this for better flexibility
enum UriFeatures : uint {
http, /// http:// protocol absolute links
https, /// https:// protocol absolute links
data, /// data: url links to embed content. On some browsers (old Firefoxes) this was a security concern.
ftp, /// ftp:// protocol links
relative, /// relative links to the current location. You might want to rebase them.
anchors /// #anchor links
}
string[] htmlTagWhitelist = [
"span", "div",
"p", "br",
"b", "i", "u", "s", "big", "small", "sub", "sup", "strong", "em", "tt", "blockquote", "cite", "ins", "del", "strike",
"ol", "ul", "li", "dl", "dt", "dd",
"q",
"table", "caption", "tr", "td", "th", "col", "thead", "tbody", "tfoot",
"hr",
"h1", "h2", "h3", "h4", "h5", "h6",
"abbr",
"img", "object", "audio", "video", "a", "source", // note that these usually *are* stripped out - see HtmlFeatures- but this lets them get into stage 2
"form", "input", "textarea", "legend", "fieldset", "label", // ditto, but with HtmlFeatures.forms
// style isn't here
];
string[] htmlAttributeWhitelist = [
// style isn't here
/*
if style, expression must be killed
all urls must be checked for javascript and/or vbscript
imports must be killed
*/
"style",
"colspan", "rowspan",
"title", "alt", "class",
"href", "src", "type", "name",
"id",
"method", "enctype", "value", "type", // for forms only FIXME
"align", "valign", "width", "height",
];
/// This returns an element wrapping sanitized content, using a whitelist for html tags and attributes,
/// and a blacklist for css. Javascript is never allowed.
///
/// It scans all URLs it allows and rejects
///
/// You can tweak the allowed features with the HtmlFeatures enum.
///
/// Note: you might want to use innerText for most user content. This is meant if you want to
/// give them a big section of rich text.
///
/// userContent should just be a basic div, holding the user's actual content.
///
/// FIXME: finish writing this
Element sanitizedHtml(/*in*/ Element userContent, string idPrefix = null, HtmlFeatures allow = HtmlFeatures.links | HtmlFeatures.images | HtmlFeatures.css) {
auto div = Element.make("div");
div.addClass("sanitized user-content");
auto content = div.appendChild(userContent.cloned);
startOver:
foreach(e; content.tree) {
if(e.nodeType == NodeType.Text)
continue; // text nodes are always fine.
e.tagName = e.tagName.toLower(); // normalize tag names...
if(!(e.tagName.isInArray(htmlTagWhitelist))) {
e.stripOut;
goto startOver;
}
if((!(allow & HtmlFeatures.links) && e.tagName == "a")) {
e.stripOut;
goto startOver;
}
if((!(allow & HtmlFeatures.video) && e.tagName == "video")
||(!(allow & HtmlFeatures.audio) && e.tagName == "audio")
||(!(allow & HtmlFeatures.objects) && e.tagName == "object")
||(!(allow & HtmlFeatures.iframes) && e.tagName == "iframe")
||(!(allow & HtmlFeatures.forms) && (
e.tagName == "form" ||
e.tagName == "input" ||
e.tagName == "textarea" ||
e.tagName == "label" ||
e.tagName == "fieldset" ||
e.tagName == "legend"
))
) {
e.innerText = e.innerText; // strips out non-text children
e.stripOut;
goto startOver;
}
if(e.tagName == "source" && (e.parentNode is null || e.parentNode.tagName != "video" || e.parentNode.tagName != "audio")) {
// source is only allowed in the HTML5 media elements
e.stripOut;
goto startOver;
}
if(!(allow & HtmlFeatures.images) && e.tagName == "img") {
e.replaceWith(new TextNode(null, e.alt));
continue; // images not allowed are replaced with their alt text
}
foreach(k, v; e.attributes) {
e.removeAttribute(k);
k = k.toLower();
if(!(k.isInArray(htmlAttributeWhitelist))) {
// not allowed, don't put it back
// this space is intentionally left blank
} else {
// it's allowed but let's make sure it's completely valid
if(k == "class" && (allow & HtmlFeatures.classes)) {
e.setAttribute("class", v);
} else if(k == "id") {
if(idPrefix !is null)
e.setAttribute(k, idPrefix ~ v);
// otherwise, don't allow user IDs
} else if(k == "style") {
if(allow & HtmlFeatures.css) {
e.setAttribute(k, sanitizeCss(v));
}
} else if(k == "href" || k == "src") {
e.setAttribute(k, sanitizeUrl(v));
} else
e.setAttribute(k, v); // allowed attribute
}
}
if(e.tagName == "iframe") {
// some additional restrictions for supported browsers
e.attrs.security = "restricted";
e.attrs.sandbox = "";
}
}
return div;
}
///
Element sanitizedHtml(in Html userContent, string idPrefix = null, HtmlFeatures allow = HtmlFeatures.links | HtmlFeatures.images | HtmlFeatures.css) {
auto div = Element.make("div");
div.innerHTML = userContent.source;
return sanitizedHtml(div, idPrefix, allow);
}
string sanitizeCss(string css) {
// FIXME: do a proper whitelist here; I should probably bring in the parser from html.d
// FIXME: sanitize urls inside too
return css.replace("expression", "");
}
///
string sanitizeUrl(string url) {
// FIXME: support other options; this is more restrictive than it has to be
if(url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//"))
return url;
return null;
}
/// This is some basic CSS I suggest you copy/paste into your stylesheet
/// if you use the sanitizedHtml function.
string recommendedBasicCssForUserContent = `
.sanitized.user-content {
position: relative;
overflow: hidden;
}
.sanitized.user-content * {
max-width: 100%;
max-height: 100%;
}
`;
/++
Given arbitrary user input, find links and add `<a href>` wrappers, otherwise just escaping the rest of it for HTML display.
+/
Html linkify(string text) {
auto div = Element.make("div");
while(text.length) {
auto idx = text.indexOf("http");
if(idx == -1) {
idx = text.length;
}
div.appendText(text[0 .. idx]);
text = text[idx .. $];
if(text.length) {
// where does it end? whitespace I guess
auto idxSpace = text.indexOf(" ");
if(idxSpace == -1) idxSpace = text.length;
auto idxLine = text.indexOf("\n");
if(idxLine == -1) idxLine = text.length;
auto idxEnd = idxSpace < idxLine ? idxSpace : idxLine;
auto link = text[0 .. idxEnd];
text = text[idxEnd .. $];
div.addChild("a", link, link);
}
}
return Html(div.innerHTML);
}
/// Given existing encoded HTML, turns \n\n into `<p>`.
Html paragraphsToP(Html html) {
auto text = html.source;
string total;
foreach(p; text.split("\n\n")) {
total ~= "<p>";
auto lines = p.splitLines;
foreach(idx, line; lines)
if(line.strip.length) {
total ~= line;
if(idx != lines.length - 1)
total ~= "<br />";
}
total ~= "</p>";
}
return Html(total);
}
/// Given user text, converts newlines to `<br>` and encodes the rest.
Html nl2br(string text) {
auto div = Element.make("div");
bool first = true;
foreach(line; splitLines(text)) {
if(!first)
div.addChild("br");
else
first = false;
div.appendText(line);
}
return Html(div.innerHTML);
}
/// Returns true of the string appears to be html/xml - if it matches the pattern
/// for tags or entities.
bool appearsToBeHtml(string src) {
import std.regex;
return cast(bool) match(src, `.*\<[A-Za-z]+>.*`);
}
/// Get the favicon out of a document, or return the default a browser would attempt if it isn't there.
string favicon(Document document) {
auto item = document.querySelector("link[rel~=icon]");
if(item !is null)
return item.href;
return "/favicon.ico"; // it pisses me off that the fucking browsers do this.... but they do, so I will too.
}
///
Element checkbox(string name, string value, string label, bool checked = false) {
auto lbl = Element.make("label");
auto input = lbl.addChild("input");
input.type = "checkbox";
input.name = name;
input.value = value;
if(checked)
input.checked = "checked";
lbl.appendText(" ");
lbl.addChild("span", label);
return lbl;
}
/++ Convenience function to create a small <form> to POST, but the creation function is more like a link
than a DOM form.
The idea is if you have a link to a page which needs to be changed since it is now taking an action,
this should provide an easy way to do it.
You might want to style these with css. The form these functions create has no class - use regular
dom functions to add one. When styling, hit the form itself and form > [type=submit]. (That will
cover both input[type=submit] and button[type=submit] - the two possibilities the functions may create.)
Param:
href: the link. Query params (if present) are converted into hidden form inputs and the rest is used as the form action
innerText: the text to show on the submit button
params: additional parameters for the form
+/
Form makePostLink(string href, string innerText, string[string] params = null) {
auto submit = Element.make("input");
submit.type = "submit";
submit.value = innerText;
return makePostLink_impl(href, params, submit);
}
/// Similar to the above, but lets you pass HTML rather than just text. It puts the html inside a <button type="submit"> element.
///
/// Using html strings imo generally sucks. I recommend you use plain text or structured Elements instead most the time.
Form makePostLink(string href, Html innerHtml, string[string] params = null) {
auto submit = Element.make("button");
submit.type = "submit";
submit.innerHTML = innerHtml;
return makePostLink_impl(href, params, submit);
}
/// Like the Html overload, this uses a <button> tag to get fancier with the submit button. The element you pass is appended to the submit button.
Form makePostLink(string href, Element submitButtonContents, string[string] params = null) {
auto submit = Element.make("button");
submit.type = "submit";
submit.appendChild(submitButtonContents);
return makePostLink_impl(href, params, submit);
}
import arsd.cgi;
import std.range;
Form makePostLink_impl(string href, string[string] params, Element submitButton) {
auto form = require!Form(Element.make("form"));
form.method = "POST";
auto idx = href.indexOf("?");
if(idx == -1) {
form.action = href;
} else {
form.action = href[0 .. idx];
foreach(k, arr; decodeVariables(href[idx + 1 .. $]))
form.addValueArray(k, arr);
}
foreach(k, v; params)
form.setValue(k, v);
form.appendChild(submitButton);
return form;
}
/++ Given an existing link, create a POST item from it.
You can use this to do something like:
auto e = document.requireSelector("a.should-be-post"); // get my link from the dom
e.replaceWith(makePostLink(e)); // replace the link with a nice POST form that otherwise does the same thing
It passes all attributes of the link on to the form, though I could be convinced to put some on the submit button instead.
++/
Form makePostLink(Element link) {
Form form;
if(link.childNodes.length == 1) {
auto fc = link.firstChild;
if(fc.nodeType == NodeType.Text)
form = makePostLink(link.href, fc.nodeValue);
else
form = makePostLink(link.href, fc);
} else {
form = makePostLink(link.href, Html(link.innerHTML));
}
assert(form !is null);
// auto submitButton = form.requireSelector("[type=submit]");
foreach(k, v; link.attributes) {
if(k == "href" || k == "action" || k == "method")
continue;
form.setAttribute(k, v); // carries on class, events, etc. to the form.
}
return form;
}
/// Translates validate="" tags to inline javascript. "this" is the thing
/// being checked.
void translateValidation(Document document) {
int count;
foreach(f; document.getElementsByTagName("form")) {
count++;
string formValidation = "";
string fid = f.getAttribute("id");
if(fid is null) {
fid = "automatic-form-" ~ to!string(count);
f.setAttribute("id", "automatic-form-" ~ to!string(count));
}
foreach(i; f.tree) {
if(i.tagName != "input" && i.tagName != "select")
continue;
if(i.getAttribute("id") is null)
i.id = "form-input-" ~ i.name;
auto validate = i.getAttribute("validate");
if(validate is null)
continue;
auto valmsg = i.getAttribute("validate-message");
if(valmsg !is null) {
i.removeAttribute("validate-message");
valmsg ~= `\n`;
}
string valThis = `
var currentField = elements['`~i.name~`'];
if(!(`~validate.replace("this", "currentField")~`)) {
currentField.style.backgroundColor = '#ffcccc';
if(typeof failedMessage != 'undefined')
failedMessage += '`~valmsg~`';
if(failed == null) {
failed = currentField;
}
if('`~valmsg~`' != '') {
var msgId = '`~i.name~`-valmsg';
var msgHolder = document.getElementById(msgId);
if(!msgHolder) {
msgHolder = document.createElement('div');
msgHolder.className = 'validation-message';
msgHolder.id = msgId;
msgHolder.innerHTML = '<br />';
msgHolder.appendChild(document.createTextNode('`~valmsg~`'));
var ele = currentField;
ele.parentNode.appendChild(msgHolder);
}
}
} else {
currentField.style.backgroundColor = '#ffffff';
var msgId = '`~i.name~`-valmsg';
var msgHolder = document.getElementById(msgId);
if(msgHolder)
msgHolder.innerHTML = '';
}`;
formValidation ~= valThis;
string oldOnBlur = i.getAttribute("onblur");
i.setAttribute("onblur", `
var form = document.getElementById('`~fid~`');
var failed = null;
with(form) { `~valThis~` }
` ~ oldOnBlur);
i.removeAttribute("validate");
}
if(formValidation != "") {
auto os = f.getAttribute("onsubmit");
f.attrs.onsubmit = `var failed = null; var failedMessage = ''; with(this) { ` ~ formValidation ~ '\n' ~ ` if(failed != null) { alert('Please complete all required fields.\n' + failedMessage); failed.focus(); return false; } `~os~` return true; }`;
}
}
}
/// makes input[type=date] to call displayDatePicker with a button
void translateDateInputs(Document document) {
foreach(e; document.getElementsByTagName("input")) {
auto type = e.getAttribute("type");
if(type is null) continue;
if(type == "date") {
auto name = e.getAttribute("name");
assert(name !is null);
auto button = document.createElement("button");
button.type = "button";
button.attrs.onclick = "displayDatePicker('"~name~"');";
button.innerText = "Choose...";
e.parentNode.insertChildAfter(button, e);
e.type = "text";
e.setAttribute("class", "date");
}
}
}
/// finds class="striped" and adds class="odd"/class="even" to the relevant
/// children
void translateStriping(Document document) {
foreach(item; document.querySelectorAll(".striped")) {
bool odd = false;
string selector;
switch(item.tagName) {
case "ul":
case "ol":
selector = "> li";
break;
case "table":
selector = "> tbody > tr";
break;
case "tbody":
selector = "> tr";
break;
default:
selector = "> *";
}
foreach(e; item.getElementsBySelector(selector)) {
if(odd)
e.addClass("odd");
else
e.addClass("even");
odd = !odd;
}
}
}
/// tries to make an input to filter a list. it kinda sucks.
void translateFiltering(Document document) {
foreach(e; document.querySelectorAll("input[filter_what]")) {
auto filterWhat = e.attrs.filter_what;
if(filterWhat[0] == '#')
filterWhat = filterWhat[1..$];
auto fw = document.getElementById(filterWhat);
assert(fw !is null);
foreach(a; fw.getElementsBySelector(e.attrs.filter_by)) {
a.addClass("filterable_content");
}
e.removeAttribute("filter_what");
e.removeAttribute("filter_by");
e.attrs.onkeydown = e.attrs.onkeyup = `
var value = this.value;
var a = document.getElementById("`~filterWhat~`");
var children = a.childNodes;
for(var b = 0; b < children.length; b++) {
var child = children[b];
if(child.nodeType != 1)
continue;
var spans = child.getElementsByTagName('span'); // FIXME
for(var i = 0; i < spans.length; i++) {
var span = spans[i];
if(hasClass(span, "filterable_content")) {
if(value.length && span.innerHTML.match(RegExp(value, "i"))) { // FIXME
addClass(child, "good-match");
removeClass(child, "bad-match");
//if(!got) {
// holder.scrollTop = child.offsetTop;
// got = true;
//}
} else {
removeClass(child, "good-match");
if(value.length)
addClass(child, "bad-match");
else
removeClass(child, "bad-match");
}
}
}
}
`;
}
}
enum TextWrapperWhitespaceBehavior {
wrap,
ignore,
stripOut
}
/// This wraps every non-empty text mode in the document body with
/// <t:t></t:t>, and sets an xmlns:t to the html root.
///
/// If you use it, be sure it's the last thing you do before
/// calling toString
///
/// Why would you want this? Because CSS sucks. If it had a
/// :text pseudoclass, we'd be right in business, but it doesn't
/// so we'll hack it with this custom tag.
///
/// It's in an xml namespace so it should affect or be affected by
/// your existing code, while maintaining excellent browser support.
///
/// To style it, use myelement > t\:t { style here } in your css.
///
/// Note: this can break the css adjacent sibling selector, first-child,
/// and other structural selectors. For example, if you write
/// <span>hello</span> <span>world</span>, normally, css span + span would
/// select "world". But, if you call wrapTextNodes, there's a <t:t> in the
/// middle.... so now it no longer matches.
///
/// Of course, it can also have an effect on your javascript, especially,
/// again, when working with siblings or firstChild, etc.
///
/// You must handle all this yourself, which may limit the usefulness of this
/// function.
///
/// The second parameter, whatToDoWithWhitespaceNodes, tries to mitigate
/// this somewhat by giving you some options about what to do with text
/// nodes that consist of nothing but whitespace.
///
/// You can: wrap them, like all other text nodes, you can ignore
/// them entirely, leaving them unwrapped, and in the document normally,
/// or you can use stripOut to remove them from the document.
///
/// Beware with stripOut: <span>you</span> <span>rock</span> -- that space
/// between the spans is a text node of nothing but whitespace, so it would
/// be stripped out - probably not what you want!
///
/// ignore is the default, since this should break the least of your
/// expectations with document structure, while still letting you use this
/// function.
void wrapTextNodes(Document document, TextWrapperWhitespaceBehavior whatToDoWithWhitespaceNodes = TextWrapperWhitespaceBehavior.ignore) {
enum ourNamespace = "t";
enum ourTag = ourNamespace ~ ":t";
document.root.setAttribute("xmlns:" ~ ourNamespace, null);
foreach(e; document.mainBody.tree) {
if(e.tagName == "script")
continue;
if(e.nodeType != NodeType.Text)
continue;
auto tn = cast(TextNode) e;
if(tn is null)
continue;
if(tn.contents.length == 0)
continue;
if(tn.parentNode !is null
&& tn.parentNode.tagName == ourTag)
{
// this is just a sanity check to make sure
// we don't double wrap anything
continue;
}
final switch(whatToDoWithWhitespaceNodes) {
case TextWrapperWhitespaceBehavior.wrap:
break; // treat it like all other text
case TextWrapperWhitespaceBehavior.stripOut:
// if it's actually whitespace...
if(tn.contents.strip().length == 0) {
tn.removeFromTree();
continue;
}
break;
case TextWrapperWhitespaceBehavior.ignore:
// if it's actually whitespace...
if(tn.contents.strip().length == 0)
continue;
}
tn.replaceWith(Element.make(ourTag, tn.contents));
}
}
void translateInputTitles(Document document) {
translateInputTitles(document.root);
}
/// find <input> elements with a title. Make the title the default internal content
void translateInputTitles(Element rootElement) {
foreach(form; rootElement.getElementsByTagName("form")) {
string os;
foreach(e; form.getElementsBySelector("input[type=text][title], input[type=email][title], textarea[title]")) {
if(e.hasClass("has-placeholder"))
continue;
e.addClass("has-placeholder");
e.attrs.onfocus = e.attrs.onfocus ~ `
removeClass(this, 'default');
if(this.value == this.getAttribute('title'))
this.value = '';
`;
e.attrs.onblur = e.attrs.onblur ~ `
if(this.value == '') {
addClass(this, 'default');
this.value = this.getAttribute('title');
}
`;
os ~= `
temporaryItem = this.elements["`~e.name~`"];
if(temporaryItem.value == temporaryItem.getAttribute('title'))
temporaryItem.value = '';
`;
if(e.tagName == "input") {
if(e.value == "") {
e.attrs.value = e.attrs.title;
e.addClass("default");
}
} else {
if(e.innerText.length == 0) {
e.innerText = e.attrs.title;
e.addClass("default");
}
}
}
form.attrs.onsubmit = os ~ form.attrs.onsubmit;
}
}
/// Adds some script to run onload
/// FIXME: not implemented
void addOnLoad(Document document) {
}
mixin template opDispatches(R) {
auto opDispatch(string fieldName)(...) {
if(_arguments.length == 0) {
// a zero argument function call OR a getter....
// we can't tell which for certain, so assume getter
// since they can always use the call method on the returned
// variable
static if(is(R == Variable)) {
auto v = *(new Variable(name ~ "." ~ fieldName, group));
} else {
auto v = *(new Variable(fieldName, vars));
}
return v;
} else {
// we have some kind of assignment, but no help from the
// compiler to get the type of assignment...
// FIXME: once Variant is able to handle this, use it!
static if(is(R == Variable)) {
auto v = *(new Variable(this.name ~ "." ~ name, group));
} else
auto v = *(new Variable(fieldName, vars));
string attempt(string type) {
return `if(_arguments[0] == typeid(`~type~`)) v = va_arg!(`~type~`)(_argptr);`;
}
mixin(attempt("int"));
mixin(attempt("string"));
mixin(attempt("double"));
mixin(attempt("Element"));
mixin(attempt("ClientSideScript.Variable"));
mixin(attempt("real"));
mixin(attempt("long"));
return v;
}
}
auto opDispatch(string fieldName, T...)(T t) if(T.length != 0) {
static if(is(R == Variable)) {
auto tmp = group.codes.pop;
scope(exit) group.codes.push(tmp);
return *(new Variable(callFunction(name ~ "." ~ fieldName, t).toString[1..$-2], group)); // cut off the ending ;\n
} else {
return *(new Variable(callFunction(fieldName, t).toString, vars));
}
}
}
/**
This wraps up a bunch of javascript magic. It doesn't
actually parse or run it - it just collects it for
attachment to a DOM document.
When it returns a variable, it returns it as a string
suitable for output into Javascript source.
auto js = new ClientSideScript;
js.myvariable = 10;
js.somefunction = ClientSideScript.Function(
js.block = {
js.alert("hello");
auto a = "asds";
js.alert(a, js.somevar);
};
Translates into javascript:
alert("hello");
alert("asds", somevar);
The passed code is evaluated lazily.
*/
/+
class ClientSideScript : Element {
private Stack!(string*) codes;
this(Document par) {
codes = new Stack!(string*);
vars = new VariablesGroup;
vars.codes = codes;
super(par, "script");
}
string name;
struct Source { string source; string toString() { return source; } }
void innerCode(void delegate() theCode) {
myCode = theCode;
}
override void innerRawSource(string s) {
myCode = null;
super.innerRawSource(s);
}
private void delegate() myCode;
override string toString() const {
auto HACK = cast(ClientSideScript) this;
if(HACK.myCode) {
string code;
HACK.codes.push(&code);
HACK.myCode();
HACK.codes.pop();
HACK.innerRawSource = "\n" ~ code;
}
return super.toString();
}
enum commitCode = ` if(!codes.empty) { auto magic = codes.peek; (*magic) ~= code; }`;
struct Variable {
string name;
VariablesGroup group;
// formats it for use in an inline event handler
string inline() {
return name.replace("\t", "");
}
this(string n, VariablesGroup g) {
name = n;
group = g;
}
Source set(T)(T t) {
string code = format("\t%s = %s;\n", name, toJavascript(t));
if(!group.codes.empty) {
auto magic = group.codes.peek;
(*magic) ~= code;
}
//Variant v = t;
//group.repository[name] = v;
return Source(code);
}
Variant _get() {
return (group.repository)[name];
}
Variable doAssignCode(string code) {
if(!group.codes.empty) {
auto magic = group.codes.peek;
(*magic) ~= "\t" ~ code ~ ";\n";
}
return * ( new Variable(code, group) );
}
Variable opSlice(size_t a, size_t b) {
return * ( new Variable(name ~ ".substring("~to!string(a) ~ ", " ~ to!string(b)~")", group) );
}
Variable opBinary(string op, T)(T rhs) {
return * ( new Variable(name ~ " " ~ op ~ " " ~ toJavascript(rhs), group) );
}
Variable opOpAssign(string op, T)(T rhs) {
return doAssignCode(name ~ " " ~ op ~ "= " ~ toJavascript(rhs));
}
Variable opIndex(T)(T i) {
return * ( new Variable(name ~ "[" ~ toJavascript(i) ~ "]" , group) );
}
Variable opIndexOpAssign(string op, T, R)(R rhs, T i) {
return doAssignCode(name ~ "[" ~ toJavascript(i) ~ "] " ~ op ~ "= " ~ toJavascript(rhs));
}
Variable opIndexAssign(T, R)(R rhs, T i) {
return doAssignCode(name ~ "[" ~ toJavascript(i) ~ "]" ~ " = " ~ toJavascript(rhs));
}
Variable opUnary(string op)() {
return * ( new Variable(op ~ name, group) );
}
void opAssign(T)(T rhs) {
set(rhs);
}
// used to call with zero arguments
Source call() {
string code = "\t" ~ name ~ "();\n";
if(!group.codes.empty) {
auto magic = group.codes.peek;
(*magic) ~= code;
}
return Source(code);
}
mixin opDispatches!(Variable);
// returns code to call a function
Source callFunction(T...)(string name, T t) {
string code = "\t" ~ name ~ "(";
bool outputted = false;
foreach(v; t) {
if(outputted)
code ~= ", ";
else
outputted = true;
code ~= toJavascript(v);
}
code ~= ");\n";
if(!group.codes.empty) {
auto magic = group.codes.peek;
(*magic) ~= code;
}
return Source(code);
}
}
// this exists only to allow easier access
class VariablesGroup {
/// If the variable is a function, we call it. If not, we return the source
@property Variable opDispatch(string name)() {
return * ( new Variable(name, this) );
}
Variant[string] repository;
Stack!(string*) codes;
}
VariablesGroup vars;
mixin opDispatches!(ClientSideScript);
// returns code to call a function
Source callFunction(T...)(string name, T t) {
string code = "\t" ~ name ~ "(";
bool outputted = false;