import { Directive , ElementRef , EventEmitter , HostListener , Inject , Input , NgZone , OnInit , Output , PLATFORM_ID , OnDestroy } from '@angular/core' ; import { isPlatformBrowser , isPlatformServer } from '@angular/common' ; import { Subscription } from 'rxjs' ; import { CAPTCHA_CONFIG , CaptchaConfig } from './ng-hcaptcha-config' ; import { loadHCaptcha } from './hcaptcha-utils' ; declare const window ; @ Directive ( { selector : '[ngHcaptchaInvisibleButton]' } ) export class NgHcaptchaInvisibleButtonDirective implements OnInit , OnDestroy { @ Input ( ) siteKey : string ; @ Input ( ) languageCode : string ; @ Output ( ) verify : EventEmitter < string > = new EventEmitter < string > ( ) ; @ Output ( ) expired : EventEmitter < any > = new EventEmitter < any > ( ) ; @ Output ( ) error : EventEmitter < any > = new EventEmitter < any > ( ) ; @ Output ( ) click : EventEmitter < any > = new EventEmitter < any > ( ) ; private lastClickEvent : any ; private captcha$ : Subscription ; private widgetId : string ; constructor ( private elRef , @ Inject ( CAPTCHA_CONFIG ) private config , private zone , @ Inject ( PLATFORM_ID ) private platformId ) { } ngOnInit ( ) { if ( ! this . languageCode ) { this . languageCode = this . config . languageCode ; } if ( isPlatformServer ( this . platformId ) ) { return ; } this . captcha$ = loadHCaptcha ( this . languageCode ) . subscribe ( ( ) => { setTimeout ( ( context ) => { const options = { sitekey : ( context . siteKey || context . config . siteKey ) , size : 'invisible' , callback : ( res ) => { context . zone . run ( ( ) => context . onVerify ( res ) ) ; } , 'expired-callback' : ( res ) => { context . zone . run ( ( ) => context . onExpired ( res ) ) ; } , 'error-callback' : ( err ) => { context . zone . run ( ( ) => context . onError ( err ) ) ; } } ; context . widgetId = window . hcaptcha . render ( context . elRef . nativeElement , options ) ; } , 50 , this ) ; } ) ; } ngOnDestroy ( ) { if ( isPlatformServer ( this . platformId ) ) { return ; } this . captcha$ . unsubscribe ( ) ; } @ HostListener ( 'click' , [ '$event' ] ) onClick ( event ) { if ( event . hCaptchaToken ) { return ; } this . lastClickEvent = event ; event . stopPropagation ( ) ; event . preventDefault ( ) ; event . cancelBubble = true ; if ( isPlatformBrowser ( this . platformId ) ) { window . hcaptcha . execute ( this . widgetId ) ; } return false ; } param response private onVerify ( response ) { const event = this . lastClickEvent || { } ; event . hCaptchaToken = response ; this . click . emit ( event ) ; this . verify . emit ( response ) ; } param response private onExpired ( response ) { this . expired . emit ( response ) ; } param error private onError ( error ) { this . error . emit ( error ) ; } }