UNPKG

@cerberus-design/react

Version:

The Cerberus Design React component library.

104 lines (99 loc) 2.58 kB
'use client'; 'use strict'; Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); const React = require('react'); function useDate(options) { const initialValue = options?.initialValue ?? ""; const format = options?.format ?? DateFormats.USMilitary; const onChange = options?.onChange; const [value, setValue] = React.useState(initialValue); const handleChange = React.useCallback( (e) => { const newValue = formatMilitaryDate(e.currentTarget.value); if (onChange) onChange(e); setValue(newValue); }, [onChange] ); return React.useMemo( () => ({ format, value, ISO: formatMilitaryToISO(value), onChange: handleChange }), [format, value, handleChange] ); } function formatMilitaryToISO(input) { const [day, month, year] = input.split(" "); const monthIndex = MONTHS.findIndex((m) => m.startsWith(month)); const monthNum = monthIndex + 1; return `${year ?? "0000"}-${monthNum.toString().padStart(2, "0")}-${day.padStart( 2, "0" )}`; } function formatMilitaryDate(input) { let formatted = input.toUpperCase().replace(/[^0-9A-Z]/g, ""); let day = ""; let month = ""; let year = ""; if (formatted.length >= 2) { day = formatted.replace(/[^0-9]/g, "").slice(0, 2); const dayNum = parseInt(day, 10); if (dayNum > 31) day = "31"; else if (dayNum === 0) day = "01"; formatted = formatted.slice(2); } if (formatted.length >= 3) { month = formatted.slice(0, 3); const monthIndex = MONTHS.findIndex((m) => m.startsWith(month)); if (monthIndex !== -1) { month = MONTHS[monthIndex]; } else { month = month.replace(/[^A-Z]/g, ""); } formatted = formatted.slice(3); } if (formatted.length > 0) { year = formatted.slice(0, 4); } return [day, month, year].filter(Boolean).join(" "); } function formatISOToMilitary(date) { const [year, month, day] = date.split("-"); const monthIndex = parseInt(month, 10) - 1; const monthStr = MONTHS[monthIndex]; return `${day} ${monthStr} ${year}`; } const DateFormats = { get ISO() { return "YYYY-MM-DD"; }, get USMilitary() { return "DD MMM YYYY"; }, get Months() { return MONTHS; } }; const MONTHS = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ]; exports.DateFormats = DateFormats; exports.formatISOToMilitary = formatISOToMilitary; exports.formatMilitaryDate = formatMilitaryDate; exports.formatMilitaryToISO = formatMilitaryToISO; exports.useDate = useDate;