Skip to content

Commit

Permalink
Refactor in oder to remove circular dependencies
Browse files Browse the repository at this point in the history
- Moved the `serialize` function into the `Builder`
- Moved log functions into `./log.js`
- Declare `Strophe` in `./index.js` and don't import it from anywhere else.

Used `dpdm` to identify circular dependencies:

```
npx dpdm src/index.js --warning=off
```
  • Loading branch information
jcbrand committed Mar 22, 2024
1 parent c1ac71d commit 62cd939
Show file tree
Hide file tree
Showing 27 changed files with 1,116 additions and 894 deletions.
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

0 comments on commit 62cd939

Please sign in to comment.