/
Range.ts
1080 lines (938 loc) · 32.2 KB
/
Range.ts
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
import INode from '../nodes/node/INode';
import IDocument from '../nodes/document/IDocument';
import IDocumentFragment from '../nodes/document-fragment/IDocumentFragment';
import DOMRect from '../nodes/element/DOMRect';
import RangeHowEnum from './RangeHowEnum';
import DOMException from '../exception/DOMException';
import DOMExceptionNameEnum from '../exception/DOMExceptionNameEnum';
import RangeUtility from './RangeUtility';
import NodeTypeEnum from '../nodes/node/NodeTypeEnum';
import NodeUtility from '../nodes/node/NodeUtility';
import XMLParser from '../xml-parser/XMLParser';
import IComment from '../nodes/comment/IComment';
import IText from '../nodes/text/IText';
import MutationListener from '../mutation-observer/MutationListener';
import Node from '../nodes/node/Node';
import DOMRectListFactory from '../nodes/element/DOMRectListFactory';
import IDOMRectList from '../nodes/element/IDOMRectList';
/**
* Range.
*
* Reference:
* https://developer.mozilla.org/en-US/docs/Web/API/Range.
*/
export default class Range {
public static _ownerDocument: IDocument = null;
public static readonly END_TO_END: number = RangeHowEnum.endToEnd;
public static readonly END_TO_START: number = RangeHowEnum.endToStart;
public static readonly START_TO_END: number = RangeHowEnum.startToEnd;
public static readonly START_TO_START: number = RangeHowEnum.startToStart;
public readonly END_TO_END: number = RangeHowEnum.endToEnd;
public readonly END_TO_START: number = RangeHowEnum.endToStart;
public readonly START_TO_END: number = RangeHowEnum.startToEnd;
public readonly START_TO_START: number = RangeHowEnum.startToStart;
public readonly startOffset: number = 0;
public readonly endOffset: number = 0;
public readonly startContainer: INode = null;
public readonly endContainer: INode = null;
public _startObserver: MutationListener = null;
public _endObserver: MutationListener = null;
public readonly _ownerDocument: IDocument = null;
/**
* Constructor.
*/
constructor() {
this._ownerDocument = (<typeof Range>this.constructor)._ownerDocument;
this._setStartContainer(this._ownerDocument, 0);
this._setEndContainer(this._ownerDocument, 0);
}
/**
* Returns a boolean value indicating whether the range's start and end points are at the same position.
*
* @see https://dom.spec.whatwg.org/#dom-range-collapsed
* @returns Collapsed.
*/
public get collapsed(): boolean {
return this.startContainer === this.endContainer && this.startOffset === this.endOffset;
}
/**
* Returns the deepest Node that contains the startContainer and endContainer nodes.
*
* @see https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer
* @returns Node.
*/
public get commonAncestorContainer(): INode {
let container = this.startContainer;
while (container) {
if (NodeUtility.isInclusiveAncestor(container, this.endContainer)) {
return container;
}
container = container.parentNode;
}
return null;
}
/**
* Returns -1, 0, or 1 depending on whether the referenceNode is before, the same as, or after the Range.
*
* @see https://dom.spec.whatwg.org/#dom-range-collapse
* @param toStart A boolean value: true collapses the Range to its start, false to its end. If omitted, it defaults to false.
*/
public collapse(toStart = false): void {
if (toStart) {
this._setEndContainer(this.startContainer, this.startOffset);
} else {
this._setStartContainer(this.endContainer, this.endOffset);
}
}
/**
* Compares the boundary points of the Range with those of another range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-compareboundarypoints
* @param how How.
* @param sourceRange Range.
* @returns A number, -1, 0, or 1, indicating whether the corresponding boundary-point of the Range is respectively before, equal to, or after the corresponding boundary-point of sourceRange.
*/
public compareBoundaryPoints(how: RangeHowEnum, sourceRange: Range): number {
if (
how !== RangeHowEnum.startToStart &&
how !== RangeHowEnum.startToEnd &&
how !== RangeHowEnum.endToEnd &&
how !== RangeHowEnum.endToStart
) {
throw new DOMException(
`The comparison method provided must be one of '${RangeHowEnum.startToStart}', '${RangeHowEnum.startToEnd}', '${RangeHowEnum.endToEnd}' or '${RangeHowEnum.endToStart}'.`,
DOMExceptionNameEnum.notSupportedError
);
}
if (this._ownerDocument !== sourceRange._ownerDocument) {
throw new DOMException(
`The two Ranges are not in the same tree.`,
DOMExceptionNameEnum.wrongDocumentError
);
}
const thisPoint: { node: INode; offset: number } = {
node: null,
offset: 0
};
const sourcePoint: { node: INode; offset: number } = {
node: null,
offset: 0
};
switch (how) {
case RangeHowEnum.startToStart:
thisPoint.node = this.startContainer;
thisPoint.offset = this.startOffset;
sourcePoint.node = sourceRange.startContainer;
sourcePoint.offset = sourceRange.startOffset;
break;
case RangeHowEnum.startToEnd:
thisPoint.node = this.endContainer;
thisPoint.offset = this.endOffset;
sourcePoint.node = sourceRange.startContainer;
sourcePoint.offset = sourceRange.startOffset;
break;
case RangeHowEnum.endToEnd:
thisPoint.node = this.endContainer;
thisPoint.offset = this.endOffset;
sourcePoint.node = sourceRange.endContainer;
sourcePoint.offset = sourceRange.endOffset;
break;
case RangeHowEnum.endToStart:
thisPoint.node = this.startContainer;
thisPoint.offset = this.startOffset;
sourcePoint.node = sourceRange.endContainer;
sourcePoint.offset = sourceRange.endOffset;
break;
}
return RangeUtility.compareBoundaryPointsPosition(thisPoint, sourcePoint);
}
/**
* Returns -1, 0, or 1 depending on whether the referenceNode is before, the same as, or after the Range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-comparepoint
* @param node Reference node.
* @param offset Offset.
* @returns -1,0, or 1.
*/
public comparePoint(node: INode, offset): number {
if (node.ownerDocument !== this._ownerDocument) {
throw new DOMException(
`The two Ranges are not in the same tree.`,
DOMExceptionNameEnum.wrongDocumentError
);
}
RangeUtility.validateBoundaryPoint({ node, offset });
const boundaryPoint = { node, offset };
if (
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.startContainer,
offset: this.startOffset
}) === -1
) {
return -1;
} else if (
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.endContainer,
offset: this.endOffset
}) === 1
) {
return 1;
}
return 0;
}
/**
* Returns a DocumentFragment copying the objects of type Node included in the Range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#concept-range-clone
* @returns Document fragment.
*/
public cloneContents(): IDocumentFragment {
const fragment = this._ownerDocument.createDocumentFragment();
if (this.collapsed) {
return fragment;
}
if (
this.startContainer === this.endContainer &&
(this.startContainer.nodeType === NodeTypeEnum.textNode ||
this.startContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.startContainer.nodeType === NodeTypeEnum.commentNode)
) {
const clone = (<IText | IComment>this.startContainer).cloneNode(false);
clone['_data'] = clone.substringData(this.startOffset, this.endOffset - this.startOffset);
fragment.appendChild(clone);
return fragment;
}
let commonAncestor = this.startContainer;
while (!NodeUtility.isInclusiveAncestor(commonAncestor, this.endContainer)) {
commonAncestor = commonAncestor.parentNode;
}
let firstPartialContainedChild = null;
if (!NodeUtility.isInclusiveAncestor(this.startContainer, this.endContainer)) {
let candidate = commonAncestor.firstChild;
while (!firstPartialContainedChild) {
if (RangeUtility.isPartiallyContained(candidate, this)) {
firstPartialContainedChild = candidate;
}
candidate = candidate.nextSibling;
}
}
let lastPartiallyContainedChild = null;
if (!NodeUtility.isInclusiveAncestor(this.endContainer, this.startContainer)) {
let candidate = commonAncestor.lastChild;
while (!lastPartiallyContainedChild) {
if (RangeUtility.isPartiallyContained(candidate, this)) {
lastPartiallyContainedChild = candidate;
}
candidate = candidate.previousSibling;
}
}
const containedChildren = [];
for (const node of commonAncestor.childNodes) {
if (RangeUtility.isContained(node, this)) {
if (node.nodeType === NodeTypeEnum.documentTypeNode) {
throw new DOMException(
'Invalid document type element.',
DOMExceptionNameEnum.hierarchyRequestError
);
}
containedChildren.push(node);
}
}
if (
firstPartialContainedChild !== null &&
(firstPartialContainedChild.nodeType === NodeTypeEnum.textNode ||
firstPartialContainedChild.nodeType === NodeTypeEnum.processingInstructionNode ||
firstPartialContainedChild.nodeType === NodeTypeEnum.commentNode)
) {
const clone = (<IText | IComment>this.startContainer).cloneNode(false);
clone['_data'] = clone.substringData(
this.startOffset,
NodeUtility.getNodeLength(this.startContainer) - this.startOffset
);
fragment.appendChild(clone);
} else if (firstPartialContainedChild !== null) {
const clone = firstPartialContainedChild.cloneNode();
fragment.appendChild(clone);
const subRange = new Range();
subRange._setStartContainer(this.startContainer, this.startOffset);
subRange._setEndContainer(
firstPartialContainedChild,
NodeUtility.getNodeLength(firstPartialContainedChild)
);
const subDocumentFragment = subRange.cloneContents();
clone.appendChild(subDocumentFragment);
}
for (const containedChild of containedChildren) {
const clone = containedChild.cloneNode(true);
fragment.appendChild(clone);
}
if (
lastPartiallyContainedChild !== null &&
(lastPartiallyContainedChild.nodeType === NodeTypeEnum.textNode ||
lastPartiallyContainedChild.nodeType === NodeTypeEnum.processingInstructionNode ||
lastPartiallyContainedChild.nodeType === NodeTypeEnum.commentNode)
) {
const clone = (<IText | IComment>this.endContainer).cloneNode(false);
clone['_data'] = clone.substringData(0, this.endOffset);
fragment.appendChild(clone);
} else if (lastPartiallyContainedChild !== null) {
const clone = lastPartiallyContainedChild.cloneNode(false);
fragment.appendChild(clone);
const subRange = new Range();
subRange._setStartContainer(lastPartiallyContainedChild, 0);
subRange._setEndContainer(this.endContainer, this.endOffset);
const subFragment = subRange.cloneContents();
clone.appendChild(subFragment);
}
return fragment;
}
/**
* Returns a Range object with boundary points identical to the cloned Range.
*
* @see https://dom.spec.whatwg.org/#dom-range-clonerange
* @returns Range.
*/
public cloneRange(): Range {
const clone = new Range();
clone._setStartContainer(this.startContainer, this.startOffset);
clone._setEndContainer(this.endContainer, this.endOffset);
return clone;
}
/**
* Returns a DocumentFragment by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead.
*
* @see https://w3c.github.io/DOM-Parsing/#dfn-fragment-parsing-algorithm
* @param tagString Tag string.
* @returns Document fragment.
*/
public createContextualFragment(tagString: string): IDocumentFragment {
// TODO: We only have support for HTML in the parser currently, so it is not necessary to check which context it is
return XMLParser.parse(this._ownerDocument, tagString);
}
/**
* Removes the contents of the Range from the Document.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-deletecontents
*/
public deleteContents(): void {
if (this.collapsed) {
return;
}
if (
this.startContainer === this.endContainer &&
(this.startContainer.nodeType === NodeTypeEnum.textNode ||
this.startContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.startContainer.nodeType === NodeTypeEnum.commentNode)
) {
(<IText | IComment>this.startContainer).replaceData(
this.startOffset,
this.endOffset - this.startOffset,
''
);
return;
}
const nodesToRemove = [];
let currentNode = this.startContainer;
const endNode = NodeUtility.nextDecendantNode(this.endContainer);
while (currentNode && currentNode !== endNode) {
if (
RangeUtility.isContained(currentNode, this) &&
!RangeUtility.isContained(currentNode.parentNode, this)
) {
nodesToRemove.push(currentNode);
}
currentNode = NodeUtility.following(currentNode);
}
let newNode;
let newOffset;
if (NodeUtility.isInclusiveAncestor(this.startContainer, this.endContainer)) {
newNode = this.startContainer;
newOffset = this.startOffset;
} else {
let referenceNode = this.startContainer;
while (
referenceNode &&
!NodeUtility.isInclusiveAncestor(referenceNode.parentNode, this.endContainer)
) {
referenceNode = referenceNode.parentNode;
}
newNode = referenceNode.parentNode;
newOffset = referenceNode.parentNode.childNodes.indexOf(referenceNode) + 1;
}
if (
this.startContainer.nodeType === NodeTypeEnum.textNode ||
this.startContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.startContainer.nodeType === NodeTypeEnum.commentNode
) {
(<IText | IComment>this.startContainer).replaceData(
this.startOffset,
NodeUtility.getNodeLength(this.startContainer) - this.startOffset,
''
);
}
for (const node of nodesToRemove) {
const parent = node.parentNode;
parent.removeChild(node);
}
if (
this.endContainer.nodeType === NodeTypeEnum.textNode ||
this.endContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.endContainer.nodeType === NodeTypeEnum.commentNode
) {
(<IText | IComment>this.endContainer).replaceData(0, this.endOffset, '');
}
this._setStartContainer(newNode, newOffset);
this._setEndContainer(newNode, newOffset);
}
/**
* Does nothing. It used to disable the Range object and enable the browser to release associated resources. The method has been kept for compatibility.
*
* @see https://dom.spec.whatwg.org/#dom-range-detach
*/
public detach(): void {
// Do nothing by spec
}
/**
* Moves contents of the Range from the document tree into a DocumentFragment.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-extractcontents
* @returns Document fragment.
*/
public extractContents(): IDocumentFragment {
const fragment = this._ownerDocument.createDocumentFragment();
if (this.collapsed) {
return fragment;
}
if (
this.startContainer === this.endContainer &&
(this.startContainer.nodeType === NodeTypeEnum.textNode ||
this.startContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.startContainer.nodeType === NodeTypeEnum.commentNode)
) {
const clone = <IText | IComment>this.startContainer.cloneNode(false);
clone['_data'] = clone.substringData(this.startOffset, this.endOffset - this.startOffset);
fragment.appendChild(clone);
(<IText | IComment>this.startContainer).replaceData(
this.startOffset,
this.endOffset - this.startOffset,
''
);
return fragment;
}
let commonAncestor = this.startContainer;
while (!NodeUtility.isInclusiveAncestor(commonAncestor, this.endContainer)) {
commonAncestor = commonAncestor.parentNode;
}
let firstPartialContainedChild = null;
if (!NodeUtility.isInclusiveAncestor(this.startContainer, this.endContainer)) {
let candidate = commonAncestor.firstChild;
while (!firstPartialContainedChild) {
if (RangeUtility.isPartiallyContained(candidate, this)) {
firstPartialContainedChild = candidate;
}
candidate = candidate.nextSibling;
}
}
let lastPartiallyContainedChild = null;
if (!NodeUtility.isInclusiveAncestor(this.endContainer, this.startContainer)) {
let candidate = commonAncestor.lastChild;
while (!lastPartiallyContainedChild) {
if (RangeUtility.isPartiallyContained(candidate, this)) {
lastPartiallyContainedChild = candidate;
}
candidate = candidate.previousSibling;
}
}
const containedChildren = [];
for (const node of commonAncestor.childNodes) {
if (RangeUtility.isContained(node, this)) {
if (node.nodeType === NodeTypeEnum.documentTypeNode) {
throw new DOMException(
'Invalid document type element.',
DOMExceptionNameEnum.hierarchyRequestError
);
}
containedChildren.push(node);
}
}
let newNode;
let newOffset;
if (NodeUtility.isInclusiveAncestor(this.startContainer, this.endContainer)) {
newNode = this.startContainer;
newOffset = this.startOffset;
} else {
let referenceNode = this.startContainer;
while (
referenceNode &&
!NodeUtility.isInclusiveAncestor(referenceNode.parentNode, this.endContainer)
) {
referenceNode = referenceNode.parentNode;
}
newNode = referenceNode.parentNode;
newOffset = referenceNode.parentNode.childNodes.indexOf(referenceNode) + 1;
}
if (
firstPartialContainedChild !== null &&
(firstPartialContainedChild.nodeType === NodeTypeEnum.textNode ||
firstPartialContainedChild.nodeType === NodeTypeEnum.processingInstructionNode ||
firstPartialContainedChild.nodeType === NodeTypeEnum.commentNode)
) {
const clone = <IText | IComment>this.startContainer.cloneNode(false);
clone['_data'] = clone.substringData(
this.startOffset,
NodeUtility.getNodeLength(this.startContainer) - this.startOffset
);
fragment.appendChild(clone);
(<IText | IComment>this.startContainer).replaceData(
this.startOffset,
NodeUtility.getNodeLength(this.startContainer) - this.startOffset,
''
);
} else if (firstPartialContainedChild !== null) {
const clone = firstPartialContainedChild.cloneNode(false);
fragment.appendChild(clone);
const subRange = new Range();
subRange._setStartContainer(this.startContainer, this.startOffset);
subRange._setEndContainer(
firstPartialContainedChild,
NodeUtility.getNodeLength(firstPartialContainedChild)
);
const subFragment = subRange.extractContents();
clone.appendChild(subFragment);
}
for (const containedChild of containedChildren) {
fragment.appendChild(containedChild);
}
if (
lastPartiallyContainedChild !== null &&
(lastPartiallyContainedChild.nodeType === NodeTypeEnum.textNode ||
lastPartiallyContainedChild.nodeType === NodeTypeEnum.processingInstructionNode ||
lastPartiallyContainedChild.nodeType === NodeTypeEnum.commentNode)
) {
const clone = <IText | IComment>this.endContainer.cloneNode(false);
clone['_data'] = clone.substringData(0, this.endOffset);
fragment.appendChild(clone);
(<IText | IComment>this.endContainer).replaceData(0, this.endOffset, '');
} else if (lastPartiallyContainedChild !== null) {
const clone = lastPartiallyContainedChild.cloneNode(false);
fragment.appendChild(clone);
const subRange = new Range();
subRange._setStartContainer(lastPartiallyContainedChild, 0);
subRange._setEndContainer(this.endContainer, this.endOffset);
const subFragment = subRange.extractContents();
clone.appendChild(subFragment);
}
this._setStartContainer(newNode, newOffset);
this._setEndContainer(newNode, newOffset);
return fragment;
}
/**
* Returns a DOMRect object that bounds the contents of the range; this is a rectangle enclosing the union of the bounding rectangles for all the elements in the range.
*
* @returns DOMRect object.
*/
public getBoundingClientRect(): DOMRect {
// TODO: Not full implementation
return new DOMRect();
}
/**
* The Range.getClientRects() method returns a list of DOMRect objects representing the area of the screen occupied by the range. This is created by aggregating the results of calls to Element.getClientRects() for all the elements in the range.
*
* @returns DOMRect objects.
*/
public getClientRects(): IDOMRectList<DOMRect> {
// TODO: Not full implementation
return DOMRectListFactory.create();
}
/**
* Returns a boolean indicating whether the given point is in the Range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-ispointinrange
* @param node Reference node.
* @param offset Offset.
* @returns "true" if in range.
*/
public isPointInRange(node: INode, offset = 0): boolean {
if (node.ownerDocument !== this._ownerDocument) {
return false;
}
const boundaryPoint = { node, offset };
RangeUtility.validateBoundaryPoint(boundaryPoint);
if (
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.startContainer,
offset: this.startOffset
}) === -1 ||
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.endContainer,
offset: this.endOffset
}) === 1
) {
return false;
}
return true;
}
/**
* Inserts a node at the start of the Range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#concept-range-insert
* @param newNode New node.
*/
public insertNode(newNode: INode): void {
if (
this.startContainer.nodeType === NodeTypeEnum.processingInstructionNode ||
this.startContainer.nodeType === NodeTypeEnum.commentNode ||
(this.startContainer.nodeType === NodeTypeEnum.textNode && !this.startContainer.parentNode) ||
newNode === this.startContainer
) {
throw new DOMException('Invalid start node.', DOMExceptionNameEnum.hierarchyRequestError);
}
let referenceNode =
this.startContainer.nodeType === NodeTypeEnum.textNode
? this.startContainer
: this.startContainer.childNodes[this.startOffset] || null;
const parent = !referenceNode ? this.startContainer : referenceNode.parentNode;
if (this.startContainer.nodeType === NodeTypeEnum.textNode) {
referenceNode = (<IText>this.startContainer).splitText(this.startOffset);
}
if (newNode === referenceNode) {
referenceNode = referenceNode.nextSibling;
}
const nodeParent = newNode.parentNode;
if (nodeParent) {
nodeParent.removeChild(newNode);
}
let newOffset = !referenceNode
? NodeUtility.getNodeLength(parent)
: referenceNode.parentNode.childNodes.indexOf(referenceNode);
newOffset +=
newNode.nodeType === NodeTypeEnum.documentFragmentNode
? NodeUtility.getNodeLength(newNode)
: 1;
parent.insertBefore(newNode, referenceNode);
if (this.collapsed) {
this._setEndContainer(parent, newOffset);
}
}
/**
* Returns a boolean indicating whether the given Node intersects the Range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-intersectsnode
* @param node Reference node.
* @returns "true" if it intersects.
*/
public intersectsNode(node: INode): boolean {
if (node.ownerDocument !== this._ownerDocument) {
return false;
}
const parent = node.parentNode;
if (!parent) {
return true;
}
const offset = parent.childNodes.indexOf(node);
return (
RangeUtility.compareBoundaryPointsPosition(
{ node: parent, offset },
{ node: this.endContainer, offset: this.endOffset }
) === -1 &&
RangeUtility.compareBoundaryPointsPosition(
{ node: parent, offset: offset + 1 },
{ node: this.startContainer, offset: this.startOffset }
) === 1
);
}
/**
* Sets the Range to contain the Node and its contents.
*
* @see https://dom.spec.whatwg.org/#concept-range-select
* @param node Reference node.
*/
public selectNode(node: INode): void {
if (!node.parentNode) {
throw new DOMException(
`The given Node has no parent.`,
DOMExceptionNameEnum.invalidNodeTypeError
);
}
const index = node.parentNode.childNodes.indexOf(node);
this._setStartContainer(node.parentNode, index);
this._setEndContainer(node.parentNode, index + 1);
}
/**
* Sets the Range to contain the contents of a Node.
*
* @see https://dom.spec.whatwg.org/#dom-range-selectnodecontents
* @param node Reference node.
*/
public selectNodeContents(node: INode): void {
if (node.nodeType === NodeTypeEnum.documentTypeNode) {
throw new DOMException(
"DocumentType Node can't be used as boundary point.",
DOMExceptionNameEnum.invalidNodeTypeError
);
}
this._setStartContainer(node, 0);
this._setEndContainer(node, NodeUtility.getNodeLength(node));
}
/**
* Sets the end position of a Range to be located at the given offset into the specified node x.
*
* @see https://dom.spec.whatwg.org/#dom-range-setend
* @param node End node.
* @param offset End offset.
*/
public setEnd(node: INode, offset = 0): void {
RangeUtility.validateBoundaryPoint({ node, offset });
const boundaryPoint = { node, offset };
if (
node.ownerDocument !== this._ownerDocument ||
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.startContainer,
offset: this.startOffset
}) === -1
) {
this._setStartContainer(node, offset);
}
this._setEndContainer(node, offset);
}
/**
* Sets the start position of a Range.
*
* @see https://dom.spec.whatwg.org/#dom-range-setstart
* @param node Start node.
* @param offset Start offset.
*/
public setStart(node: INode, offset = 0): void {
RangeUtility.validateBoundaryPoint({ node, offset });
const boundaryPoint = { node, offset };
if (
node.ownerDocument !== this._ownerDocument ||
RangeUtility.compareBoundaryPointsPosition(boundaryPoint, {
node: this.endContainer,
offset: this.endOffset
}) === 1
) {
this._setEndContainer(node, offset);
}
this._setStartContainer(node, offset);
}
/**
* Sets the end position of a Range relative to another Node.
*
* @see https://dom.spec.whatwg.org/#dom-range-setendafter
* @param node Reference node.
*/
public setEndAfter(node: INode): void {
if (!node.parentNode) {
throw new DOMException(
'The given Node has no parent.',
DOMExceptionNameEnum.invalidNodeTypeError
);
}
this.setEnd(node.parentNode, node.parentNode.childNodes.indexOf(node) + 1);
}
/**
* Sets the end position of a Range relative to another Node.
*
* @see https://dom.spec.whatwg.org/#dom-range-setendbefore
* @param node Reference node.
*/
public setEndBefore(node: INode): void {
if (!node.parentNode) {
throw new DOMException(
'The given Node has no parent.',
DOMExceptionNameEnum.invalidNodeTypeError
);
}
this.setEnd(node.parentNode, node.parentNode.childNodes.indexOf(node));
}
/**
* Sets the start position of a Range relative to a Node.
*
* @see https://dom.spec.whatwg.org/#dom-range-setstartafter
* @param node Reference node.
*/
public setStartAfter(node: INode): void {
if (!node.parentNode) {
throw new DOMException(
'The given Node has no parent.',
DOMExceptionNameEnum.invalidNodeTypeError
);
}
this.setStart(node.parentNode, node.parentNode.childNodes.indexOf(node) + 1);
}
/**
* Sets the start position of a Range relative to another Node.
*
* @see https://dom.spec.whatwg.org/#dom-range-setstartbefore
* @param node Reference node.
*/
public setStartBefore(node: INode): void {
if (!node.parentNode) {
throw new DOMException(
'The given Node has no parent.',
DOMExceptionNameEnum.invalidNodeTypeError
);
}
this.setStart(node.parentNode, node.parentNode.childNodes.indexOf(node));
}
/**
* Moves content of the Range into a new node, placing the new node at the start of the specified range.
*
* Based on logic from:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/Range-impl.js
*
* @see https://dom.spec.whatwg.org/#dom-range-surroundcontents
* @param newParent New parent.
*/
public surroundContents(newParent: INode): void {
let node = this.commonAncestorContainer;
const endNode = NodeUtility.nextDecendantNode(node);
while (node !== endNode) {
if (
node.nodeType !== NodeTypeEnum.textNode &&
RangeUtility.isPartiallyContained(node, this)
) {
throw new DOMException(
'The Range has partially contains a non-Text node.',
DOMExceptionNameEnum.invalidStateError
);
}
node = NodeUtility.following(node);
}
if (
newParent.nodeType === NodeTypeEnum.documentNode ||
newParent.nodeType === NodeTypeEnum.documentTypeNode ||
newParent.nodeType === NodeTypeEnum.documentFragmentNode
) {
throw new DOMException('Invalid element type.', DOMExceptionNameEnum.invalidNodeTypeError);
}
const fragment = this.extractContents();
while (newParent.firstChild) {
newParent.removeChild(newParent.firstChild);
}
this.insertNode(newParent);
newParent.appendChild(fragment);
this.selectNode(newParent);
}
/**
* Returns the text of the Range.
*
* @see https://dom.spec.whatwg.org/#dom-range-stringifier
*/
public toString(): string {
let string = '';
if (
this.startContainer === this.endContainer &&
this.startContainer.nodeType === NodeTypeEnum.textNode
) {
return (<IText>this.startContainer).data.slice(this.startOffset, this.endOffset);
}
if (this.startContainer.nodeType === NodeTypeEnum.textNode) {
string += (<IText>this.startContainer).data.slice(this.startOffset);
}
const endNode = NodeUtility.nextDecendantNode(this.endContainer);
let currentNode = this.startContainer;
while (currentNode && currentNode !== endNode) {
if (
currentNode.nodeType === NodeTypeEnum.textNode &&
RangeUtility.isContained(currentNode, this)
) {
string += (<IText>currentNode).data;
}
currentNode = NodeUtility.following(currentNode);