import { globalState } from '../../../app/global-state'; import PowerduckState from '../../../app/powerduck-state'; import { PortalUtils } from '../../../common/utils/utils'; export enum DateInputUsage { DatetimePicker = 0, DaterangePicker = 1, } export default class DateInputHelper { static useNativeElement(showTime: boolean): boolean { if (!globalState.windowExists) { return true; } return ( DateInputHelper.nativeSupported(showTime) && (PortalUtils.isTouchDevice() || globalState.cordova != null) ); } static getLocale(): string { const locale = PowerduckState.getCurrentLanguage(); if (locale == 'en' && globalState.windowExists) { const navigatorLang = navigator.language || (navigator as any).userLanguage; if (navigatorLang != null && navigatorLang.indexOf('en-') == 0) { return navigatorLang; } } return locale; } static nativeSupported(showTime: boolean): boolean { const inputType = this.getNativeInputType(showTime); const cacheKey = `${inputType}-supported`; const cachedValue = this.getValueFromCache(cacheKey); if (cachedValue != null) { return cachedValue; } const el = document.createElement('input'); const notADateValue = 'not-a-date'; el.setAttribute('type', inputType); el.setAttribute('value', notADateValue); const retVal = !(el.value === notADateValue); this.cacheValue(cacheKey, retVal); return retVal; } static getNativeInputType(showTime: boolean): string { return showTime ? 'datetime-local' : 'date'; } static getDtpDateFormat(showTime: boolean, usage: DateInputUsage): string { const locale = this.getLocale(); const cacheKey = `format-${locale}-${(showTime == true).toString()}-${usage.toString()}`; const cachedValue = this.getValueFromCache(cacheKey); if (cachedValue != null) { return cachedValue; } // eslint-disable-next-line no-restricted-syntax const date = new Date(Date.UTC( 1990, 9, 11, 12, 20, 30, )); const options: any = { year: 'numeric', month: '2-digit', day: 'numeric', timeZone: 'UTC', }; if (showTime) { options.hour = '2-digit'; options.minute = '2-digit'; // options.second = '2-digit'; } const retVal = date .toLocaleDateString(locale, options) .split('. ') .join('.') .split(',') .join(' ') .split('1990') .join('yyyy') .split('10') .join('mm') .split('11') .join('dd') .split('12') .join('hh') .split('20') .join('ii') .split('30') .join('ss') .split('AM') .join('') .split('PM') .join('') .split('yyyyhh') .join('yyyy hh'); this.cacheValue(cacheKey, retVal); return retVal; } static getStartOfWeek(): number { return 1; } private static getValueFromCache(key: string): any { if (globalState._DateTimePickerCache == null) { globalState._DateTimePickerCache = {}; } return globalState._DateTimePickerCache[key]; } private static cacheValue(key: string, value: any): void { if (globalState._DateTimePickerCache == null) { globalState._DateTimePickerCache = {}; } return (globalState._DateTimePickerCache[key] = value); } }