tsx-dom-ssr
Version:
A simple way to use tsx syntax to do async server-side-rendering.
41 lines (40 loc) • 1.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toDom = toDom;
exports.renderToString = renderToString;
function toDomRecursive(document, children, thisArg, result) {
if (Array.isArray(children)) {
for (const child of children)
toDomRecursive(document, child, thisArg, result);
}
else if (typeof children === "string") {
if (children)
result.push(Promise.resolve(document.createTextNode(children)));
}
else if (typeof children === "number") {
result.push(Promise.resolve(document.createTextNode(children.toString())));
}
else if (typeof children === "function") {
// It's a VNode
result.push(children(document, thisArg));
}
else if (children) {
// It's a promise
result.push(children.then((resolved) => toDom(document, resolved, thisArg)));
}
return result;
}
async function toDom(document, children, thisArg) {
const target = document.createDocumentFragment();
const domChildren = await Promise.all(toDomRecursive(document, children, thisArg, []));
for (const child of domChildren) {
target.appendChild(child);
}
return target;
}
async function renderToString(document, children, thisArg) {
const fragment = await toDom(document, children, thisArg);
const wrapper = document.createElement("div");
wrapper.appendChild(fragment);
return wrapper.innerHTML;
}