forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom.d
4865 lines (4105 loc) · 120 KB
/
dom.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 is an html DOM implementation, started with cloning
what the browser offers in Javascript, but going well beyond
it in convenience.
If you can do it in Javascript, you can probably do it with
this module.
And much more.
Note: some of the documentation here writes html with added
spaces. That's because ddoc doesn't bother encoding html output,
and adding spaces is easier than using LT macros everywhere.
BTW: this file depends on arsd.characterencodings, so help it
correctly read files from the internet. You should be able to
get characterencodings.d from the same place you got this file.
*/
module arsd.dom;
// NOTE: do *NOT* override toString on Element subclasses. It won't work.
// Instead, override writeToAppender();
// FIXME: should I keep processing instructions like <?blah ?> and <!-- blah --> (comments too lol)? I *want* them stripped out of most my output, but I want to be able to parse and create them too.
// Stripping them is useful for reading php as html.... but adding them
// is good for building php.
// I need to maintain compatibility with the way it is now too.
import arsd.characterencodings;
import std.string;
import std.exception;
import std.uri;
import std.array;
import std.range;
//import std.stdio;
// tag soup works for most the crap I know now! If you have two bad closing tags back to back, it might erase one, but meh
// that's rarer than the flipped closing tags that hack fixes so I'm ok with it. (Odds are it should be erased anyway; it's
// most likely a typo so I say kill kill kill.
/// This might belong in another module, but it represents a file with a mime type and some data.
/// Document implements this interface with type = text/html (see Document.contentType for more info)
/// and data = document.toString, so you can return Documents anywhere web.d expects FileResources.
interface FileResource {
string contentType() const; /// the content-type of the file. e.g. "text/html; charset=utf-8" or "image/png"
immutable(ubyte)[] getData() const; /// the data
}
// this puts in operators and opDispatch to handle string indexes and properties, forwarding to get and set functions.
mixin template JavascriptStyleDispatch() {
string opDispatch(string name)(string v = null) if(name != "popFront") { // popFront will make this look like a range. Do not want.
if(v !is null)
return set(name, v);
return get(name);
}
string opIndex(string key) const {
return get(key);
}
string opIndexAssign(string value, string field) {
return set(field, value);
}
// FIXME: doesn't seem to work
string* opBinary(string op)(string key) if(op == "in") {
return key in fields;
}
}
/// A proxy object to do the Element class' dataset property. See Element.dataset for more info.
///
/// Do not create this object directly.
struct DataSet {
this(Element e) {
this._element = e;
}
private Element _element;
string set(string name, string value) {
_element.setAttribute("data-" ~ unCamelCase(name), value);
return value;
}
string get(string name) const {
return _element.getAttribute("data-" ~ unCamelCase(name));
}
mixin JavascriptStyleDispatch!();
}
/// for style, i want to be able to set it with a string like a plain attribute,
/// but also be able to do properties Javascript style.
struct ElementStyle {
this(Element parent) {
_element = parent;
}
Element _element;
@property ref inout(string) _attribute() inout {
auto s = "style" in _element.attributes;
if(s is null) {
auto e = cast() _element; // const_cast
e.attributes["style"] = ""; // we need something to reference
s = cast(inout) ("style" in e.attributes);
}
assert(s !is null);
return *s;
}
alias _attribute this; // this is meant to allow element.style = element.style ~ " string "; to still work.
string set(string name, string value) {
if(name.length == 0)
return value;
name = unCamelCase(name);
auto r = rules();
r[name] = value;
_attribute = "";
foreach(k, v; r) {
if(_attribute.length)
_attribute ~= " ";
_attribute ~= k ~ ": " ~ v ~ ";";
}
_element.setAttribute("style", _attribute); // this is to trigger the observer call
return value;
}
string get(string name) const {
name = unCamelCase(name);
auto r = rules();
if(name in r)
return r[name];
return null;
}
string[string] rules() const {
string[string] ret;
foreach(rule; _attribute().split(";")) {
rule = rule.strip();
if(rule.length == 0)
continue;
auto idx = rule.indexOf(":");
if(idx == -1)
ret[rule] = "";
else {
auto name = rule[0 .. idx].strip;
auto value = rule[idx + 1 .. $].strip;
ret[name] = value;
}
}
return ret;
}
mixin JavascriptStyleDispatch!();
}
///.
enum NodeType { Text = 3 }
/// You can use this to do an easy null check or a dynamic cast+null check on any element.
T require(T = Element, string file = __FILE__, int line = __LINE__)(Element e) if(is(T : Element))
in {}
out(ret) { assert(ret !is null); }
body {
auto ret = cast(T) e;
if(ret is null)
throw new ElementNotFoundException(T.stringof, "passed value", file, line);
return ret;
}
/// This represents almost everything in the DOM.
class Element {
// this is a thing so i can remove observer support if it gets slow
// I have not implemented all these yet
private void sendObserverEvent(DomMutationOperations operation, string s1 = null, string s2 = null, Element r = null, Element r2 = null) {
if(parentDocument is null) return;
DomMutationEvent me;
me.operation = operation;
me.target = this;
me.relatedString = s1;
me.relatedString2 = s2;
me.related = r;
me.related2 = r2;
parentDocument.dispatchMutationEvent(me);
}
// putting all the members up front
// this ought to be private. don't use it directly.
Element[] children;
/// The name of the tag. Remember, changing this doesn't change the dynamic type of the object.
string tagName;
/// This is where the attributes are actually stored. You should use getAttribute, setAttribute, and hasAttribute instead.
string[string] attributes;
/// In XML, it is valid to write <tag /> for all elements with no children, but that breaks HTML, so I don't do it here.
/// Instead, this flag tells if it should be. It is based on the source document's notation and a html element list.
private bool selfClosed;
/// Get the parent Document object that contains this element.
/// It may be null, so remember to check for that.
Document parentDocument;
///.
Element parentNode;
// the next few methods are for implementing interactive kind of things
private CssStyle _computedStyle;
// these are here for event handlers. Don't forget that this library never fires events.
// (I'm thinking about putting this in a version statement so you don't have the baggage. The instance size of this class is 56 bytes right now.)
EventHandler[][string] bubblingEventHandlers;
EventHandler[][string] capturingEventHandlers;
EventHandler[string] defaultEventHandlers;
void addEventListener(string event, EventHandler handler, bool useCapture = false) {
if(event.length > 2 && event[0..2] == "on")
event = event[2 .. $];
if(useCapture)
capturingEventHandlers[event] ~= handler;
else
bubblingEventHandlers[event] ~= handler;
}
// and now methods
/// Convenience function to try to do the right thing for HTML. This is the main
/// way I create elements.
static Element make(string tagName, string childInfo = null, string childInfo2 = null) {
bool selfClosed = tagName.isInArray(selfClosedElements);
Element e;
// want to create the right kind of object for the given tag...
switch(tagName) {
case "table":
e = new Table(null);
break;
case "a":
e = new Link(null);
break;
case "form":
e = new Form(null);
break;
case "tr":
e = new TableRow(null);
break;
case "td", "th":
e = new TableCell(null, tagName);
break;
default:
e = new Element(null, tagName, null, selfClosed); // parent document should be set elsewhere
}
// make sure all the stuff is constructed properly FIXME: should probably be in all the right constructors too
e.tagName = tagName;
e.selfClosed = selfClosed;
if(childInfo !is null)
switch(tagName) {
/* html5 convenience tags */
case "audio":
if(childInfo.length)
e.addChild("source", childInfo);
if(childInfo2 !is null)
e.appendText(childInfo2);
break;
case "source":
e.src = childInfo;
if(childInfo2 !is null)
e.type = childInfo2;
break;
/* regular html 4 stuff */
case "img":
e.src = childInfo;
if(childInfo2 !is null)
e.alt = childInfo2;
break;
case "link":
e.href = childInfo;
if(childInfo2 !is null)
e.rel = childInfo2;
break;
case "option":
e.innerText = childInfo;
if(childInfo2 !is null)
e.value = childInfo2;
break;
case "input":
e.type = "hidden";
e.name = childInfo;
if(childInfo2 !is null)
e.value = childInfo2;
break;
case "a":
e.innerText = childInfo;
if(childInfo2 !is null)
e.href = childInfo2;
break;
case "script":
case "style":
e.innerRawSource = childInfo;
break;
case "meta":
e.name = childInfo;
if(childInfo2 !is null)
e.content = childInfo2;
break;
/* generically, assume we were passed text and perhaps class */
default:
e.innerText = childInfo;
if(childInfo2.length)
e.className = childInfo2;
}
return e;
}
/// Generally, you don't want to call this yourself - use Element.make or document.createElement instead.
this(Document _parentDocument, string _tagName, string[string] _attributes = null, bool _selfClosed = false) {
parentDocument = _parentDocument;
tagName = _tagName;
if(_attributes !is null)
attributes = _attributes;
selfClosed = _selfClosed;
version(dom_node_indexes)
this.dataset.nodeIndex = to!string(&(this.attributes));
}
/// Convenience constructor when you don't care about the parentDocument. Note this might break things on the document.
/// Note also that without a parent document, elements are always in strict, case-sensitive mode.
this(string _tagName, string[string] _attributes = null) {
tagName = _tagName;
if(_attributes !is null)
attributes = _attributes;
selfClosed = tagName.isInArray(selfClosedElements);
// this is meant to reserve some memory. It makes a small, but consistent improvement.
//children.length = 8;
//children.length = 0;
version(dom_node_indexes)
this.dataset.nodeIndex = to!string(&(this.attributes));
}
private this(Document _parentDocument) {
parentDocument = _parentDocument;
version(dom_node_indexes)
this.dataset.nodeIndex = to!string(&(this.attributes));
}
/* *******************************
Navigating the DOM
*********************************/
/// Returns the first child of this element. If it has no children, returns null.
/// Remember, text nodes are children too.
@property Element firstChild() {
return children.length ? children[0] : null;
}
///
@property Element lastChild() {
return children.length ? children[$ - 1] : null;
}
///.
@property Element previousSibling(string tagName = null) {
if(this.parentNode is null)
return null;
Element ps = null;
foreach(e; this.parentNode.childNodes) {
if(e is this)
break;
if(tagName == "*" && e.nodeType != NodeType.Text) {
ps = e;
break;
}
if(tagName is null || e.tagName == tagName)
ps = e;
}
return ps;
}
///.
@property Element nextSibling(string tagName = null) {
if(this.parentNode is null)
return null;
Element ns = null;
bool mightBe = false;
foreach(e; this.parentNode.childNodes) {
if(e is this) {
mightBe = true;
continue;
}
if(mightBe) {
if(tagName == "*" && e.nodeType != NodeType.Text) {
ns = e;
break;
}
if(tagName is null || e.tagName == tagName) {
ns = e;
break;
}
}
}
return ns;
}
/// Gets the nearest node, going up the chain, with the given tagName
/// May return null or throw.
T getParent(T = Element)(string tagName = null) if(is(T : Element)) {
if(tagName is null) {
static if(is(T == Form))
tagName = "form";
else static if(is(T == Table))
tagName = "table";
else static if(is(T == Table))
tagName == "a";
}
auto par = this.parentNode;
while(par !is null) {
if(tagName is null || par.tagName == tagName)
break;
par = par.parentNode;
}
static if(!is(T == Element)) {
auto t = cast(T) par;
if(t is null)
throw new ElementNotFoundException("", tagName ~ " parent not found");
} else
auto t = par;
return t;
}
///.
Element getElementById(string id) {
// FIXME: I use this function a lot, and it's kinda slow
// not terribly slow, but not great.
foreach(e; tree)
if(e.id == id)
return e;
return null;
}
///.
final SomeElementType requireElementById(SomeElementType = Element, string file = __FILE__, int line = __LINE__)(string id)
if(
is(SomeElementType : Element)
)
out(ret) {
assert(ret !is null);
}
body {
auto e = cast(SomeElementType) getElementById(id);
if(e is null)
throw new ElementNotFoundException(SomeElementType.stringof, "id=" ~ id, file, line);
return e;
}
///.
final SomeElementType requireSelector(SomeElementType = Element, string file = __FILE__, int line = __LINE__)(string selector)
if(
is(SomeElementType : Element)
)
out(ret) {
assert(ret !is null);
}
body {
auto e = cast(SomeElementType) querySelector(selector);
if(e is null)
throw new ElementNotFoundException(SomeElementType.stringof, selector, file, line);
return e;
}
/// Note: you can give multiple selectors, separated by commas.
/// It will return the first match it finds.
Element querySelector(string selector) {
// FIXME: inefficient; it gets all results just to discard most of them
auto list = getElementsBySelector(selector);
if(list.length == 0)
return null;
return list[0];
}
/// a more standards-compliant alias for getElementsBySelector
Element[] querySelectorAll(string selector) {
return getElementsBySelector(selector);
}
/**
Does a CSS selector
* -- all, default if nothing else is there
tag#id.class.class.class:pseudo[attrib=what][attrib=what] OP selector
It is all additive
OP
space = descendant
> = direct descendant
+ = sibling (E+F Matches any F element immediately preceded by a sibling element E)
[foo] Foo is present as an attribute
[foo="warning"] Matches any E element whose "foo" attribute value is exactly equal to "warning".
E[foo~="warning"] Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning"
E[lang|="en"] Matches any E element whose "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en".
[item$=sdas] ends with
[item^-sdsad] begins with
Quotes are optional here.
Pseudos:
:first-child
:last-child
:link (same as a[href] for our purposes here)
There can be commas separating the selector. A comma separated list result is OR'd onto the main.
This ONLY cares about elements. text, etc, are ignored
There should be two functions: given element, does it match the selector? and given a selector, give me all the elements
*/
Element[] getElementsBySelector(string selector) {
// FIXME: this function could probably use some performance attention
// ... but only mildly so according to the profiler in the big scheme of things; probably negligible in a big app.
bool caseSensitiveTags = true;
if(parentDocument && parentDocument.loose)
caseSensitiveTags = false;
Element[] ret;
foreach(sel; parseSelectorString(selector, caseSensitiveTags))
ret ~= sel.getElements(this);
return ret;
}
/// .
Element[] getElementsByClassName(string cn) {
// is this correct?
return getElementsBySelector("." ~ cn);
}
///.
Element[] getElementsByTagName(string tag) {
if(parentDocument && parentDocument.loose)
tag = tag.toLower();
Element[] ret;
foreach(e; tree)
if(e.tagName == tag)
ret ~= e;
return ret;
}
/* *******************************
Attributes
*********************************/
/**
Gets the given attribute value, or null if the
attribute is not set.
Note that the returned string is decoded, so it no longer contains any xml entities.
*/
string getAttribute(string name) const {
if(parentDocument && parentDocument.loose)
name = name.toLower();
auto e = name in attributes;
if(e)
return *e;
else
return null;
}
/**
Sets an attribute. Returns this for easy chaining
*/
Element setAttribute(string name, string value) {
if(parentDocument && parentDocument.loose)
name = name.toLower();
// I never use this shit legitimately and neither should you
auto it = name.toLower;
if(it == "href" || it == "src") {
auto v = value.strip.toLower();
if(v.startsWith("vbscript:"))
value = value[9..$];
if(v.startsWith("javascript:"))
value = value[11..$];
}
attributes[name] = value;
sendObserverEvent(DomMutationOperations.setAttribute, name, value);
return this;
}
/**
Returns if the attribute exists.
*/
bool hasAttribute(string name) {
if(parentDocument && parentDocument.loose)
name = name.toLower();
if(name in attributes)
return true;
else
return false;
}
/**
Removes the given attribute from the element.
*/
Element removeAttribute(string name)
out(ret) {
assert(ret is this);
}
body {
if(parentDocument && parentDocument.loose)
name = name.toLower();
if(name in attributes)
attributes.remove(name);
sendObserverEvent(DomMutationOperations.removeAttribute, name);
return this;
}
/**
Gets the class attribute's contents. Returns
an empty string if it has no class.
*/
string className() const {
auto c = getAttribute("class");
if(c is null)
return "";
return c;
}
///.
Element className(string c) {
setAttribute("class", c);
return this;
}
/**
Provides easy access to attributes, object style.
auto element = Element.make("a");
a.href = "cool.html"; // this is the same as a.setAttribute("href", "cool.html");
string where = a.href; // same as a.getAttribute("href");
*/
// name != "popFront" is so duck typing doesn't think it's a range
@property string opDispatch(string name)(string v = null) if(name != "popFront") {
if(v !is null)
setAttribute(name, v);
return getAttribute(name);
}
/**
Returns the element's children.
*/
@property const(Element[]) childNodes() const {
return children;
}
/// Mutable version of the same
@property Element[] childNodes() { // FIXME: the above should be inout
return children;
}
/// get all the classes on this element
@property string[] classes() {
return split(className, " ");
}
/// Adds a string to the class attribute. The class attribute is used a lot in CSS.
Element addClass(string c) {
if(hasClass(c))
return this; // don't add it twice
string cn = getAttribute("class");
if(cn.length == 0) {
setAttribute("class", c);
return this;
} else {
setAttribute("class", cn ~ " " ~ c);
}
return this;
}
/// Removes a particular class name.
Element removeClass(string c) {
if(!hasClass(c))
return this;
string n;
foreach(name; classes) {
if(c == name)
continue; // cut it out
if(n.length)
n ~= " ";
n ~= name;
}
className = n.strip;
return this;
}
/// Returns whether the given class appears in this element.
bool hasClass(string c) {
auto cn = className;
auto idx = cn.indexOf(c);
if(idx == -1)
return false;
foreach(cla; cn.split(" "))
if(cla == c)
return true;
return false;
/*
int rightSide = idx + c.length;
bool checkRight() {
if(rightSide == cn.length)
return true; // it's the only class
else if(iswhite(cn[rightSide]))
return true;
return false; // this is a substring of something else..
}
if(idx == 0) {
return checkRight();
} else {
if(!iswhite(cn[idx - 1]))
return false; // substring
return checkRight();
}
assert(0);
*/
}
/// HTML5's dataset property. It is an alternate view into attributes with the data- prefix.
///
/// Given: <a data-my-property="cool" />
///
/// We get: assert(a.dataset.myProperty == "cool");
DataSet dataset() {
return DataSet(this);
}
/// Provides both string and object style (like in Javascript) access to the style attribute.
@property ElementStyle style() {
return ElementStyle(this);
}
/// This sets the style attribute with a string.
@property ElementStyle style(string s) {
this.setAttribute("style", s);
return this.style();
}
private void parseAttributes(string[] whichOnes = null) {
/+
if(whichOnes is null)
whichOnes = attributes.keys;
foreach(attr; whichOnes) {
switch(attr) {
case "id":
break;
case "class":
break;
case "style":
break;
default:
// we don't care about it
}
}
+/
}
// if you change something here, it won't apply... FIXME const? but changing it would be nice if it applies to the style attribute too though you should use style there.
///.
@property CssStyle computedStyle() {
if(_computedStyle is null) {
auto style = this.getAttribute("style");
/* we'll treat shitty old html attributes as css here */
if(this.hasAttribute("width"))
style ~= "; width: " ~ this.width;
if(this.hasAttribute("height"))
style ~= "; width: " ~ this.height;
if(this.hasAttribute("bgcolor"))
style ~= "; background-color: " ~ this.bgcolor;
if(this.tagName == "body" && this.hasAttribute("text"))
style ~= "; color: " ~ this.text;
if(this.hasAttribute("color"))
style ~= "; color: " ~ this.color;
/* done */
_computedStyle = new CssStyle(null, style); // gives at least something to work with
}
return _computedStyle;
}
/// These properties are useless in most cases, but if you write a layout engine on top of this lib, they may be good
version(browser) {
void* expansionHook; ///ditto
int offsetWidth; ///ditto
int offsetHeight; ///ditto
int offsetLeft; ///ditto
int offsetTop; ///ditto
Element offsetParent; ///ditto
bool hasLayout; ///ditto
int zIndex; ///ditto
///ditto
int absoluteLeft() {
int a = offsetLeft;
auto p = offsetParent;
while(p) {
a += p.offsetLeft;
p = p.offsetParent;
}
return a;
}
///ditto
int absoluteTop() {
int a = offsetTop;
auto p = offsetParent;
while(p) {
a += p.offsetTop;
p = p.offsetParent;
}
return a;
}
}
// Back to the regular dom functions
public:
/* *******************************
DOM Mutation
*********************************/
/// Removes all inner content from the tag; all child text and elements are gone.
void removeAllChildren()
out {
assert(this.children.length == 0);
}
body {
children = null;
}
/// convenience function to quickly add a tag with some text or
/// other relevant info (for example, it's a src for an <img> element
/// instead of inner text)
Element addChild(string tagName, string childInfo = null, string childInfo2 = null)
in {
assert(tagName !is null);
}
out(e) {
assert(e.parentNode is this);
assert(e.parentDocument is this.parentDocument);
}
body {
auto e = Element.make(tagName, childInfo, childInfo2);
// FIXME (maybe): if the thing is self closed, we might want to go ahead and
// return the parent. That will break existing code though.
return appendChild(e);
}
/// Another convenience function. Adds a child directly after the current one, returning
/// the new child.
///
/// Between this, addChild, and parentNode, you can build a tree as a single expression.
Element addSibling(string tagName, string childInfo = null, string childInfo2 = null)
in {
assert(tagName !is null);
assert(parentNode !is null);
}
out(e) {
assert(e.parentNode is this.parentNode);
assert(e.parentDocument is this.parentDocument);
}
body {
auto e = Element.make(tagName, childInfo, childInfo2);
return parentNode.insertAfter(this, e);
}
/// Convenience function to append text intermixed with other children.
/// For example: div.addChildren("You can visit my website by ", new Link("mysite.com", "clicking here"), ".");
/// or div.addChildren("Hello, ", user.name, "!");
/// See also: appendHtml. This might be a bit simpler though because you don't have to think about escaping.
void addChildren(T...)(T t) {
foreach(item; t) {
static if(is(item : Element))
appendChild(item);
else static if (is(isSomeString!(item)))
appendText(to!string(item));
else static assert(0, "Cannot pass " ~ typeof(item).stringof ~ " to addChildren");
}
}
///.
Element addChild(string tagName, Element firstChild)
in {
assert(firstChild !is null);
}
out(ret) {
assert(ret !is null);
assert(ret.parentNode is this);
assert(firstChild.parentNode is ret);
assert(ret.parentDocument is this.parentDocument);
//assert(firstChild.parentDocument is this.parentDocument);
}
body {
auto e = Element.make(tagName);
e.appendChild(firstChild);
this.appendChild(e);
return e;
}
Element addChild(string tagName, Html innerHtml)
in {
}
out(ret) {
assert(ret !is null);
assert(ret.parentNode is this);
assert(ret.parentDocument is this.parentDocument);
}
body {
auto e = Element.make(tagName);
this.appendChild(e);
e.innerHTML = innerHtml.source;
return e;
}
/// Appends the given element to this one. The given element must not have a parent already.
Element appendChild(Element e)
in {
assert(e !is null);