Files
discord-clone/node_modules/@unhead/ssr/dist/index.cjs
2023-01-03 09:29:04 -06:00

63 lines
1.9 KiB
JavaScript

'use strict';
const SelfClosingTags = ["meta", "link", "base"];
const propsToString = (props) => {
const handledAttributes = [];
for (const [key, value] of Object.entries(props)) {
if (value === false || value == null)
continue;
let attribute = key;
if (value !== true)
attribute += `="${String(value).replace(/"/g, """)}"`;
handledAttributes.push(attribute);
}
return handledAttributes.length > 0 ? ` ${handledAttributes.join(" ")}` : "";
};
const tagToString = (tag) => {
const attrs = propsToString(tag.props);
const openTag = `<${tag.tag}${attrs}>`;
return SelfClosingTags.includes(tag.tag) ? openTag : `${openTag}${tag.children || ""}</${tag.tag}>`;
};
function ssrRenderTags(tags) {
const schema = { htmlAttrs: {}, bodyAttrs: {}, tags: { head: [], bodyClose: [], bodyOpen: [] } };
for (const tag of tags) {
if (tag.tag === "htmlAttrs" || tag.tag === "bodyAttrs") {
schema[tag.tag] = { ...schema[tag.tag], ...tag.props };
continue;
}
schema.tags[tag.tagPosition || "head"].push(tagToString(tag));
}
return {
headTags: schema.tags.head.join("\n"),
bodyTags: schema.tags.bodyClose.join("\n"),
bodyTagsOpen: schema.tags.bodyOpen.join("\n"),
htmlAttrs: propsToString(schema.htmlAttrs),
bodyAttrs: propsToString(schema.bodyAttrs)
};
}
async function renderSSRHead(head) {
const beforeRenderCtx = { shouldRender: true };
await head.hooks.callHook("ssr:beforeRender", beforeRenderCtx);
if (!beforeRenderCtx.shouldRender) {
return {
headTags: "",
bodyTags: "",
bodyTagsOpen: "",
htmlAttrs: "",
bodyAttrs: ""
};
}
const ctx = { tags: await head.resolveTags() };
await head.hooks.callHook("ssr:render", ctx);
const html = ssrRenderTags(ctx.tags);
const renderCtx = { tags: ctx.tags, html };
await head.hooks.callHook("ssr:rendered", renderCtx);
return renderCtx.html;
}
exports.renderSSRHead = renderSSRHead;