File: /var/www/quadcode.com/src/components/form/input/Recaptcha.svelte
<script lang="ts">
import { env } from '$env/dynamic/public';
import { onMount, onDestroy } from 'svelte';
import { locale } from '$lib/translations';
export let error: string | undefined = undefined;
let container: HTMLDivElement;
let widgetId: string | undefined = undefined;
export const getResponse = (): string => {
if (widgetId === undefined) return '';
return window.grecaptcha?.getResponse(widgetId) ?? '';
};
export const reset = (): void => {
if (widgetId !== undefined) {
window.grecaptcha?.reset(widgetId);
}
};
const renderWidget = () => {
if (!container || widgetId !== undefined) return;
if (window.grecaptcha?.render) {
const id = window.grecaptcha.render(container, {
sitekey: env.PUBLIC_RECAPTCHA_SITE_KEY ?? '',
hl: $locale,
});
widgetId = String(id);
}
};
onMount(() => {
if (window.grecaptcha?.render) {
renderWidget();
} else {
const queue = ((window as unknown as Record<string, unknown>)['__recaptchaQueue'] ??= []) as (() => void)[];
queue.push(renderWidget);
}
});
onDestroy(() => {
widgetId = undefined;
});
</script>
{#if env?.PUBLIC_RECAPTCHA_SITE_KEY}
<div class="recaptcha">
<div class="recaptchaBlock" bind:this={container} />
{#if error !== undefined}
<p class="recaptchaError">{error}</p>
{/if}
</div>
{/if}
<style lang="scss">
@import 'src/scss/media';
@import 'src/scss/mixins';
@import 'src/scss/variables';
.recaptcha {
position: relative;
.recaptchaBlock {
display: flex;
margin-inline: auto;
width: max-content;
@include breakpoint-down('deskS') {
transform: scale(0.85);
}
}
.recaptchaError {
position: absolute;
top: -15px;
right: 24px;
z-index: 1;
border-radius: 4px;
background: $redPrimary;
padding: 2px 8px;
color: $techWhite;
font-size: 10px;
font-weight: 400;
line-height: 14px;
}
}
</style>