tsx-dom-ssr
Version:
A simple way to use tsx syntax to do async server-side-rendering.
53 lines (52 loc) • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHtmlElementNode = createHtmlElementNode;
exports.createComponentNode = createComponentNode;
exports.internalComponent = internalComponent;
const setAttributes_1 = require("./setAttributes");
const domUtils_1 = require("./domUtils");
function hasChildrenSet(children) {
if (Array.isArray(children)) {
return children.length > 0;
}
return children !== undefined;
}
function createDomElement(document, tag, attrs) {
const options = attrs.is ? { is: attrs.is } : undefined;
if (attrs.xmlns)
return document.createElementNS(attrs.xmlns, tag, options);
return document.createElement(tag, options);
}
function createHtmlElementNode(tag, { children, ...attrs }) {
return async (document, thisArg) => {
let finalTag = tag;
let finalAttrs = attrs;
if ("tsxTag" in finalAttrs) {
finalTag = finalAttrs.tsxTag;
if (!finalAttrs.is && tag.includes("-")) {
finalAttrs = { ...finalAttrs, is: tag };
}
}
const el = createDomElement(document, finalTag, finalAttrs);
(0, setAttributes_1.setAttributes)(el, finalAttrs);
if (el.innerHTML) {
if (hasChildrenSet(children)) {
console.error("Received both dangerouslySetInnerHTML and children. Children will be ignored!");
}
}
else {
const fragment = await (0, domUtils_1.toDom)(document, children, thisArg);
el.appendChild(fragment);
}
return el;
};
}
function createComponentNode(tag, props) {
return async (document, thisArg) => {
const children = await tag.call(thisArg, props);
return (0, domUtils_1.toDom)(document, children, thisArg);
};
}
function internalComponent(comp) {
return Object.assign(comp, { __tsxInternal: true });
}