51 lines
1.7 KiB
JavaScript
51 lines
1.7 KiB
JavaScript
(function () {
|
|
'use strict';
|
|
|
|
window.HtmlHelpers = (function() {
|
|
|
|
// `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.
|
|
function parseResponse(response, options) {
|
|
options = options || {};
|
|
|
|
return response.text().then(function (responseText) {
|
|
var docFrag = document.createRange().createContextualFragment(responseText);
|
|
var idPrefix;
|
|
if (!options.keepIds) {
|
|
idPrefix = _getIdPrefix();
|
|
_prefixIds(docFrag, idPrefix);
|
|
}
|
|
return Promise.resolve({ idPrefix: idPrefix, element: docFrag });
|
|
},
|
|
function (error) {
|
|
return Promise.reject(error);
|
|
}).catch(function (error) { console.error(error); });
|
|
}
|
|
|
|
function _prefixIds(element, idPrefix) {
|
|
var idAttrs = ['id', 'for', 'data-conditional-input', 'data-modal-trigger'];
|
|
|
|
idAttrs.forEach(function(attr) {
|
|
Array.from(element.querySelectorAll('[' + attr + ']')).forEach(function(input) {
|
|
var value = idPrefix + input.getAttribute(attr);
|
|
input.setAttribute(attr, value);
|
|
});
|
|
});
|
|
}
|
|
|
|
function _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) + '__';
|
|
}
|
|
|
|
return {
|
|
parseResponse: parseResponse,
|
|
}
|
|
})();
|
|
})();
|