import { Components } from '@formio/js'; import { Utils as FormioUtils } from '@formio/js'; import { FieldError } from '@formio/core'; import * as _ from 'lodash'; import moment from 'moment'; import TimeHelper from '../util/TimeHelper'; import { GDSDatetimeComponentSchema } from '../../types'; const Field = Components.components.field; const Day = Components.components.day; export default class GDSDatetimeComponent extends Day { declare component: GDSDatetimeComponentSchema; declare refs: { hour: HTMLInputElement; minute: HTMLInputElement; day: HTMLInputElement; month: HTMLInputElement; year: HTMLInputElement; input: HTMLInputElement[]; }; declare dataValue: string; declare data: Record; declare validators: string[]; declare shouldDisabled: boolean; declare triggerChange: (flags?: Record) => void; // eslint-disable-next-line @typescript-eslint/no-explicit-any declare interpolateErrors: (errors: any[]) => any[]; get format(): string { return 'DD-MM-YYYY'; } get defaultValue(): string { let defaultValue = this.component.defaultValue; if (!defaultValue && this.component.defaultDate) { defaultValue = FormioUtils.getDateSetting(this.component.defaultDate); defaultValue = defaultValue ? moment(defaultValue).format() : ''; } return defaultValue ?? ''; } get emptyValue(): null { return null; } get parts(): { day: string | null; month: string | null; year: string | null; hour: string | null; minute: string | null } { return { day: this.getFieldValue('day'), month: this.getFieldValue('month'), year: this.getFieldValue('year'), hour: this.getFieldValue('hour'), minute: this.getFieldValue('minute'), }; } private timeHelper: TimeHelper = new TimeHelper(); // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public attach(element: any): Promise { this.loadRefs(element, { hour: 'single', minute: 'single' }); this.addEventListener(this.refs.hour, 'input', () => { this.timeHelper.checkAndValidateHour(this.refs.hour); this.setPristine(false); this.updateValue(null, { modified: true }); this.checkComponentValidity(this.data, true); this.triggerChange({ dirty: true }); }); this.addEventListener(this.refs.minute, 'input', () => { this.timeHelper.checkAndValidateMinutes(this.refs.minute); this.setPristine(false); this.updateValue(null, { modified: true }); this.checkComponentValidity(this.data, true); this.triggerChange({ dirty: true }); }); this.addEventListener(this.refs.hour, 'keypress', this.timeHelper.preventNonNumericKeyPress); this.addEventListener(this.refs.minute, 'keypress', this.timeHelper.preventNonNumericKeyPress); if (this.shouldDisabled) { this.setDisabled(this.refs.hour, true); this.setDisabled(this.refs.minute, true); } const superAttach = super.attach(element); this.addEventListener(this.refs.year, 'keypress', this.timeHelper.preventNonNumericKeyPress); this.addEventListener(this.refs.month, 'keypress', this.timeHelper.preventNonNumericKeyPress); this.addEventListener(this.refs.day, 'keypress', this.timeHelper.preventNonNumericKeyPress); this.addEventListener(this.refs.year, 'input', () => { this.timeHelper.validateDateInput(this.refs.year, 4); this.setPristine(false); this.updateValue(null, { modified: true }); this.checkComponentValidity(this.data, true); this.triggerChange({ dirty: true }); }); this.addEventListener(this.refs.day, 'input', () => { this.timeHelper.validateDateInput(this.refs.day, 2); this.setPristine(false); this.updateValue(null, { modified: true }); this.checkComponentValidity(this.data, true); this.triggerChange({ dirty: true }); }); this.addEventListener(this.refs.month, 'input', () => { this.timeHelper.validateDateInput(this.refs.month, 2); this.setPristine(false); this.updateValue(null, { modified: true }); this.checkComponentValidity(this.data, true); this.triggerChange({ dirty: true }); }); return superAttach; } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public t(text: any, ...args: any[]): any { const keyMap: Record = { invalidDate: 'invalid_date', }; return super.t(keyMap[text] ?? text, ...args); } public init(): void { super.init(); this.validators = (this.validators || []).filter((v) => v !== 'day').concat(['date']); this.component.maxDate = this.component.datePicker?.maxDate ?? undefined; this.component.minDate = this.component.datePicker?.minDate ?? undefined; this.component.suffix = null; // `` is invalid; datetime parts are numeric inputs. this.component.fields.month.type = 'number'; this.component.fields.day.required = this.component.validate?.required; this.component.fields.month.required = this.component.validate?.required; this.component.fields.year.required = this.component.validate?.required; this.component.fields.hour = { type: 'number', placeholder: 'HH', required: this.component.validate?.required, }; this.component.fields.minute = { type: 'number', placeholder: 'MM', required: this.component.validate?.required, }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public setErrorClasses(elements: any, dirty: any, hasError: any): void { super.setErrorClasses([this.refs.hour, this.refs.minute, ...elements], dirty, hasError); } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public removeInputError(elements: any): void { super.removeInputError([this.refs.hour, this.refs.minute, ...elements]); } public render(): string { return Field.prototype.render.call(this, this.renderTemplate('datetime', { component: this.component, dataValue: this.dataValue, day: this.renderField('day'), month: this.renderField('month'), year: this.renderField('year'), hour: this.renderField('hour'), minute: this.renderField('minute'), })); } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public getDate(value: any): string | null { const defaults: Array = []; const [DAY, MONTH, YEAR, HOUR, MINUTE] = [0, 1, 2, 3, 4]; const defaultValue = value || this.component.defaultValue; if (defaultValue) { try { const defaultDate = moment(defaultValue); defaults[DAY] = defaultDate.format('DD'); defaults[MONTH] = defaultDate.format('MM'); defaults[YEAR] = defaultDate.format('YYYY'); defaults[HOUR] = defaultDate.format('HH'); defaults[MINUTE] = defaultDate.format('mm'); } catch { // ignored } } const day: number = this.processField('day', defaults, DAY); const month: number = this.processField('month', defaults, MONTH); const year: number = this.processField('year', defaults, YEAR); const hour: number = this.processField('hour', defaults, HOUR); const minute: number = this.processField('minute', defaults, MINUTE); // processField() returns 0 for blank inputs const hourInputEmpty = this.refs.hour?.value === ''; const minuteInputEmpty = this.refs.minute?.value === ''; const yearInputEmpty = this.refs.year?.value === ''; const dayInputEmpty = this.refs.day?.value === ''; const monthInputEmpty = this.refs.month?.value === ''; const allDateEmpty = !day && !month && !year; const allTimeEmpty = hourInputEmpty && minuteInputEmpty; if (allDateEmpty && allTimeEmpty) { return null; } // A partial date returns the sentinel, so both "required" and "invalid date" show (as in v2) if (yearInputEmpty || dayInputEmpty || monthInputEmpty) { return 'Invalid date'; } const dayStr = day.toString().padStart(2, '0'); const monthStr = month.toString().padStart(2, '0'); const yearStr = year.toString().padStart(4, '0'); const hourStr = hour.toString().padStart(2, '0'); const minuteStr = minute.toString().padStart(2, '0'); const toMoment = moment(`${yearStr}-${monthStr}-${dayStr} ${hourStr}:${minuteStr}`, 'YYYY-MM-DD HH:mm'); return toMoment.format(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public getFieldValue(name: any): string | null { if (this.dataValue && this.dataValue !== 'Invalid date') { try { let val: string | null = null; const date = moment(this.dataValue, 'YYYY-MM-DD HH:mm'); switch (name) { case 'month': val = date.format('MM'); break; case 'day': val = date.format('DD'); break; case 'year': val = date.format('YYYY'); break; case 'hour': val = date.format('HH'); break; case 'minute': val = date.format('mm'); break; } return val; } catch { return null; } } return null; } public boolValue(value: unknown): boolean { if (_.isBoolean(value)) { return value; } else if (_.isString(value)) { return (value.toLowerCase() === 'true'); } else { return !!value; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public setValueAt(_index: number, value: any): void { // Temporary: avoids resetting the inputs on an invalid date if (!value || value === 'Invalid date') { return; } const date = moment(value, moment.ISO_8601); if (date.isValid()) { if (this.refs.day) { this.refs.day.value = date.format('DD'); } if (this.refs.month) { this.refs.month.value = date.format('MM'); } if (this.refs.year) { this.refs.year.value = date.format('YYYY'); } if (this.refs.hour) { this.refs.hour.value = date.format('HH'); } if (this.refs.minute) { this.refs.minute.value = date.format('mm'); } } } public getValueAt(index: number): string | null { const date = this.date; if (date) { this.refs.input[index].value = date; return this.refs.input[index].value; } else { this.refs.input[index].value = ''; return null; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public normalizeValue(value: any): any { return value; } // eslint-disable-next-line @typescript-eslint/no-explicit-any get validationValue(): any { if (this.dataValue === 'Invalid date') { return null; } if (this.component.enableTime && (this.refs?.hour?.value === '' || this.refs?.minute?.value === '')) { return null; } return this.dataValue; } // eslint-disable-next-line @typescript-eslint/no-explicit-any public validateComponent(data: any = null, row: any = null, flags: any = {}): any { const errors = super.validateComponent(data, row, flags); if (this.dataValue === 'Invalid date') { // eslint-disable-next-line @typescript-eslint/no-explicit-any const alreadyAdded = Array.isArray(errors) && (errors as any[]).some( // eslint-disable-next-line @typescript-eslint/no-explicit-any (e: any) => e?.errorKeyOrMessage === 'invalidDate' || e?.ruleName === 'date', ); if (!alreadyAdded) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const context: any = { component: this.component, data: data || this.rootValue, row: row || this.data, value: this.dataValue, instance: this, // eslint-disable-next-line @typescript-eslint/no-explicit-any path: (this as any).path || this.component.key, // eslint-disable-next-line @typescript-eslint/no-explicit-any form: this.root ? (this.root as any)._form : {}, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const rawError = new FieldError('invalidDate', context as any, 'date'); const [interpolated] = this.interpolateErrors([rawError]); // eslint-disable-next-line @typescript-eslint/no-explicit-any (errors as any[]).push(interpolated); } } return errors; } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types public validateRequired(setting: any, value: any): boolean { const { day, month, year, minute, hour } = this.parts; if (this.component.validate?.required && (!day || parseInt(day, 10) === 0)) { return false; } if (this.component.validate?.required && (!month || parseInt(month, 10) === 0)) { return false; } if (this.component.validate?.required && (!year || parseInt(year, 10) === 0)) { return false; } if (this.component.validate?.required && (this.refs.minute.value === '' || !minute)) { return false; } if (this.component.validate?.required && (this.refs.hour.value === '' || !hour)) { return false; } if (!this.boolValue(setting)) { return true; } return !this.isEmpty(value); } private processField(field: string, defaults: Array, fieldIndex: number): number { const refKey = field as keyof typeof this.refs; const ref = this.refs[refKey]; const inputRef = ref instanceof HTMLInputElement ? ref : undefined; let fieldValue: number | undefined = inputRef ? parseInt(inputRef.value, 10) : undefined; if (fieldValue === undefined || _.isNaN(fieldValue)) { fieldValue = defaults[fieldIndex] && !_.isNaN(defaults[fieldIndex]) ? Number(defaults[fieldIndex]) : 0; } return fieldValue; } }