4
0

calendarMonthQuery.js 765 B

1234567891011121314151617181920212223242526
  1. const MONTH_QUERY_PATTERN = /^(\d{4})-(\d{2})$/
  2. export function formatCalendarMonthQuery (monthIndex, year) {
  3. return `${String(year).padStart(4, '0')}-${String(monthIndex + 1).padStart(2, '0')}`
  4. }
  5. // Falls back to the month of `today` so that a missing or hand-edited bad value still shows a calendar.
  6. export function parseCalendarMonthQuery (value, today = new Date()) {
  7. const fallback = { monthIndex: today.getMonth(), year: today.getFullYear() }
  8. if (typeof value !== 'string') {
  9. return fallback
  10. }
  11. const match = MONTH_QUERY_PATTERN.exec(value)
  12. if (!match) {
  13. return fallback
  14. }
  15. const monthIndex = Number(match[2]) - 1
  16. if (monthIndex < 0 || monthIndex > 11) {
  17. return fallback
  18. }
  19. return { monthIndex, year: Number(match[1]) }
  20. }