File size: 2,246 Bytes
20dbb3c | 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 | 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;
}
function isMathDomNode(node: VirtualNode): node is MathDomNode {
return 'toText' in node;
}
/**
* 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 extends VirtualNode>
implements HtmlDomNode, MathDomNode {
children: ReadonlyArray<ChildType>;
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 this.classes.includes(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 {
return this.children.map((child: ChildType): string => {
if (isMathDomNode(child)) {
return child.toText();
}
throw new Error(
`Expected MathDomNode with toText, got ${child.constructor.name}`);
}).join("");
}
}
|