@shopify/react-html
Version:
A component to render your React app with no static HTML
78 lines (73 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
const SERIALIZE_ATTRIBUTE = 'data-serialized-id';
const MANAGED_ATTRIBUTE = 'data-react-html';
function getSerializationsFromDocument() {
const serializations = new Map();
if (typeof document === 'undefined') {
return serializations;
}
for (const node of document.querySelectorAll(`[${SERIALIZE_ATTRIBUTE}]`)) {
serializations.set(node.getAttribute(SERIALIZE_ATTRIBUTE), getSerializedFromNode(node));
}
return serializations;
}
function getSerializedFromNode(node) {
const value = node.textContent;
try {
return value ? JSON.parse(value) : undefined;
} catch {
return undefined;
}
}
function getSerialized(id) {
const node = document.querySelector(`[${SERIALIZE_ATTRIBUTE}="${id}"]`);
if (node == null) {
throw new Error(`No serializations found for id "${id}"`);
}
return getSerializedFromNode(node);
}
// We hide the document in development by default in order to prevent
// flashes of unstyled content. This function will show the document
// after the styles have loaded.
function showPage() {
// eslint-disable-next-line no-process-env
return process.env.NODE_ENV === 'development' && typeof document !== 'undefined' ? new Promise(resolve => {
setTimeout(() => {
document.body.style.visibility = '';
resolve();
}, 0);
}) : Promise.resolve();
}
function removeDuplicate(metas) {
const names = new Set();
const properties = new Set();
const metasWithoutDuplicates = metas.reverse().filter(meta => {
const {
name,
property
} = meta;
if (name) {
if (names.has(name)) {
return false;
}
names.add(name);
return true;
}
if (property) {
if (properties.has(property)) {
return false;
}
properties.add(property);
return true;
}
return true;
});
return metasWithoutDuplicates.reverse();
}
exports.MANAGED_ATTRIBUTE = MANAGED_ATTRIBUTE;
exports.SERIALIZE_ATTRIBUTE = SERIALIZE_ATTRIBUTE;
exports.getSerializationsFromDocument = getSerializationsFromDocument;
exports.getSerialized = getSerialized;
exports.removeDuplicate = removeDuplicate;
exports.showPage = showPage;