import { Component, Input, OnInit } from '@angular/core'; import { Validators } from '@angular/forms'; import { LocationService } from '@core/services/location.service'; import { RegexValidator, TypeSafeFormBuilder, TypeSafeFormGroup, URLValidator } from '@yourcause/common'; import { I18nService } from '@yourcause/common/i18n'; import { YCModalComponent } from '@yourcause/common/modals'; import { BaseHelpContent, HelpContent } from '../help-content.typing'; const IsUrlPathRegexp = /^((\/\:?[\w-]+)+\/?)(\?([\w-]+(=[\w-]+)?\&?)*)?/; @Component({ selector: 'gc-help-content-modal', templateUrl: './help-content-modal.component.html', styleUrls: ['./help-content-modal.component.scss'] }) export class HelpContentModalComponent extends YCModalComponent implements OnInit { @Input() existing?: HelpContent; header!: string; formGroup: TypeSafeFormGroup; constructor ( private formBuilder: TypeSafeFormBuilder, private i18n: I18nService, private locationService: LocationService ) { super(); } ngOnInit () { this.header = this.existing ? this.i18n.translate('ADMIN:hdrEditHelpContent', {}, 'Edit Help Content') : this.i18n.translate('ADMIN:hdrNewHelpContent', {}, 'New Help Content'); this.formGroup = this.formBuilder.group({ name: [this.existing?.name ?? '', Validators.required], description: [this.existing?.description ?? '', Validators.required], grantsConnectLink: [this.existing?.grantsConnectLink ?? '', [ Validators.required, RegexValidator( IsUrlPathRegexp, { isUrlPath: { i18nKey: 'ADMIN:textIsNotValidPath', defaultValue: 'Is not a valid path' } } ) ]], helpContentLink: [this.existing?.helpContentLink ?? '', [Validators.required, URLValidator()]] }); } handleGrantsConnectLink () { const rawLink = this.formGroup.value.grantsConnectLink; let link = rawLink; if (link.startsWith('http')) { const url = new URL(link); link = url.pathname; } const cleanLink = this.locationService.getGenericRoute(link); if (rawLink !== cleanLink) { this.formGroup.get('grantsConnectLink').setValue(cleanLink); } } submit () { this.handleGrantsConnectLink(); this.closeModal.emit(this.formGroup.value); } cancel () { this.closeModal.emit(); } }