Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 26x 23x 25x 25x 362x 1815x 23x 23x 25x 23x 23x 23x 23x 38x 34x 28x 28x 3x 3x 25x 25x 28x 28x 46x 46x 26x 36x 26x 10x 10x 3x 97x 1x 6x 6x 7x 7x 7x 7x 99x 7x 2x 7x 4x 7x 5x 5x 5x 5x 1x 1x 1x 1x 6x 5x 5x 2x 2x 724x 62x 93x 62x 3x 3x 3x 62x 62x 367x 63x 63x 35x 35x 28x 35x 25x 10x 10x 10x 9x 1x 1x 1x 30x 30x 8x 5x 8x 7x 1x 43x 71x 18x 63x 63x 63x | /** * Copyright (c) Siemens 2016 - 2025 * SPDX-License-Identifier: MIT */ import { CdkConnectedOverlay, CdkOverlayOrigin } from '@angular/cdk/overlay'; import { NgClass } from '@angular/common'; import { booleanAttribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, ElementRef, inject, input, model, OnChanges, output, signal, SimpleChanges, viewChild } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator } from '@angular/forms'; import { SI_FORM_ITEM_CONTROL, SiFormItemControl } from '@siemens/element-ng/form'; import { addIcons, elementDown2, SiIconComponent } from '@siemens/element-ng/icon'; import { SiSelectListHasFilterComponent } from '@siemens/element-ng/select'; import { injectSiTranslateService, SiTranslatePipe, t } from '@siemens/element-translate-ng/translate'; import { PhoneNumber, PhoneNumberFormat, PhoneNumberUtil } from 'google-libphonenumber'; import { SiPhoneNumberInputSelectDirective } from './si-phone-number-input-select.directive'; import { CountryInfo, PhoneDetails } from './si-phone-number-input.models'; @Component({ selector: 'si-phone-number-input', imports: [ CdkOverlayOrigin, CdkConnectedOverlay, NgClass, SiIconComponent, SiPhoneNumberInputSelectDirective, SiSelectListHasFilterComponent, SiTranslatePipe ], templateUrl: './si-phone-number-input.component.html', styleUrl: './si-phone-number-input.component.scss', providers: [ { provide: NG_VALIDATORS, useExisting: SiPhoneNumberInputComponent, multi: true }, { provide: NG_VALUE_ACCESSOR, useExisting: SiPhoneNumberInputComponent, multi: true }, { provide: SI_FORM_ITEM_CONTROL, useExisting: SiPhoneNumberInputComponent } ], changeDetection: ChangeDetectionStrategy.OnPush, host: { 'role': 'group', '[attr.aria-labelledby]': 'labelledby()', '[attr.id]': 'id()', '[class.disabled]': 'disabled()', '[class.readonly]': 'readonly()', '[class.country-focus]': 'countryFocused()' } }) export class SiPhoneNumberInputComponent implements ControlValueAccessor, Validator, OnChanges, SiFormItemControl { private static idCounter = 0; private phoneUtil = PhoneNumberUtil.getInstance(); private translate = injectSiTranslateService(); private changeDetectorRef = inject(ChangeDetectorRef); private elementRef = inject<ElementRef<HTMLElement>>(ElementRef); /** * Unique identifier. * * @defaultValue * ``` * `__si-phone-number-input-${SiPhoneNumberInputComponent.idCounter++}` * ``` */ readonly id = input(`__si-phone-number-input-${SiPhoneNumberInputComponent.idCounter++}`); /** * ISO_3166-2 Code of the selected country. */ readonly country = model<string>(); /** * ISO_3166-2 Code of the country which shall be used on form-control reset. */ readonly defaultCountry = input<string>(); /** * Placeholder text for country search input. * * @defaultValue * ``` * t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SEARCH_PLACEHOLDER:Search`) * ``` */ readonly placeholderForSearch = input( t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SEARCH_PLACEHOLDER:Search`) ); /** * @defaultValue * ``` * t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SEARCH_NO-RESULTS_FOUND:No results found`) * ``` */ readonly searchNoResultsFoundLabel = input( t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SEARCH_NO-RESULTS_FOUND:No results found`) ); /** * Text for the country dropdown aria-label attribute. * * @defaultValue * ``` * t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SELECT_COUNTRY:Select country`) * ``` */ readonly selectCountryAriaLabel = input( t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.SELECT_COUNTRY:Select country`) ); /** * Text for the phone number input aria-label attribute. * * @defaultValue * ``` * t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.PHONE_NUMBER_INPUT_LABEL:Enter phone number`) * ``` */ readonly phoneNumberAriaLabel = input( t(() => $localize`:@@SI_PHONE_NUMBER_INPUT.PHONE_NUMBER_INPUT_LABEL:Enter phone number`) ); /** * List of countries in ISO2 format, from which the user is allowed to select one. * If no values are provided, the dropdown will show all known countries. */ readonly supportedCountries = input<readonly string[] | null>(); /** * @defaultValue * ``` * `${this.id()}-label` * ``` */ readonly labelledby = input(`${this.id()}-label`); /** @defaultValue false */ // eslint-disable-next-line @angular-eslint/no-input-rename readonly disabledInput = input(false, { alias: 'disabled', transform: booleanAttribute }); /** @defaultValue false */ readonly readonly = input(false, { transform: booleanAttribute }); readonly valueChange = output<PhoneDetails>(); /** * This ID will be bound to the `aria-describedby` attribute of the phone-number-input. * Use this to reference the element containing the error message(s) for the phone-number-input. * It will be picked by the {@link SiFormItemComponent} if the phone-number-input is used inside a form item. * * @defaultValue * ``` * `${this.id()}-errormessage` * ``` */ readonly errormessageId = input(`${this.id()}-errormessage`); protected readonly phoneInput = viewChild.required<ElementRef<HTMLInputElement>>('phoneInput'); protected selectedCountry?: CountryInfo; protected placeholder = ''; protected readonly countryFocused = signal(false); protected open = false; protected overlayWidth = 0; protected readonly disabled = computed(() => this.disabledInput() || this.disabledNgControl()); protected readonly countryList = computed(() => { const countries = this.allowedCountries() ?? this.phoneUtil.getSupportedRegions(); return countries .map((country: string) => ({ name: this.getCountryName(country), countryCode: this.phoneUtil.getCountryCodeForRegion(country), isoCode: country })) .sort((a: CountryInfo, b: CountryInfo) => a.name.localeCompare(b.name)); }); protected readonly icons = addIcons({ elementDown2 }); private readonly allowedCountries = computed( () => this.supportedCountries() ?? this.phoneUtil.getSupportedRegions() ); private readonly disabledNgControl = signal(false); private isValidNumber = true; private phoneNumber?: PhoneNumber; private onChange: (val: string) => void = () => {}; private onTouched: () => void = () => {}; ngOnChanges(changes: SimpleChanges): void { if (changes.country) { this.writeCountry(); } } /** @internal */ writeValue(value: string | undefined): void { this.phoneNumber = this.parseNumber(value); if (this.phoneNumber) { this.writeValueToInput(); this.country.set(this.getRegionCode()); } else { // Number could not be parsed, write raw value instead to handle cases like undefined this.writeTextToInput(value); this.country.set(this.defaultCountry() ?? this.country()); } this.writeCountry(); this.changeDetectorRef.markForCheck(); } /** @internal */ registerOnChange(fn: any): void { this.onChange = fn; } /** @internal */ registerOnTouched(fn: () => void): void { this.onTouched = fn; } /** @internal */ setDisabledState(isDisabled: boolean): void { this.disabledNgControl.set(isDisabled); } /** @internal */ validate(control: AbstractControl): ValidationErrors | null { if (!this.phoneInput().nativeElement.value) { return null; } this.isValidNumber = false; if (!this.phoneNumber || !this.phoneUtil.isValidNumber(this.phoneNumber)) { return { invalidPhoneNumberFormat: true }; } if (!this.countryList().some(c => c.isoCode === this.selectedCountry!.isoCode)) { return { notSupportedPhoneNumberCountry: true }; } this.isValidNumber = true; return null; } protected input(): void { const rawNumber = this.phoneInput().nativeElement.value; this.phoneNumber = this.parseNumber(rawNumber); if (this.phoneNumber) { const regionCode = this.getRegionCode(); let countryInfo = this.countryList().find(country => regionCode === country.isoCode); if (!countryInfo && regionCode) { countryInfo = { name: this.getCountryName(regionCode), countryCode: this.phoneNumber.getCountryCode()!, isoCode: regionCode }; } if (countryInfo && this.selectedCountry?.isoCode !== countryInfo.isoCode) { this.selectedCountry = countryInfo; } } else IEif (rawNumber.trim().startsWith('+')) { this.selectedCountry = undefined; } this.handleChange(); } protected blur(): void { this.countryFocused.set(false); this.onTouched(); this.writeValueToInput(); this.valueChange.emit({ country: this.selectedCountry, phoneNumber: this.formatPhoneNumber(PhoneNumberFormat.INTERNATIONAL), isValid: this.isValidNumber }); } protected countryInput(num: CountryInfo): void { this.selectedCountry = num; this.updatePlaceholder(); this.refreshValueAfterCountryChange(); this.handleChange(); } protected openOverlay(): void { if (!this.readonly()) { this.open = true; this.overlayWidth = this.elementRef.nativeElement.getBoundingClientRect().width + 2; // 2px border } } protected overlayDetach(): void { this.open = false; this.phoneInput().nativeElement.focus(); } protected valueProvider(country: CountryInfo): string { return `${country.name} +${country.countryCode}`; } private writeCountry(): void { const currentCountry = this.country()!; this.selectedCountry = this.countryList().find(country => country.isoCode === currentCountry); if (!this.selectedCountry) { const countryCode = this.phoneUtil.getCountryCodeForRegion( currentCountry ?? this.defaultCountry() ?? 'XX' ); if (countryCode) { this.selectedCountry = { isoCode: currentCountry, countryCode, name: this.getCountryName(currentCountry) }; } } this.updatePlaceholder(); this.refreshValueAfterCountryChange(); } private getCountryName(countryCode: string): string { // This auto translates the given country name to the selected locale language return ( new Intl.DisplayNames([this.translate.currentLanguage], { type: 'region' }).of( countryCode.toUpperCase() ) ?? '' ); } private updatePlaceholder(): void { if (this.selectedCountry) { this.placeholder = this.phoneUtil .format( this.phoneUtil.getExampleNumber(this.selectedCountry.isoCode), PhoneNumberFormat.NATIONAL ) .replace(/^0/, ''); } } private parseNumber(rawNumber: string | undefined): PhoneNumber | undefined { try { let regionCodeForParsing: string | undefined; if (!rawNumber?.trim().startsWith('+')) { regionCodeForParsing = this.selectedCountry?.isoCode; } return this.phoneUtil.parse(rawNumber, regionCodeForParsing); } catch (e) { // The Number is too short, we cannot parse it yet. Error can be ignored. Hopefully, the user enters more digits. return; } } /** * PhoneUtil does not resolve country code early enough when the national prefix is shared among other countries (+1 and +44). * This Method fakes a complete number to force PhoneUtil returning a proper region code. */ private getRegionCode(): string | undefined { if (this.phoneNumber) { const regionCode = this.phoneUtil.getRegionCodeForNumber(this.phoneNumber); if (regionCode) { return regionCode; } const nationalNumber = this.phoneNumber.getNationalNumber() + ''; if ( // USA, CANADA, ... (this.phoneNumber.getCountryCode() === 1 && nationalNumber.length >= 3) || // UK, ... (this.phoneNumber.getCountryCode() === 44 && nationalNumber.length >= 4) ) { return this.phoneUtil.getRegionCodeForNumber( this.phoneUtil.parse( '+' + this.phoneNumber.getCountryCode() + nationalNumber + new Array(10 - nationalNumber.length).fill(5).join('') ) ); } return this.phoneUtil.getRegionCodeForCountryCode(this.phoneNumber.getCountryCode()!); } return undefined; } private formatPhoneNumber(format: PhoneNumberFormat): string | undefined { if (this.phoneNumber) { return this.phoneUtil.format(this.phoneNumber, format); } return undefined; } private handleChange(): void { if (this.selectedCountry && this.country() !== this.selectedCountry?.isoCode) { this.country.set(this.selectedCountry?.isoCode); } if (this.phoneNumber) { this.onChange(this.formatPhoneNumber(PhoneNumberFormat.INTERNATIONAL)!); } else { this.onChange(''); } } private writeTextToInput(value?: string): void { this.phoneInput().nativeElement.value = value ?? ''; } /** * Format and update input text or clear input text if the input value is undefined. */ private writeValueToInput(): void { if (this.phoneNumber) { this.writeTextToInput(this.formatPhoneNumber(PhoneNumberFormat.NATIONAL)!.replace(/^0/, '')); } } private refreshValueAfterCountryChange(): void { if (this.selectedCountry) { this.phoneNumber?.setCountryCode(this.selectedCountry?.countryCode); this.writeValueToInput(); } } } |