astro/packages/renderers/renderer-lit/server.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

import './server-shim.js';
import '@lit-labs/ssr/lib/render-lit-html.js';
import { LitElementRenderer } from '@lit-labs/ssr/lib/lit-element-renderer.js';
function isCustomElementTag(name) {
2021-12-22 21:11:05 +00:00
return typeof name === 'string' && /-/.test(name);
}
function getCustomElementConstructor(name) {
2021-12-22 21:11:05 +00:00
if (typeof customElements !== 'undefined' && isCustomElementTag(name)) {
return customElements.get(name) || null;
}
return null;
}
async function isLitElement(Component) {
2021-12-22 21:11:05 +00:00
const Ctr = getCustomElementConstructor(Component);
return !!(Ctr && Ctr._$litElement$);
}
async function check(Component, _props, _children) {
2021-12-22 21:11:05 +00:00
// Lit doesn't support getting a tagName from a Constructor at this time.
// So this must be a string at the moment.
return !!(await isLitElement(Component));
}
2021-07-13 12:28:50 +00:00
function* render(tagName, attrs, children) {
2021-12-22 21:11:05 +00:00
const instance = new LitElementRenderer(tagName);
2021-12-22 21:11:05 +00:00
// LitElementRenderer creates a new element instance, so copy over.
const Ctr = getCustomElementConstructor(tagName);
for (let [name, value] of Object.entries(attrs)) {
// check if this is a reactive property
if (name in Ctr.prototype) {
instance.setProperty(name, value);
} else {
instance.setAttribute(name, value);
}
}
2021-12-22 21:11:05 +00:00
instance.connectedCallback();
2021-12-22 21:11:05 +00:00
yield `<${tagName}`;
yield* instance.renderAttributes();
yield `>`;
const shadowContents = instance.renderShadow({});
if (shadowContents !== undefined) {
yield '<template shadowroot="open">';
yield* shadowContents;
yield '</template>';
}
yield children || ''; // dont print “undefined” as string
yield `</${tagName}>`;
}
async function renderToStaticMarkup(Component, props, children) {
2021-12-22 21:11:05 +00:00
let tagName = Component;
2021-12-22 21:11:05 +00:00
let out = '';
for (let chunk of render(tagName, props, children)) {
out += chunk;
}
2021-12-22 21:11:05 +00:00
return {
html: out,
};
}
export default {
2021-12-22 21:11:05 +00:00
check,
renderToStaticMarkup,
};