/
imported-xml-component.ts
89 lines (79 loc) · 2.85 KB
/
imported-xml-component.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
import { Element as XmlElement, xml2js } from "xml-js";
import { IXmlableObject, XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { IContext } from "./base";
/**
* Converts the given xml element (in json format) into XmlComponent.
*
* @param element the xml element in json presentation
*/
export const convertToXmlComponent = (element: XmlElement): ImportedXmlComponent | string | undefined => {
switch (element.type) {
case undefined:
case "element":
// eslint-disable-next-line no-case-declarations
const xmlComponent = new ImportedXmlComponent(element.name as string, element.attributes);
// eslint-disable-next-line no-case-declarations
const childElements = element.elements || [];
for (const childElm of childElements) {
const child = convertToXmlComponent(childElm);
if (child !== undefined) {
// eslint-disable-next-line functional/immutable-data
xmlComponent.push(child);
}
}
return xmlComponent;
case "text":
return element.text as string;
default:
return undefined;
/* c8 ignore next 2 */
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
class ImportedXmlComponentAttributes extends XmlAttributeComponent<any> {
// noop
}
/**
* Represents imported xml component from xml file.
*/
export class ImportedXmlComponent extends XmlComponent {
/**
* Converts the xml string to a XmlComponent tree.
*
* @param importedContent xml content of the imported component
*/
public static fromXmlString(importedContent: string): ImportedXmlComponent {
const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement;
return convertToXmlComponent(xmlObj) as ImportedXmlComponent;
}
/**
* Converts the xml string to a XmlComponent tree.
*
* @param importedContent xml content of the imported component
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public constructor(rootKey: string, _attr?: any) {
super(rootKey);
if (_attr) {
// eslint-disable-next-line functional/immutable-data
this.root.push(new ImportedXmlComponentAttributes(_attr));
}
}
public push(xmlComponent: XmlComponent | string): void {
this.root.push(xmlComponent);
}
}
/**
* Used for the attributes of root element that is being imported.
*/
export class ImportedRootElementAttributes extends XmlComponent {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public constructor(private readonly _attr: any) {
super("");
}
public prepForXml(_: IContext): IXmlableObject {
return {
_attr: this._attr,
};
}
}