2024-04-17 03:38:53 -05:00
|
|
|
import { setup } from 'virtual:@astrojs/vue/app';
|
2024-02-27 06:15:27 -05:00
|
|
|
import { Suspense, createApp, createSSRApp, h } from 'vue';
|
2022-03-18 17:35:45 -05:00
|
|
|
import StaticHtml from './static-html.js';
|
|
|
|
|
2024-09-17 07:54:49 -05:00
|
|
|
// keep track of already initialized apps, so we don't hydrate again for view transitions
|
|
|
|
let appMap = new WeakMap();
|
|
|
|
|
2022-05-31 11:47:13 -05:00
|
|
|
export default (element) =>
|
2022-10-13 14:15:57 -05:00
|
|
|
async (Component, props, slotted, { client }) => {
|
2022-05-31 11:47:13 -05:00
|
|
|
if (!element.hasAttribute('ssr')) return;
|
2022-05-31 11:29:36 -05:00
|
|
|
|
2022-05-31 11:47:13 -05:00
|
|
|
// Expose name on host component for Vue devtools
|
|
|
|
const name = Component.name ? `${Component.name} Host` : undefined;
|
|
|
|
const slots = {};
|
2022-06-23 10:10:54 -05:00
|
|
|
for (const [key, value] of Object.entries(slotted)) {
|
|
|
|
slots[key] = () => h(StaticHtml, { value, name: key === 'default' ? undefined : key });
|
2022-05-31 11:47:13 -05:00
|
|
|
}
|
2023-03-31 12:42:03 -05:00
|
|
|
|
2023-08-29 09:30:11 -05:00
|
|
|
const isHydrate = client !== 'only';
|
2023-10-18 08:23:19 -05:00
|
|
|
const bootstrap = isHydrate ? createSSRApp : createApp;
|
2023-08-29 09:30:11 -05:00
|
|
|
|
2024-09-17 07:54:49 -05:00
|
|
|
// keep a reference to the app, props and slots so we can update a running instance later
|
|
|
|
let appInstance = appMap.get(element);
|
|
|
|
|
|
|
|
if (!appInstance) {
|
|
|
|
appInstance = {
|
|
|
|
props,
|
|
|
|
slots,
|
|
|
|
};
|
|
|
|
const app = bootstrap({
|
|
|
|
name,
|
|
|
|
render() {
|
|
|
|
let content = h(Component, appInstance.props, appInstance.slots);
|
|
|
|
appInstance.component = this;
|
|
|
|
// related to https://github.com/withastro/astro/issues/6549
|
|
|
|
// if the component is async, wrap it in a Suspense component
|
|
|
|
if (isAsync(Component.setup)) {
|
|
|
|
content = h(Suspense, null, content);
|
|
|
|
}
|
|
|
|
return content;
|
|
|
|
},
|
|
|
|
});
|
2024-10-03 13:52:11 -05:00
|
|
|
app.config.idPrefix = element.getAttribute('prefix');
|
2024-09-17 07:54:49 -05:00
|
|
|
await setup(app);
|
|
|
|
app.mount(element, isHydrate);
|
|
|
|
appMap.set(element, appInstance);
|
2024-10-05 06:48:30 -05:00
|
|
|
element.addEventListener('astro:unmount', () => app.unmount(), { once: true });
|
2024-09-17 07:54:49 -05:00
|
|
|
} else {
|
|
|
|
appInstance.props = props;
|
|
|
|
appInstance.slots = slots;
|
|
|
|
appInstance.component.$forceUpdate();
|
|
|
|
}
|
2022-05-31 11:47:13 -05:00
|
|
|
};
|
2023-03-31 12:42:03 -05:00
|
|
|
|
2023-03-31 12:44:00 -05:00
|
|
|
function isAsync(fn) {
|
|
|
|
const constructor = fn?.constructor;
|
2023-03-31 12:42:03 -05:00
|
|
|
return constructor && constructor.name === 'AsyncFunction';
|
|
|
|
}
|