libs/core-forms/src/lib/turnstile-component-plugin/turnstile.component.ts
DfCustomComponent<TurnstileConfig>
| changeDetection | ChangeDetectionStrategy.OnPush |
| selector | df-turnstile-component |
| standalone | true |
| imports |
NxErrorComponent
NxFormfieldErrorDirective
|
| templateUrl | ./turnstile.component.html |
No results matching.
ValidationErrorsModule
DfBaseModule
NxErrorComponent
NxFormfieldErrorDirective
DfCustomComponent<TurnstileConfig>
AfterViewInit
OnDestroy
Properties |
Inputs |
Outputs |
constructor()
|
| config | |
Type : C
|
|
| Required : true | |
|
Inherited from
DfBaseComponent
|
|
|
The configuration object for this formfield. Note that derived formfield components should extend the |
|
| control | |
Type : AbstractControl
|
|
Default value : new UntypedFormControl()
|
|
|
Inherited from
DfBaseComponent
|
|
|
The If an existing If no If a form component doesn't use the Note that if |
|
| formAclPath | |
Type : string
|
|
|
Inherited from
DfBaseComponent
|
|
| isAclHandled | |
Type : boolean
|
|
Default value : false
|
|
|
Inherited from
DfBaseComponent
|
|
| isRetailChannel | |
Type : boolean
|
|
|
Inherited from
DfBaseComponent
|
|
| validationConfigs | |
Type : ValidationConfig[] | undefined
|
|
|
Inherited from
DfBaseComponent
|
|
| formEvent | |
Type : DfEventPayload
|
|
|
Inherited from
DfBaseComponent
|
|
|
Emits when events associated to the form control happen. The emitted object contains the data necessary to uniquely identify the event (field id and event type). It also contains the event data. |
|
| appRootElementRef |
Type : unknown
|
Default value : inject(APP_ROOT_ELEMENT_REF)
|
| turnstileContainer |
Type : ElementRef<HTMLDivElement>
|
Decorators :
@ViewChild('turnstileContainer')
|
| componentOrControlInitFinished |
Type : unknown
|
Default value : new ReplaySubject<AbstractControl | undefined>(1)
|
|
Inherited from
DfBaseComponent
|
|
This ReplaySubject is provided to emit the control once it is initialized. |
| errorMessages |
Type : WritableSignal<Observable[]>
|
Default value : signal([])
|
|
Inherited from
DfBaseComponent
|
|
The resolved validation error messages for the current control state. |
| Readonly nxErrorAppearance |
Type : ErrorStyleType
|
Default value : inject(ERROR_DEFAULT_OPTIONS, { optional: true })?.appearance ||
(inject<CHANNEL>(CHANNEL_TOKEN) === CHANNEL.EXPERT ? 'text' : 'message')
|
|
Inherited from
DfBaseComponent
|
import { PfeBusinessService } from '@allianz/ngx-pfe';
import {
APP_ROOT_ELEMENT_REF,
LOCALE_RUNTIME_TOKEN,
TalyRuntimeLocalizationService,
type ValidationConfig
} from '@allianz/taly-core';
import { TrackingPlugin } from '../tracking-plugin/tracking-plugin';
import { DfBaseModule, DfCustomComponent } from '@allianz/taly-core/dynamic-form';
import { ValidationErrorsModule } from '@allianz/taly-core/ui';
import {
afterNextRender,
AfterViewInit,
ChangeDetectionStrategy,
Component,
computed,
ElementRef,
inject,
Injector,
OnDestroy,
Renderer2,
ViewChild
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Validators } from '@angular/forms';
import { LocalizeFn } from '@angular/localize/init';
import { Subject, switchMap } from 'rxjs';
import { NxErrorComponent } from '@allianz/ng-aquila/base';
import { NxFormfieldErrorDirective } from '@allianz/ng-aquila/formfield';
declare let $localize: LocalizeFn;
declare global {
interface Window {
onloadTurnstileCallback: () => void;
turnstile: {
render: (idOrContainer: string | HTMLElement, options: TurnstileOptions) => string;
reset: (widgetIdOrContainer: string | HTMLElement) => void;
getResponse: (widgetIdOrContainer: string | HTMLElement) => string | undefined;
remove: (widgetIdOrContainer: string | HTMLElement) => void;
ready: (callback: () => void) => void;
};
}
}
// Interface extracted of the Turnstile documentation:
// https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/#configurations
interface TurnstileOptions {
sitekey: string;
action?: string;
cData?: string;
callback?: (token: string) => void;
'error-callback'?: (errorCode: string) => void;
'expired-callback'?: () => void;
theme?: 'light' | 'dark' | 'auto';
language?: string;
tabindex?: number;
appearance?: 'always' | 'execute' | 'interaction-only';
}
export type TurnstileConfig = Pick<TurnstileOptions, 'action'>;
export const TURNSTILE_REQUIRED_ERROR_KEY = 'turnstileRequiredError';
@Component({
selector: 'df-turnstile-component',
imports: [ValidationErrorsModule, DfBaseModule, NxErrorComponent, NxFormfieldErrorDirective],
templateUrl: './turnstile.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TurnstileComponent
extends DfCustomComponent<TurnstileConfig>
implements AfterViewInit, OnDestroy
{
@ViewChild('turnstileContainer') turnstileContainer!: ElementRef<HTMLDivElement>;
appRootElementRef = inject(APP_ROOT_ELEMENT_REF);
private localeId = inject(LOCALE_RUNTIME_TOKEN);
private pfeBusinessService = inject(PfeBusinessService);
private trackingPlugin = inject(TrackingPlugin, { optional: true });
private talyRuntimeLocalizationService = inject(TalyRuntimeLocalizationService);
private scriptElement?: HTMLScriptElement;
private injector = inject(Injector);
private renderer = inject(Renderer2);
private scriptLoaded$ = new Subject<void>();
constructor() {
super();
this.control()?.addValidators(Validators.required);
this.enrichedValidationConfigs = computed(() => {
const requiredValidationConfig: ValidationConfig = {
validator: Validators.required,
validatorName: 'required',
errorMessage:
this.talyRuntimeLocalizationService.getTranslation(TURNSTILE_REQUIRED_ERROR_KEY)() ||
$localize`:@@validation.error.required:This field is required!`
};
const turnstileErrorValidationConfig: ValidationConfig = {
validatorName: 'turnstileError',
errorMessage: $localize`:@@validation.error.turnstile-error:An unexpected error occurred. Please try again later.`
} as unknown as ValidationConfig;
return [
...(this.validationConfigs() || []),
requiredValidationConfig,
turnstileErrorValidationConfig
];
});
}
ngAfterViewInit() {
this.handleTurstileInitialization();
this.addTurnstileScript();
}
ngOnDestroy() {
if (this.scriptElement) {
this.scriptElement.onload = null;
}
if (this.appRootElementRef.shadowRoot && this.turnstileContainer.nativeElement) {
this.renderer.removeChild(
this.appRootElementRef.nativeElement(),
this.turnstileContainer.nativeElement
);
}
}
private addTurnstileScript() {
if (window.turnstile) {
this.scriptLoaded$.next();
return;
}
this.scriptElement = document.createElement('script');
this.scriptElement.src =
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
this.scriptElement.async = false;
this.scriptElement.defer = false;
this.scriptElement.onload = () => this.scriptLoaded$.next();
document.head.appendChild(this.scriptElement);
}
private handleTurstileInitialization() {
this.scriptLoaded$
.pipe(
switchMap(() =>
this.pfeBusinessService.getObservableForExpressionKey('$._taly.turnstileSitekey', true)
),
takeUntilDestroyed(this.destroyRef)
)
.subscribe((sitekey) =>
afterNextRender(() => this.showTurnstile(sitekey), { injector: this.injector })
);
}
private showTurnstile(sitekey?: string) {
this.removeTurnstile();
if (!sitekey) {
if (this.pfeBusinessService.getValueByExpression('$._taly.turnstileSitekeyError')) {
console.error('Not able to initialize turnstile component because sitekey is missing.');
}
return;
}
const config = this.config().config;
const action = config?.action || '';
if (window?.turnstile === undefined) return;
if (this.appRootElementRef.shadowRoot) {
this.renderer.appendChild(
this.appRootElementRef.nativeElement(),
this.turnstileContainer.nativeElement
);
this.renderer.setAttribute(this.turnstileContainer.nativeElement, 'slot', 'turnstile');
}
window.turnstile.ready(() => {
window.turnstile.render(this.turnstileContainer.nativeElement, {
language: this.localeId().toLocaleLowerCase(),
action: action,
sitekey: sitekey,
callback: (token) => {
this.control()?.setValue(token);
},
'error-callback': (errorCode) => {
this.trackingPlugin?.onTurnstileError(errorCode);
this.control()?.setValue(null);
this.control()?.setErrors({ turnstileError: true });
console.error(
'Turnstile Error. Open https://developers.cloudflare.com/turnstile/troubleshooting/client-side-errors/error-codes/ for more details on this error code: ',
errorCode
);
},
'expired-callback': () => {
this.control()?.setValue(null);
this.control()?.setErrors({ turnstileError: true });
console.error('Turnstile token expired and did not reset the widget');
}
});
});
}
private removeTurnstile() {
if (this.turnstileContainer && this.turnstileContainer.nativeElement) {
this.turnstileContainer.nativeElement.innerHTML = '';
}
}
}
@if (appRootElementRef.shadowRoot) {
<slot name="turnstile"></slot>
}
<div #turnstileContainer></div>
@if (control()?.touched) { @for (message$ of errorMessages(); track $index) {
<nx-error class="nx-margin-top-xs" nxFormfieldError [appearance]="nxErrorAppearance">{{
message$ | async
}}</nx-error>
} }