summaryrefslogtreecommitdiff
path: root/packages/integrations/react/src/context.ts
blob: 953c35c6a119fbb99ef0c6fe90721015dcedc55a (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
import type { SSRResult } from 'astro';

const contexts = new WeakMap<SSRResult, { currentIndex: number; readonly id: string }>();

const ID_PREFIX = 'r';

function getContext(rendererContextResult: SSRResult) {
	if (contexts.has(rendererContextResult)) {
		return contexts.get(rendererContextResult);
	}
	const ctx = {
		currentIndex: 0,
		get id() {
			return ID_PREFIX + this.currentIndex.toString();
		},
	};
	contexts.set(rendererContextResult, ctx);
	return ctx;
}

export function incrementId(rendererContextResult: SSRResult) {
	const ctx = getContext(rendererContextResult)!;
	const id = ctx.id;
	ctx.currentIndex++;
	return id;
}