fradrive/static/es/services/htmlHelpers.js

44 lines
1.5 KiB
JavaScript

class HtmlHelpers {
// `parseResponse` takes a raw HttpClient response and an options object.
// Returns an object with `element` being an contextual fragment of the
// HTML in the response and `ifPrefix` being the prefix that was used to
// "unique-ify" the ids of the received HTML.
// Original Response IDs can optionally be kept by adding `keepIds: true`
// to the `options` object.
parseResponse(response, options = {}) {
return response.text()
.then(
(responseText) => {
const docFrag = document.createRange().createContextualFragment(responseText);
let idPrefix;
if (!options.keepIds) {
idPrefix = this._getIdPrefix();
this._prefixIds(docFrag, idPrefix);
}
return Promise.resolve({ idPrefix, element: docFrag });
},
Promise.reject,
).catch(console.error);
}
_prefixIds(element, idPrefix) {
const idAttrs = ['id', 'for', 'data-conditional-input', 'data-modal-trigger'];
idAttrs.forEach((attr) => {
Array.from(element.querySelectorAll('[' + attr + ']')).forEach((input) => {
const value = idPrefix + input.getAttribute(attr);
input.setAttribute(attr, value);
});
});
}
_getIdPrefix() {
// leading 'r'(andom) to overcome the fact that IDs
// starting with a numeric value are not valid in CSS
return 'r' + Math.floor(Math.random() * 100000) + '__';
}
}
window.HtmlHelpers = new HtmlHelpers();