-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplementation.js
7847 lines (6777 loc) · 262 KB
/
implementation.js
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
"use strict";
var htmlNamespace = "http://www.w3.org/1999/xhtml";
var cssStylingFlag = false;
// This is bad :(
var globalRange = null;
// Commands are stored in a dictionary where we call their actions and such
var commands = {};
///////////////////////////////////////////////////////////////////////////////
////////////////////////////// Utility functions //////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//@{
function nextNode(node) {
if (node.hasChildNodes()) {
return node.firstChild;
}
return nextNodeDescendants(node);
}
function previousNode(node) {
if (node.previousSibling) {
node = node.previousSibling;
while (node.hasChildNodes()) {
node = node.lastChild;
}
return node;
}
if (node.parentNode
&& node.parentNode.nodeType == Node.ELEMENT_NODE) {
return node.parentNode;
}
return null;
}
function nextNodeDescendants(node) {
while (node && !node.nextSibling) {
node = node.parentNode;
}
if (!node) {
return null;
}
return node.nextSibling;
}
/**
* Returns true if ancestor is an ancestor of descendant, false otherwise.
*/
function isAncestor(ancestor, descendant) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
/**
* Returns true if ancestor is an ancestor of or equal to descendant, false
* otherwise.
*/
function isAncestorContainer(ancestor, descendant) {
return (ancestor || descendant)
&& (ancestor == descendant || isAncestor(ancestor, descendant));
}
/**
* Returns true if descendant is a descendant of ancestor, false otherwise.
*/
function isDescendant(descendant, ancestor) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
/**
* Returns true if node1 is before node2 in tree order, false otherwise.
*/
function isBefore(node1, node2) {
return Boolean(node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_FOLLOWING);
}
/**
* Returns true if node1 is after node2 in tree order, false otherwise.
*/
function isAfter(node1, node2) {
return Boolean(node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_PRECEDING);
}
function getAncestors(node) {
var ancestors = [];
while (node.parentNode) {
ancestors.unshift(node.parentNode);
node = node.parentNode;
}
return ancestors;
}
function getDescendants(node) {
var descendants = [];
var stop = nextNodeDescendants(node);
while ((node = nextNode(node))
&& node != stop) {
descendants.push(node);
}
return descendants;
}
function convertProperty(property) {
// Special-case for now
var map = {
"fontFamily": "font-family",
"fontSize": "font-size",
"fontStyle": "font-style",
"fontWeight": "font-weight",
"textDecoration": "text-decoration",
};
if (typeof map[property] != "undefined") {
return map[property];
}
return property;
}
// Return the <font size=X> value for the given CSS size, or undefined if there
// is none.
function cssSizeToLegacy(cssVal) {
return {
"xx-small": 1,
"small": 2,
"medium": 3,
"large": 4,
"x-large": 5,
"xx-large": 6,
"xxx-large": 7
}[cssVal];
}
// Return the CSS size given a legacy size.
function legacySizeToCss(legacyVal) {
return {
1: "xx-small",
2: "small",
3: "medium",
4: "large",
5: "x-large",
6: "xx-large",
7: "xxx-large",
}[legacyVal];
}
// Opera 11 puts HTML elements in the null namespace, it seems.
function isHtmlNamespace(ns) {
return ns === null
|| ns === htmlNamespace;
}
// "the directionality" from HTML. I don't bother caring about non-HTML
// elements.
//
// "The directionality of an element is either 'ltr' or 'rtl', and is
// determined as per the first appropriate set of steps from the following
// list:"
function getDirectionality(element) {
// "If the element's dir attribute is in the ltr state
// The directionality of the element is 'ltr'."
if (element.dir == "ltr") {
return "ltr";
}
// "If the element's dir attribute is in the rtl state
// The directionality of the element is 'rtl'."
if (element.dir == "rtl") {
return "rtl";
}
// "If the element's dir attribute is in the auto state
// "If the element is a bdi element and the dir attribute is not in a
// defined state (i.e. it is not present or has an invalid value)
// [lots of complicated stuff]
//
// Skip this, since no browser implements it anyway.
// "If the element is a root element and the dir attribute is not in a
// defined state (i.e. it is not present or has an invalid value)
// The directionality of the element is 'ltr'."
if (!isHtmlElement(element.parentNode)) {
return "ltr";
}
// "If the element has a parent element and the dir attribute is not in a
// defined state (i.e. it is not present or has an invalid value)
// The directionality of the element is the same as the element's
// parent element's directionality."
return getDirectionality(element.parentNode);
}
//@}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////// DOM Range functions /////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//@{
function getNodeIndex(node) {
var ret = 0;
while (node.previousSibling) {
ret++;
node = node.previousSibling;
}
return ret;
}
// "The length of a Node node is the following, depending on node:
//
// ProcessingInstruction
// DocumentType
// Always 0.
// Text
// Comment
// node's length.
// Any other node
// node's childNodes's length."
function getNodeLength(node) {
switch (node.nodeType) {
case Node.PROCESSING_INSTRUCTION_NODE:
case Node.DOCUMENT_TYPE_NODE:
return 0;
case Node.TEXT_NODE:
case Node.COMMENT_NODE:
return node.length;
default:
return node.childNodes.length;
}
}
/**
* The position of two boundary points relative to one another, as defined by
* DOM Range.
*/
function getPosition(nodeA, offsetA, nodeB, offsetB) {
// "If node A is the same as node B, return equal if offset A equals offset
// B, before if offset A is less than offset B, and after if offset A is
// greater than offset B."
if (nodeA == nodeB) {
if (offsetA == offsetB) {
return "equal";
}
if (offsetA < offsetB) {
return "before";
}
if (offsetA > offsetB) {
return "after";
}
}
// "If node A is after node B in tree order, compute the position of (node
// B, offset B) relative to (node A, offset A). If it is before, return
// after. If it is after, return before."
if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_FOLLOWING) {
var pos = getPosition(nodeB, offsetB, nodeA, offsetA);
if (pos == "before") {
return "after";
}
if (pos == "after") {
return "before";
}
}
// "If node A is an ancestor of node B:"
if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_CONTAINS) {
// "Let child equal node B."
var child = nodeB;
// "While child is not a child of node A, set child to its parent."
while (child.parentNode != nodeA) {
child = child.parentNode;
}
// "If the index of child is less than offset A, return after."
if (getNodeIndex(child) < offsetA) {
return "after";
}
}
// "Return before."
return "before";
}
/**
* Returns the furthest ancestor of a Node as defined by DOM Range.
*/
function getFurthestAncestor(node) {
var root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
}
/**
* "contained" as defined by DOM Range: "A Node node is contained in a range
* range if node's furthest ancestor is the same as range's root, and (node, 0)
* is after range's start, and (node, length of node) is before range's end."
*/
function isContained(node, range) {
var pos1 = getPosition(node, 0, range.startContainer, range.startOffset);
var pos2 = getPosition(node, getNodeLength(node), range.endContainer, range.endOffset);
return getFurthestAncestor(node) == getFurthestAncestor(range.startContainer)
&& pos1 == "after"
&& pos2 == "before";
}
/**
* Return all nodes contained in range that the provided function returns true
* for, omitting any with an ancestor already being returned.
*/
function getContainedNodes(range, condition) {
if (typeof condition == "undefined") {
condition = function() { return true };
}
var node = range.startContainer;
if (node.hasChildNodes()
&& range.startOffset < node.childNodes.length) {
// A child is contained
node = node.childNodes[range.startOffset];
} else if (range.startOffset == getNodeLength(node)) {
// No descendant can be contained
node = nextNodeDescendants(node);
} else {
// No children; this node at least can't be contained
node = nextNode(node);
}
var stop = range.endContainer;
if (stop.hasChildNodes()
&& range.endOffset < stop.childNodes.length) {
// The node after the last contained node is a child
stop = stop.childNodes[range.endOffset];
} else {
// This node and/or some of its children might be contained
stop = nextNodeDescendants(stop);
}
var nodeList = [];
while (isBefore(node, stop)) {
if (isContained(node, range)
&& condition(node)) {
nodeList.push(node);
node = nextNodeDescendants(node);
continue;
}
node = nextNode(node);
}
return nodeList;
}
/**
* As above, but includes nodes with an ancestor that's already been returned.
*/
function getAllContainedNodes(range, condition) {
if (typeof condition == "undefined") {
condition = function() { return true };
}
var node = range.startContainer;
if (node.hasChildNodes()
&& range.startOffset < node.childNodes.length) {
// A child is contained
node = node.childNodes[range.startOffset];
} else if (range.startOffset == getNodeLength(node)) {
// No descendant can be contained
node = nextNodeDescendants(node);
} else {
// No children; this node at least can't be contained
node = nextNode(node);
}
var stop = range.endContainer;
if (stop.hasChildNodes()
&& range.endOffset < stop.childNodes.length) {
// The node after the last contained node is a child
stop = stop.childNodes[range.endOffset];
} else {
// This node and/or some of its children might be contained
stop = nextNodeDescendants(stop);
}
var nodeList = [];
while (isBefore(node, stop)) {
if (isContained(node, range)
&& condition(node)) {
nodeList.push(node);
}
node = nextNode(node);
}
return nodeList;
}
// Returns either null, or something of the form rgb(x, y, z), or something of
// the form rgb(x, y, z, w) with w != 0.
function normalizeColor(color) {
if (color.toLowerCase() == "currentcolor") {
return null;
}
var outerSpan = document.createElement("span");
document.body.appendChild(outerSpan);
outerSpan.style.color = "black";
var innerSpan = document.createElement("span");
outerSpan.appendChild(innerSpan);
innerSpan.style.color = color;
color = getComputedStyle(innerSpan).color;
if (color == "rgb(0, 0, 0)") {
// Maybe it's really black, maybe it's invalid.
outerSpan.color = "white";
color = getComputedStyle(innerSpan).color;
if (color != "rgb(0, 0, 0)") {
return null;
}
}
document.body.removeChild(outerSpan);
// I rely on the fact that browsers generally provide consistent syntax for
// getComputedStyle(), although it's not standardized. There are only two
// exceptions I found:
if (/^rgba\([0-9]+, [0-9]+, [0-9]+, 1\)$/.test(color)) {
// IE10PP2 seems to do this sometimes.
return color.replace("rgba", "rgb").replace(", 1)", ")");
}
if (color == "transparent") {
// IE10PP2, Firefox 7.0a2, and Opera 11.50 all return "transparent" if
// the specified value is "transparent".
return "rgba(0, 0, 0, 0)";
}
return color;
}
// Returns either null, or something of the form #xxxxxx, or the color itself
// if it's a valid keyword.
function parseSimpleColor(color) {
color = color.toLowerCase();
if (["aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan",
"darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki",
"darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred",
"darksalmon", "darkseagreen", "darkslateblue", "darkslategray",
"darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue",
"dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite",
"forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod",
"gray", "green", "greenyellow", "grey", "honeydew", "hotpink", "indianred",
"indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen",
"lemonchiffon", "lightblue", "lightcoral", "lightcyan",
"lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey",
"lightpink", "lightsalmon", "lightseagreen", "lightskyblue",
"lightslategray", "lightslategrey", "lightsteelblue", "lightyellow",
"lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine",
"mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen",
"mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange",
"orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise",
"palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum",
"powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver",
"skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen",
"steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet",
"wheat", "white", "whitesmoke", "yellow", "yellowgreen"].indexOf(color) != -1) {
return color;
}
color = normalizeColor(color);
var matches = /^rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)$/.exec(color);
if (matches) {
return "#"
+ parseInt(matches[1]).toString(16).replace(/^.$/, "0$&")
+ parseInt(matches[2]).toString(16).replace(/^.$/, "0$&")
+ parseInt(matches[3]).toString(16).replace(/^.$/, "0$&");
}
return null;
}
//@}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////// Edit command functions ///////////////////////////
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////
///// Methods of the HTMLDocument interface /////
/////////////////////////////////////////////////
//@{
var executionStackDepth = 0;
// Helper function for common behavior.
function editCommandMethod(command, prop, range, callback) {
// Set up our global range magic, but only if we're the outermost function
if (executionStackDepth == 0 && typeof range != "undefined") {
globalRange = range;
} else if (executionStackDepth == 0) {
globalRange = null;
globalRange = getActiveRange();
}
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// We can't throw a real one, but a string will do for our purposes.
if (!(command in commands)) {
throw "NOT_SUPPORTED_ERR";
}
// "If command has no action, raise an INVALID_ACCESS_ERR exception."
// "If command has no indeterminacy, raise an INVALID_ACCESS_ERR
// exception."
// "If command has no state, raise an INVALID_ACCESS_ERR exception."
// "If command has no value, raise an INVALID_ACCESS_ERR exception."
if (prop != "enabled"
&& !(prop in commands[command])) {
throw "INVALID_ACCESS_ERR";
}
executionStackDepth++;
try {
var ret = callback();
} catch(e) {
executionStackDepth--;
throw e;
}
executionStackDepth--;
return ret;
}
function myExecCommand(command, showUi, value, range) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
// "If only one argument was provided, let show UI be false."
//
// If range was passed, I can't actually detect how many args were passed
// . . .
if (arguments.length == 1
|| (arguments.length >=4 && typeof showUi == "undefined")) {
showUi = false;
}
// "If only one or two arguments were provided, let value be the empty
// string."
if (arguments.length <= 2
|| (arguments.length >=4 && typeof value == "undefined")) {
value = "";
}
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// "If command has no action, raise an INVALID_ACCESS_ERR exception."
return editCommandMethod(command, "action", range, (function(command, showUi, value) { return function() {
// "If command is not enabled, return false."
if (!myQueryCommandEnabled(command)) {
return false;
}
// "Take the action for command, passing value to the instructions as an
// argument."
commands[command].action(value);
// "Return true."
return true;
}})(command, showUi, value));
}
function myQueryCommandEnabled(command, range) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
return editCommandMethod(command, "action", range, (function(command) { return function() {
// "Among commands defined in this specification, those listed in
// Miscellaneous commands are always enabled. The other commands defined
// here are enabled if the active range is not null, and disabled
// otherwise."
return ["copy", "cut", "paste", "selectall", "stylewithcss", "usecss"].indexOf(command) != -1
|| getActiveRange() !== null;
}})(command));
}
function myQueryCommandIndeterm(command, range) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// "If command has no indeterminacy, raise an INVALID_ACCESS_ERR
// exception."
return editCommandMethod(command, "indeterm", range, (function(command) { return function() {
// "If command is not enabled, return false."
if (!myQueryCommandEnabled(command)) {
return false;
}
// "Return true if command is indeterminate, otherwise false."
return commands[command].indeterm();
}})(command));
}
function myQueryCommandState(command, range) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// "If command has no state, raise an INVALID_ACCESS_ERR exception."
return editCommandMethod(command, "state", range, (function(command) { return function() {
// "If command is not enabled, return false."
if (!myQueryCommandEnabled(command)) {
return false;
}
// "If the state override for command is set, return it."
if (typeof getStateOverride(command) != "undefined") {
return getStateOverride(command);
}
// "Return true if command's state is true, otherwise false."
return commands[command].state();
}})(command));
}
// "When the queryCommandSupported(command) method on the HTMLDocument
// interface is invoked, the user agent must return true if command is
// supported, and false otherwise."
function myQueryCommandSupported(command) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
return command in commands;
}
function myQueryCommandValue(command, range) {
// "All of these methods must treat their command argument ASCII
// case-insensitively."
command = command.toLowerCase();
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// "If command has no value, raise an INVALID_ACCESS_ERR exception."
return editCommandMethod(command, "value", range, function() {
// "If command is not enabled, return the empty string."
if (!myQueryCommandEnabled(command)) {
return "";
}
// "If command is "fontSize" and its value override is set, convert the
// value override to an integer number of pixels and return the legacy
// font size for the result."
if (command == "fontsize"
&& getValueOverride("fontsize") !== undefined) {
return getLegacyFontSize(getValueOverride("fontsize"));
}
// "If the value override for command is set, return it."
if (typeof getValueOverride(command) != "undefined") {
return getValueOverride(command);
}
// "Return command's value."
return commands[command].value();
});
}
//@}
//////////////////////////////
///// Common definitions /////
//////////////////////////////
//@{
// "An HTML element is an Element whose namespace is the HTML namespace."
//
// I allow an extra argument to more easily check whether something is a
// particular HTML element, like isHtmlElement(node, "OL"). It accepts arrays
// too, like isHtmlElement(node, ["OL", "UL"]) to check if it's an ol or ul.
function isHtmlElement(node, tags) {
if (typeof tags == "string") {
tags = [tags];
}
if (typeof tags == "object") {
tags = tags.map(function(tag) { return tag.toUpperCase() });
}
return node
&& node.nodeType == Node.ELEMENT_NODE
&& isHtmlNamespace(node.namespaceURI)
&& (typeof tags == "undefined" || tags.indexOf(node.tagName) != -1);
}
// "A prohibited paragraph child name is "address", "article", "aside",
// "blockquote", "caption", "center", "col", "colgroup", "dd", "details",
// "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer",
// "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li",
// "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section",
// "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", or
// "xmp"."
var prohibitedParagraphChildNames = ["address", "article", "aside",
"blockquote", "caption", "center", "col", "colgroup", "dd", "details",
"dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li",
"listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section",
"summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul",
"xmp"];
// "A prohibited paragraph child is an HTML element whose local name is a
// prohibited paragraph child name."
function isProhibitedParagraphChild(node) {
return isHtmlElement(node, prohibitedParagraphChildNames);
}
// "A block node is either an Element whose "display" property does not have
// resolved value "inline" or "inline-block" or "inline-table" or "none", or a
// Document, or a DocumentFragment."
function isBlockNode(node) {
return node
&& ((node.nodeType == Node.ELEMENT_NODE && ["inline", "inline-block", "inline-table", "none"].indexOf(getComputedStyle(node).display) == -1)
|| node.nodeType == Node.DOCUMENT_NODE
|| node.nodeType == Node.DOCUMENT_FRAGMENT_NODE);
}
// "An inline node is a node that is not a block node."
function isInlineNode(node) {
return node && !isBlockNode(node);
}
// "An editing host is a node that is either an Element with a contenteditable
// attribute set to the true state, or the Element child of a Document whose
// designMode is enabled."
function isEditingHost(node) {
return node
&& node.nodeType == Node.ELEMENT_NODE
&& (node.contentEditable == "true"
|| (node.parentNode
&& node.parentNode.nodeType == Node.DOCUMENT_NODE
&& node.parentNode.designMode == "on"));
}
// "Something is editable if it is a node which is not an editing host, does
// not have a contenteditable attribute set to the false state, and whose
// parent is an editing host or editable."
function isEditable(node) {
// This is slightly a lie, because we're excluding non-HTML elements with
// contentEditable attributes.
return node
&& !isEditingHost(node)
&& (node.nodeType != Node.ELEMENT_NODE || node.contentEditable != "false")
&& (isEditingHost(node.parentNode) || isEditable(node.parentNode));
}
// Helper function, not defined in the spec
function hasEditableDescendants(node) {
for (var i = 0; i < node.childNodes.length; i++) {
if (isEditable(node.childNodes[i])
|| hasEditableDescendants(node.childNodes[i])) {
return true;
}
}
return false;
}
// "The editing host of node is null if node is neither editable nor an editing
// host; node itself, if node is an editing host; or the nearest ancestor of
// node that is an editing host, if node is editable."
function getEditingHostOf(node) {
if (isEditingHost(node)) {
return node;
} else if (isEditable(node)) {
var ancestor = node.parentNode;
while (!isEditingHost(ancestor)) {
ancestor = ancestor.parentNode;
}
return ancestor;
} else {
return null;
}
}
// "Two nodes are in the same editing host if the editing host of the first is
// non-null and the same as the editing host of the second."
function inSameEditingHost(node1, node2) {
return getEditingHostOf(node1)
&& getEditingHostOf(node1) == getEditingHostOf(node2);
}
// "A collapsed line break is a br that begins a line box which has nothing
// else in it, and therefore has zero height."
function isCollapsedLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
// Add a zwsp after it and see if that changes the height of the nearest
// non-inline parent. Note: this is not actually reliable, because the
// parent might have a fixed height or something.
var ref = br.parentNode;
while (getComputedStyle(ref).display == "inline") {
ref = ref.parentNode;
}
var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null;
ref.style.height = "auto";
ref.style.maxHeight = "none";
ref.style.minHeight = "0";
var space = document.createTextNode("\u200b");
var origHeight = ref.offsetHeight;
if (origHeight == 0) {
throw "isCollapsedLineBreak: original height is zero, bug?";
}
br.parentNode.insertBefore(space, br.nextSibling);
var finalHeight = ref.offsetHeight;
space.parentNode.removeChild(space);
if (refStyle === null) {
// Without the setAttribute() line, removeAttribute() doesn't work in
// Chrome 14 dev. I have no idea why.
ref.setAttribute("style", "");
ref.removeAttribute("style");
} else {
ref.setAttribute("style", refStyle);
}
// Allow some leeway in case the zwsp didn't create a whole new line, but
// only made an existing line slightly higher. Firefox 6.0a2 shows this
// behavior when the first line is bold.
return origHeight < finalHeight - 5;
}
// "An extraneous line break is a br that has no visual effect, in that
// removing it from the DOM would not change layout, except that a br that is
// the sole child of an li is not extraneous."
//
// FIXME: This doesn't work in IE, since IE ignores display: none in
// contenteditable.
function isExtraneousLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
if (isHtmlElement(br.parentNode, "li")
&& br.parentNode.childNodes.length == 1) {
return false;
}
// Make the line break disappear and see if that changes the block's
// height. Yes, this is an absurd hack. We have to reset height etc. on
// the reference node because otherwise its height won't change if it's not
// auto.
var ref = br.parentNode;
while (getComputedStyle(ref).display == "inline") {
ref = ref.parentNode;
}
var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null;
ref.style.height = "auto";
ref.style.maxHeight = "none";
ref.style.minHeight = "0";
var brStyle = br.hasAttribute("style") ? br.getAttribute("style") : null;
var origHeight = ref.offsetHeight;
if (origHeight == 0) {
throw "isExtraneousLineBreak: original height is zero, bug?";
}
br.setAttribute("style", "display:none");
var finalHeight = ref.offsetHeight;
if (refStyle === null) {
// Without the setAttribute() line, removeAttribute() doesn't work in
// Chrome 14 dev. I have no idea why.
ref.setAttribute("style", "");
ref.removeAttribute("style");
} else {
ref.setAttribute("style", refStyle);
}
if (brStyle === null) {
br.removeAttribute("style");
} else {
br.setAttribute("style", brStyle);
}
return origHeight == finalHeight;
}
// "A whitespace node is either a Text node whose data is the empty string; or
// a Text node whose data consists only of one or more tabs (0x0009), line
// feeds (0x000A), carriage returns (0x000D), and/or spaces (0x0020), and whose
// parent is an Element whose resolved value for "white-space" is "normal" or
// "nowrap"; or a Text node whose data consists only of one or more tabs
// (0x0009), carriage returns (0x000D), and/or spaces (0x0020), and whose
// parent is an Element whose resolved value for "white-space" is "pre-line"."
function isWhitespaceNode(node) {
return node
&& node.nodeType == Node.TEXT_NODE
&& (node.data == ""
|| (
/^[\t\n\r ]+$/.test(node.data)
&& node.parentNode
&& node.parentNode.nodeType == Node.ELEMENT_NODE
&& ["normal", "nowrap"].indexOf(getComputedStyle(node.parentNode).whiteSpace) != -1
) || (
/^[\t\r ]+$/.test(node.data)
&& node.parentNode
&& node.parentNode.nodeType == Node.ELEMENT_NODE
&& getComputedStyle(node.parentNode).whiteSpace == "pre-line"
));
}
// "node is a collapsed whitespace node if the following algorithm returns
// true:"
function isCollapsedWhitespaceNode(node) {
// "If node is not a whitespace node, return false."
if (!isWhitespaceNode(node)) {
return false;
}
// "If node's data is the empty string, return true."
if (node.data == "") {
return true;
}
// "Let ancestor be node's parent."
var ancestor = node.parentNode;
// "If ancestor is null, return true."
if (!ancestor) {
return true;
}
// "If the "display" property of some ancestor of node has resolved value
// "none", return true."
if (getAncestors(node).some(function(ancestor) {
return ancestor.nodeType == Node.ELEMENT_NODE
&& getComputedStyle(ancestor).display == "none";
})) {
return true;
}
// "While ancestor is not a block node and its parent is not null, set
// ancestor to its parent."
while (!isBlockNode(ancestor)
&& ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
// "Let reference be node."
var reference = node;
// "While reference is a descendant of ancestor:"
while (reference != ancestor) {
// "Let reference be the node before it in tree order."
reference = previousNode(reference);
// "If reference is a block node or a br, return true."
if (isBlockNode(reference)
|| isHtmlElement(reference, "br")) {
return true;
}
// "If reference is a Text node that is not a whitespace node, or is an
// img, break from this loop."
if ((reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference))
|| isHtmlElement(reference, "img")) {
break;
}
}
// "Let reference be node."
reference = node;
// "While reference is a descendant of ancestor:"
var stop = nextNodeDescendants(ancestor);
while (reference != stop) {
// "Let reference be the node after it in tree order, or null if there
// is no such node."
reference = nextNode(reference);
// "If reference is a block node or a br, return true."
if (isBlockNode(reference)
|| isHtmlElement(reference, "br")) {
return true;
}
// "If reference is a Text node that is not a whitespace node, or is an
// img, break from this loop."
if ((reference && reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference))
|| isHtmlElement(reference, "img")) {
break;
}