summaryrefslogtreecommitdiff
path: root/packages/integrations/svelte/client-v5.js
blob: b3d2e1964eb8ea3008fda43a1023f730c9f6a4cc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { mount } from 'svelte';

export default (element) => {
	return async (Component, props, slotted) => {
		if (!element.hasAttribute('ssr')) return;

		let children = undefined;
		let $$slots = undefined;
		for (const [key, value] of Object.entries(slotted)) {
			if (key === 'default') {
				children = createSlotDefinition(key, value);
			} else {
				$$slots ??= {};
				$$slots[key] = createSlotDefinition(key, value);
			}
		}

		const [, destroy] = mount(Component, {
			target: element,
			props: {
				...props,
				children,
				$$slots,
			},
		});

		element.addEventListener('astro:unmount', () => destroy(), { once: true });
	};
};

function createSlotDefinition(key, children) {
	/**
	 * @param {Comment} $$anchor A comment node for slots in Svelte 5
	 */
	return ($$anchor, _$$slotProps) => {
		const parent = $$anchor.parentNode;
		const el = document.createElement('div');
		el.innerHTML = `<astro-slot${
			key === 'default' ? '' : ` name="${key}"`
		}>${children}</astro-slot>`;
		parent.insertBefore(el.children[0], $$anchor);
	};
}