summaryrefslogtreecommitdiff
path: root/packages/integrations/preact/src/signals.ts
blob: ef3a4b70a4ee8f409dc804498afe7e85317d508b (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
import type { Context } from './context.js';
import { incrementId } from './context.js';
import type { AstroPreactAttrs, PropNameToSignalMap, SignalLike } from './types.js';

function isSignal(x: any): x is SignalLike {
	return x != null && typeof x === 'object' && typeof x.peek === 'function' && 'value' in x;
}

export function restoreSignalsOnProps(ctx: Context, props: Record<string, any>) {
	// Restore signal props that were mutated for serialization
	let propMap: PropNameToSignalMap;
	if (ctx.propsToSignals.has(props)) {
		propMap = ctx.propsToSignals.get(props)!;
	} else {
		propMap = new Map();
		ctx.propsToSignals.set(props, propMap);
	}
	for (const [key, signal] of propMap) {
		props[key] = signal;
	}
	return propMap;
}

export function serializeSignals(
	ctx: Context,
	props: Record<string, any>,
	attrs: AstroPreactAttrs,
	map: PropNameToSignalMap
) {
	// Check for signals
	const signals: Record<string, string> = {};
	for (const [key, value] of Object.entries(props)) {
		if (isSignal(value)) {
			// Set the value to the current signal value
			// This mutates the props on purpose, so that it will be serialized correct.
			props[key] = value.peek();
			map.set(key, value);

			let id: string;
			if (ctx.signals.has(value)) {
				id = ctx.signals.get(value)!;
			} else {
				id = incrementId(ctx);
				ctx.signals.set(value, id);
			}
			signals[key] = id;
		}
	}

	if (Object.keys(signals).length) {
		attrs['data-preact-signals'] = JSON.stringify(signals);
	}
}