@story-telling-reporter/react-embed-code-generator
Version:
## Installation `yarn install`
53 lines (50 loc) • 1.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hydrate = hydrate;
exports.render = render;
var _client = require("react-dom/client");
var _jsxRuntime = require("react/jsx-runtime");
function hydrate(namespace, pkgName, Component) {
const dataArr = window[namespace][pkgName];
if (Array.isArray(dataArr)) {
dataArr.forEach(data => {
const {
uuid,
...dataOfComponent
} = data;
const container = document.getElementById(uuid);
(0, _client.hydrateRoot)(container, /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, {
...dataOfComponent
}));
});
// Clean up data to avoid repeated hydration.
// Repeated hydration might cause unexpected error, such as:
// there are two karaoke embedded codes in the same web page.
// The first one embed code script has already hydrated these two embedded codes
// on the DOM.
// However, the second embed code script will hydrate them again since
// `window[namespace][pkgName]` has data.
// The second hydration will cause unexpected React errors.
window[namespace][pkgName] = [];
}
}
function render(namespace, pkgName, Component) {
const dataArr = window[namespace][pkgName];
if (Array.isArray(dataArr)) {
dataArr.forEach(data => {
const {
uuid,
...dataOfComponent
} = data;
const container = document.getElementById(uuid);
const root = (0, _client.createRoot)(container);
root.render(/*#__PURE__*/(0, _jsxRuntime.jsx)(Component, {
...dataOfComponent
}));
});
// Clean up data to avoid repeated rendering.
window[namespace][pkgName] = [];
}
}