typesxml
Version:
Open source XML library written in TypeScript
88 lines • 2.71 kB
JavaScript
/*******************************************************************************
* Copyright (c) 2023-2026 Maxprograms.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse License 1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-v10.html
*
* Contributors:
* Maxprograms - initial API and implementation
*******************************************************************************/
import { Constants } from "./Constants.js";
import { TextNode } from "./TextNode.js";
import { XMLUtils } from "./XMLUtils.js";
export class Indenter {
numSpaces;
indentLevel;
constructor(spaces, level) {
this.numSpaces = spaces;
if (level !== undefined) {
this.indentLevel = level;
}
else {
this.indentLevel = 1;
}
}
setSpaces(spaces) {
this.numSpaces = spaces;
}
setLevel(level) {
this.indentLevel = level;
}
indent(e) {
let space = e.getAttribute('xml:space');
if (space && 'preserve' === space.getValue()) {
return;
}
if (!this.hasText(e)) {
this.indentElement(e);
}
this.indentLevel++;
let children = e.getChildren();
children.forEach((child) => {
this.indent(child);
});
this.indentLevel--;
}
indentElement(e) {
let start = '\n';
let end = '\n';
for (let i = 0; i < (this.indentLevel * this.numSpaces); i++) {
start += ' ';
}
for (let i = 0; i < ((this.indentLevel - 1) * this.numSpaces); i++) {
end += ' ';
}
let content = new Array();
let nodes = e.getContent();
nodes.forEach((node) => {
if (!(node instanceof TextNode)) {
content.push(new TextNode(start));
content.push(node);
}
});
if (content.length !== 0) {
content.push(new TextNode(end));
}
e.setContent(content);
}
hasText(e) {
let result = false;
let content = e.getContent();
content.forEach((node) => {
if (node.getNodeType() === Constants.TEXT_NODE) {
let text = node.getValue();
let length = text.length;
for (let i = 0; i < length; i++) {
if (!XMLUtils.isXmlSpace(text.charAt(i))) {
result = true;
break;
}
}
}
});
return result;
}
}
//# sourceMappingURL=Indenter.js.map