summaryrefslogtreecommitdiff
path: root/packages/integrations/preact/src/client.ts
blob: 40475acc8c015fcf2e4536c3793a9a9cf0e6e91e (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { h, hydrate, render } from 'preact';
import StaticHtml from './static-html.js';
import type { SignalLike } from './types.js';

const sharedSignalMap = new Map<string, SignalLike>();

export default (element: HTMLElement) =>
	async (
		Component: any,
		props: Record<string, any>,
		{ default: children, ...slotted }: Record<string, any>,
		{ client }: Record<string, string>,
	) => {
		if (!element.hasAttribute('ssr')) return;
		for (const [key, value] of Object.entries(slotted)) {
			props[key] = h(StaticHtml, { value, name: key });
		}
		let signalsRaw = element.dataset.preactSignals;
		if (signalsRaw) {
			const { signal } = await import('@preact/signals');
			let signals: Record<string, string | [string, number][]> = JSON.parse(
				element.dataset.preactSignals!,
			);
			for (const [propName, signalId] of Object.entries(signals)) {
				if (Array.isArray(signalId)) {
					signalId.forEach(([id, indexOrKeyInProps]) => {
						const mapValue = props[propName][indexOrKeyInProps];
						let valueOfSignal = mapValue;

						// not an property key
						if (typeof indexOrKeyInProps !== 'string') {
							valueOfSignal = mapValue[0];
							indexOrKeyInProps = mapValue[1];
						}

						if (!sharedSignalMap.has(id)) {
							const signalValue = signal(valueOfSignal);
							sharedSignalMap.set(id, signalValue);
						}
						props[propName][indexOrKeyInProps] = sharedSignalMap.get(id);
					});
				} else {
					if (!sharedSignalMap.has(signalId)) {
						const signalValue = signal(props[propName]);
						sharedSignalMap.set(signalId, signalValue);
					}
					props[propName] = sharedSignalMap.get(signalId);
				}
			}
		}

		const child = h(
			Component,
			props,
			children != null ? h(StaticHtml, { value: children }) : children,
		);

		if (client === 'only') {
			element.innerHTML = '';
			render(child, element);
		} else {
			hydrate(child, element);
		}

		// Preact has no "unmount" option, but you can use `render(null, element)`
		element.addEventListener('astro:unmount', () => render(null, element), { once: true });
	};