mirror of
https://github.com/withastro/astro.git
synced 2024-12-23 21:53:55 -05:00
7373d61cdc
* feat: pass all slots to renderers * refactor: pass `slots` as top-level props * test: add named slot test for frameworks * fix: nested hydration, slots that are not initially rendered * test: add nested-recursive e2e test * fix: render unmatched custom element children * chore: update lockfile * fix: unrendered slots for client:only * fix(lit): ensure lit integration uses new slots API * chore: add changeset * chore: add changesets * fix: lit slots * feat: convert dash-case or snake_case slots to camelCase for JSX * feat: remove tmpl special logic * test: add slot components-in-markdown test * refactor: prefer Object.entries.map() to for/of loop Co-authored-by: Nate Moore <nate@astro.build>
46 lines
1.3 KiB
JavaScript
46 lines
1.3 KiB
JavaScript
import { h, Component as BaseComponent } from 'preact';
|
|
import render from 'preact-render-to-string';
|
|
import StaticHtml from './static-html.js';
|
|
|
|
const slotName = str => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
|
|
|
|
function check(Component, props, children) {
|
|
if (typeof Component !== 'function') return false;
|
|
|
|
if (Component.prototype != null && typeof Component.prototype.render === 'function') {
|
|
return BaseComponent.isPrototypeOf(Component);
|
|
}
|
|
|
|
try {
|
|
const { html } = renderToStaticMarkup(Component, props, children);
|
|
if (typeof html !== 'string') {
|
|
return false;
|
|
}
|
|
|
|
// There are edge cases (SolidJS) where Preact *might* render a string,
|
|
// but components would be <undefined></undefined>
|
|
|
|
return !/\<undefined\>/.test(html);
|
|
} catch (err) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function renderToStaticMarkup(Component, props, { default: children, ...slotted }) {
|
|
const slots = {};
|
|
for (const [key, value] of Object.entries(slotted)) {
|
|
const name = slotName(key);
|
|
slots[name] = h(StaticHtml, { value, name });
|
|
}
|
|
// Note: create newProps to avoid mutating `props` before they are serialized
|
|
const newProps = { ...props, ...slots }
|
|
const html = render(
|
|
h(Component, newProps, children != null ? h(StaticHtml, { value: children }) : children)
|
|
);
|
|
return { html };
|
|
}
|
|
|
|
export default {
|
|
check,
|
|
renderToStaticMarkup,
|
|
};
|