Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor in oder to remove circular dependencies #703

Merged
merged 1 commit into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 93 additions & 61 deletions src/bosh.js

Large diffs are not rendered by default.

48 changes: 45 additions & 3 deletions src/builder.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NS } from './constants.js';
import { copyElement, createHtml, serialize, xmlElement, xmlGenerator, xmlTextNode } from './utils.js';
import { ElementType, NS } from './constants.js';
import { copyElement, createHtml, xmlElement, xmlGenerator, xmlTextNode, xmlescape } from './utils.js';

/**
* Create a {@link Strophe.Builder}
Expand Down Expand Up @@ -95,6 +95,48 @@ class Builder {
this.node = this.nodeTree;
}

/**
* Render a DOM element and all descendants to a String.
* @param {Element|Builder} elem - A DOM element.
* @return {string} - The serialized element tree as a String.
*/
static serialize(elem) {
if (!elem) return null;

const el = elem instanceof Builder ? elem.tree() : elem;

const names = [...Array(el.attributes.length).keys()].map((i) => el.attributes[i].nodeName);
names.sort();
let result = names.reduce(
(a, n) => `${a} ${n}="${xmlescape(el.attributes.getNamedItem(n).value)}"`,
`<${el.nodeName}`
);

if (el.childNodes.length > 0) {
result += '>';
for (let i = 0; i < el.childNodes.length; i++) {
const child = el.childNodes[i];
switch (child.nodeType) {
case ElementType.NORMAL:
// normal element, so recurse
result += Builder.serialize(/** @type {Element} */ (child));
break;
case ElementType.TEXT:
// text element to escape values
result += xmlescape(child.nodeValue);
break;
case ElementType.CDATA:
// cdata section so don't escape values
result += '<![CDATA[' + child.nodeValue + ']]>';
}
}
result += '</' + el.nodeName + '>';
} else {
result += '/>';
}
return result;
}

/**
* Return the DOM tree.
*
Expand All @@ -117,7 +159,7 @@ class Builder {
* @return {string} The serialized DOM tree in a String.
*/
toString() {
return serialize(this.nodeTree);
return Builder.serialize(this.nodeTree);
}

/**
Expand Down
Loading
Loading