dateRangePickerUtils.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Pure helpers for the SearchDateRangePicker hook.
  3. *
  4. * Goals:
  5. * - Keep the hook smaller and focused on React state/effects.
  6. * - Keep complex logic testable without rendering.
  7. */
  8. export function normalizeDayClickArgs(args) {
  9. // react-day-picker handler signatures have differed across versions.
  10. // We normalize both of these variants:
  11. // - onDayClick(day, modifiers, event)
  12. // - onDayClick(event, day, modifiers)
  13. //
  14. // Background:
  15. // - There has been historical ambiguity around onDayClick argument order. :contentReference[oaicite:2]{index=2}
  16. const a0 = args?.[0];
  17. const a1 = args?.[1];
  18. const a2 = args?.[2];
  19. if (a0 instanceof Date) return { day: a0, modifiers: a1 || null };
  20. if (a1 instanceof Date) return { day: a1, modifiers: a2 || null };
  21. return { day: null, modifiers: null };
  22. }
  23. export function buildCalendarState({ fromDate, toDate, isRangeInvalid }) {
  24. let calendarSelected = undefined;
  25. let invalidInterval = null;
  26. if (fromDate && toDate) {
  27. if (isRangeInvalid) {
  28. const min = fromDate < toDate ? fromDate : toDate;
  29. const max = fromDate < toDate ? toDate : fromDate;
  30. calendarSelected = { from: min, to: max };
  31. invalidInterval = { from: min, to: max };
  32. } else {
  33. calendarSelected = { from: fromDate, to: toDate };
  34. }
  35. } else if (fromDate) {
  36. calendarSelected = { from: fromDate, to: undefined };
  37. } else if (toDate) {
  38. // "to only" -> visually represent as a single-day range
  39. calendarSelected = { from: toDate, to: toDate };
  40. }
  41. const calendarModifiers =
  42. isRangeInvalid && invalidInterval
  43. ? {
  44. invalid_range: invalidInterval,
  45. invalid_range_edge: [fromDate, toDate].filter(Boolean),
  46. }
  47. : undefined;
  48. const calendarModifiersClassNames =
  49. isRangeInvalid && invalidInterval
  50. ? {
  51. invalid_range:
  52. "bg-destructive/10 text-destructive dark:bg-destructive/20 dark:text-destructive",
  53. invalid_range_edge:
  54. "!bg-destructive !text-white hover:!bg-destructive/90",
  55. }
  56. : undefined;
  57. return { calendarSelected, calendarModifiers, calendarModifiersClassNames };
  58. }