Add a tagged template literal function stanza

For creating XML stanzas from template literals.
This commit is contained in:
JC Brand 2022-08-10 14:49:23 +02:00
parent cac92c3ebc
commit d2bdce51e8
2 changed files with 22 additions and 0 deletions

View File

@ -762,6 +762,7 @@ Object.assign(converse, {
log,
sizzle,
sprintf,
stanza: u.stanza,
u,
}
});

View File

@ -0,0 +1,21 @@
const parser = new DOMParser();
const parserErrorNS = parser.parseFromString('invalid', 'text/xml')
.getElementsByTagName("parsererror")[0].namespaceURI;
export function toStanza (string) {
const node = parser.parseFromString(string, "text/xml");
if (node.getElementsByTagNameNS(parserErrorNS, 'parsererror').length) {
throw new Error(`Parser Error: ${string}`);
}
return node.firstElementChild;
}
export function stanza (strings, ...values) {
return toStanza(
strings.reduce((acc, str) => {
const idx = strings.indexOf(str);
return acc + str + (values.length > idx ? values[idx] : '')
}, '')
);
}