This repository has been archived on 2024-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
fradrive-old/frontend/src/services/html-helpers/html-helpers.js
2020-05-05 15:09:42 +02:00

43 lines
1.5 KiB
JavaScript

export 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 element = document.createElement('div');
element.innerHTML = responseText;
let idPrefix = '';
if (!options.keepIds) {
idPrefix = this._getIdPrefix();
this._prefixIds(element, idPrefix);
}
return Promise.resolve({ idPrefix, element, headers: response.headers });
},
Promise.reject,
).catch(console.error);
}
_prefixIds(element, idPrefix) {
const idAttrs = ['id', 'for', 'list', '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) + '__';
}
}