import {useState, useRef, useEffect} from '@wordpress/element'; import {Popover} from '@wordpress/components'; import {__} from '@wordpress/i18n'; import {format, parse, parseISO, isValid, startOfMonth} from 'date-fns'; import {enUS} from 'date-fns/locale'; import {dateI18n, getSettings} from '@wordpress/date'; import CalendarPopover from './CalendarPopover'; import TextInput from './TextInput'; const {dateFormat} = window.adpressoAnalyticsData || {dateFormat: 'F j, Y'}; // PHP date tokens a site date format may use, as date-fns parse tokens. "S" (ordinal suffix) is stripped from the input. const PHP_TOKENS = {d: 'dd', j: 'd', S: '', D: 'EEE', l: 'EEEE', m: 'MM', n: 'M', F: 'MMMM', M: 'MMM', Y: 'yyyy', y: 'yy'}; /** * The site's PHP date format as a date-fns format, or null when it uses tokens we do not parse (times, timezones). * * @param {string} php * @returns {string|null} */ export const phpFormatToDateFns = ( php ) => { let out = ''; for ( let i = 0; i < php.length; i++ ) { const char = php[i]; if ( char === '\\' ) { i++; if ( i < php.length ) { out += `'${php[i]}'`; } } else if ( Object.prototype.hasOwnProperty.call( PHP_TOKENS, char ) ) { out += PHP_TOKENS[char]; } else if ( /[a-z]/i.test( char ) ) { return null; } else { out += char === '\'' ? '\'\'' : char; } } return out; }; const englishNames = ( kind, width ) => Array.from( {length: kind === 'month' ? 12 : 7}, ( _, i ) => enUS.localize[kind]( i, {width} ) ); // Month and weekday names as WordPress prints them for this site, replaced by their English names so date-fns can parse them. const toEnglishNames = ( text ) => { const l10n = getSettings().l10n || {}; const pairs = [ [l10n.months, englishNames( 'month', 'wide' )], [l10n.monthsShort, englishNames( 'month', 'abbreviated' )], [l10n.weekdays, englishNames( 'day', 'wide' )], [l10n.weekdaysShort, englishNames( 'day', 'abbreviated' )] ]; return pairs.reduce( ( out, [localized = [], english] ) => localized.reduce( ( acc, name, i ) => { if ( !name || !english[i] || name === english[i] ) { return acc; } return acc.replace( new RegExp( name.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' ), 'i' ), english[i] ); }, out ), text ); }; /** * The date a user typed, as ISO (2026-03-05) or in the site's date format, else null. * * @param {string} text * @param {string} phpFormat * @returns {Date|null} */ export const parseTypedDate = ( text, phpFormat = dateFormat ) => { const trimmed = ( text || '' ).trim(); if ( !trimmed ) { return null; } const candidates = []; if ( /^\d{4}-\d{2}-\d{2}$/.test( trimmed ) ) { candidates.push( parseISO( trimmed ) ); } const fnsFormat = phpFormatToDateFns( phpFormat ); if ( fnsFormat ) { try { candidates.push( parse( toEnglishNames( trimmed ).replace( /(\d)(st|nd|rd|th)\b/gi, '$1' ), fnsFormat, new Date() ) ); } catch ( e ) { // Unparseable format: ISO input still works. } } return candidates.find( ( date ) => isValid( date ) && date.getFullYear() >= 1970 && date.getFullYear() <= 2100 ) || null; }; const toDisplay = ( date ) => date ? dateI18n( dateFormat, format( date, 'yyyy-MM-dd\'T\'12:00:00' ) ) : ''; const rangeFromValue = ( value ) => { if ( !value || typeof value !== 'object' || !value.start || !value.end ) { return undefined; } const from = parseISO( value.start ); const to = parseISO( value.end ); return isValid( from ) && isValid( to ) ? {from, to} : undefined; }; const DateRangePicker = ( {value, onChange, className = ''} ) => { const [isCalendarOpen, setIsCalendarOpen] = useState( false ); const [draftRange, setDraftRange] = useState( undefined ); const [month, setMonth] = useState( startOfMonth( new Date() ) ); const [startText, setStartText] = useState( '' ); const [endText, setEndText] = useState( '' ); // The field being typed in keeps its text; the other one follows the calendar. const editingRef = useRef( null ); const anchorRef = useRef( null ); const currentRange = () => ( isCalendarOpen ? draftRange : rangeFromValue( value ) ); useEffect( () => { const range = isCalendarOpen ? draftRange : rangeFromValue( value ); if ( editingRef.current !== 'start' ) { setStartText( toDisplay( range?.from ) ); } if ( editingRef.current !== 'end' ) { setEndText( toDisplay( range?.to ) ); } }, [isCalendarOpen, draftRange, value] ); const showRange = ( range ) => { setDraftRange( range ); if ( range?.from ) { setMonth( startOfMonth( range.from ) ); } setIsCalendarOpen( true ); }; const openCalendar = () => { if ( !isCalendarOpen ) { showRange( rangeFromValue( value ) ); } }; const handleTyped = ( side, text ) => { editingRef.current = side; ( side === 'start' ? setStartText : setEndText )( text ); const base = currentRange() || {}; const date = parseTypedDate( text ); if ( !date ) { openCalendar(); return; } if ( side === 'start' ) { showRange( {from: date, to: base.to && base.to >= date ? base.to : undefined} ); } else { showRange( {from: base.from && base.from <= date ? base.from : date, to: date} ); } }; const handleBlur = () => { editingRef.current = null; const range = currentRange(); setStartText( toDisplay( range?.from ) ); setEndText( toDisplay( range?.to ) ); }; const handleApply = () => { if ( !draftRange || !draftRange.from || !draftRange.to ) { return; } const apiStart = format( draftRange.from, 'yyyy-MM-dd' ); const apiEnd = format( draftRange.to, 'yyyy-MM-dd' ); onChange( { key: 'custom', start: apiStart, end: apiEnd, label: `${toDisplay( draftRange.from )} - ${toDisplay( draftRange.to )}` } ); editingRef.current = null; setIsCalendarOpen( false ); }; const handleKeyDown = ( event ) => { if ( event.key === 'Enter' ) { event.preventDefault(); handleApply(); } else if ( event.key === 'Escape' ) { setIsCalendarOpen( false ); } }; const dynamicPlaceholder = dateI18n( dateFormat, new Date() ); return (