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
// @flow
import utils from "./utils";
import type {CssStyle, HtmlDomNode} from "./domTree";
import type {MathDomNode} from "./mathMLTree";
// To ensure that all nodes have compatible signatures for these methods.
export interface VirtualNode {
toNode(): Node;
toMarkup(): string;
}
/**
* This node represents a document fragment, which contains elements, but when
* placed into the DOM doesn't have any representation itself. It only contains
* children and doesn't have any DOM node properties.
*/
export class DocumentFragment<ChildType: VirtualNode>
implements HtmlDomNode, MathDomNode {
children: $ReadOnlyArray<ChildType>;
// HtmlDomNode
classes: string[];
height: number;
depth: number;
maxFontSize: number;
style: CssStyle; // Never used; needed for satisfying interface.
constructor(children: $ReadOnlyArray<ChildType>) {
this.children = children;
this.classes = [];
this.height = 0;
this.depth = 0;
this.maxFontSize = 0;
this.style = {};
}
hasClass(className: string): boolean {
return utils.contains(this.classes, className);
}
/** Convert the fragment into a node. */
toNode(): Node {
const frag = document.createDocumentFragment();
for (let i = 0; i < this.children.length; i++) {
frag.appendChild(this.children[i].toNode());
}
return frag;
}
/** Convert the fragment into HTML markup. */
toMarkup(): string {
let markup = "";
// Simply concatenate the markup for the children together.
for (let i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
return markup;
}
/**
* Converts the math node into a string, similar to innerText. Applies to
* MathDomNode's only.
*/
toText(): string {
// To avoid this, we would subclass documentFragment separately for
// MathML, but polyfills for subclassing is expensive per PR 1469.
// $FlowFixMe: Only works for ChildType = MathDomNode.
const toText = (child: ChildType): string => child.toText();
return this.children.map(toText).join("");
}
}