import { ChangeDetectionStrategy, Component, computed, ElementRef, input, signal, viewChild, } from '@angular/core'; import { NgClass } from '@angular/common'; import { CnPipe } from '../../ui/cn.pipe'; import { transformToBoolean } from '../../ui/utils'; import { BaseInput } from '../base-input.directive'; import { ControlErrorDirective } from '../control-error.directive'; import { ControlFeedbackDirective } from '../control-feedback.directive'; @Component({ selector: 'app-date-picker', templateUrl: './date-picker.component.html', styleUrls: ['./date-picker.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [NgClass, ControlFeedbackDirective, ControlErrorDirective, CnPipe], }) export class DatePickerComponent extends BaseInput { showLabel = input(false, { transform: transformToBoolean }); dateMin = input(''); dateMax = input(''); dateInput = viewChild>('dateInput'); isFocused = signal(false); displayValue = computed(() => { const value = this.value(); if (!value) return ''; const date = new Date(`${value}T00:00:00`); if (Number.isNaN(date.getTime())) return value; return date.toLocaleDateString('es-MX', { day: '2-digit', month: '2-digit', year: 'numeric', }); }); openPicker() { if (this.isDisabled() || this.readonly()) return; const input = this.dateInput()?.nativeElement; if (!input) return; try { input.showPicker(); } catch { input.focus(); input.click(); } } onContainerClick() { this.openPicker(); } onKeydown(event: KeyboardEvent) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); this.openPicker(); } } onDateChange(event: Event) { if (this.readonly()) { return; } const input = event.target as HTMLInputElement; const selectedValue = input.value; const minValue = this.dateMin(); const maxValue = this.dateMax(); if (minValue && selectedValue && selectedValue < minValue) { input.value = ''; this.value.set('' as string); return; } if (maxValue && selectedValue && selectedValue > maxValue) { input.value = ''; this.value.set('' as string); return; } this.value.set(selectedValue); } onFocus() { this.isFocused.set(true); } override onBlur() { this.isFocused.set(false); super.onBlur(); } }