import { i18n } from '@osd/i18n' ; import { memoize , noop } from 'lodash' ; import moment from 'moment' ; import { FieldFormat , OSD_FIELD_TYPES , FIELD_FORMAT_IDS } from '../../../common' ; import { TextContextTypeConvert } from '../../../common/field_formats/types' ; export class DateFormat extends FieldFormat { static id = FIELD_FORMAT_IDS . DATE ; static title = i18n . translate ( 'data.fieldFormats.date.title' , { defaultMessage : 'Date' , } ) ; static fieldType = OSD_FIELD_TYPES . DATE ; private memoizedConverter : Function = noop ; private memoizedPattern : string = '' ; private timeZone : string = '' ; getParamDefaults ( ) { return { pattern : this . getConfig ! ( 'dateFormat' ) , timezone : this . getConfig ! ( 'dateFormat:tz' ) , } ; } textConvert : TextContextTypeConvert = ( val ) => { const pattern = this . param ( 'pattern' ) ; const timezone = this . param ( 'timezone' ) ; const timezoneChanged = this . timeZone !== timezone ; const datePatternChanged = this . memoizedPattern !== pattern ; if ( timezoneChanged || datePatternChanged ) { this . timeZone = timezone ; this . memoizedPattern = pattern ; this . memoizedConverter = memoize ( function converter ( value ) { if ( value === null || value === undefined ) { return '-' ; } const date = moment ( value ) ; if ( date . isValid ( ) ) { return date . format ( pattern ) ; } else { return value ; } } ) ; } return this . memoizedConverter ( val ) ; } ; }