Add a tagged template literal function stanza
For creating XML stanzas from template literals.
This commit is contained in:
parent
cac92c3ebc
commit
d2bdce51e8
@ -762,6 +762,7 @@ Object.assign(converse, {
|
||||
log,
|
||||
sizzle,
|
||||
sprintf,
|
||||
stanza: u.stanza,
|
||||
u,
|
||||
}
|
||||
});
|
||||
|
21
src/headless/utils/stanza.js
Normal file
21
src/headless/utils/stanza.js
Normal 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] : '')
|
||||
}, '')
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue
Block a user