Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

3.4 KB
Raw Blame
import React from "react";

import { useDateTimeConfig } from "@/lib/datetime/client";
import { formatDateParts, formatDateTime } from "@/lib/datetime/format";
import { dayjs } from "@/lib/dayjs";

interface DayProps {
  date: Date;
  day: string;
  weekend: boolean;
  outOfMonth: boolean;
  today: boolean;
  isPast: boolean;
  selected: boolean;
}

interface HeadlessDatePickerOptions {
  onSelectionChange?: (selection: Date[]) => void;
  date?: Date;
  selection?: Date[];
  onNavigationChange?: (date: Date) => void;
}

const today = new Date();

export const useHeadlessDatePicker = (
  options?: HeadlessDatePickerOptions,
): {
  label: string;
  next: () => void;
  prev: () => void;
  today: () => void;
  daysOfWeek: string[];
  days: DayProps[];
  navigationDate: Date;
  selection: Date[];
  toggle: (date: Date) => void;
} => {
  const { locale, weekStart } = useDateTimeConfig();
  const [localSelection, setSelection] = React.useState<Date[]>([]);
  const selection = options?.selection ?? localSelection;
  const [localNavigationDate, setNavigationDate] = React.useState(today);
  const navigationDate = dayjs(options?.date ?? localNavigationDate);

  const firstDayOfMonth = navigationDate.startOf("month");
  // dayjs's startOf("week") depends on the global locale; shift explicitly so
  // the grid follows the viewer's week start.
  const firstDayOfFirstWeek = firstDayOfMonth.subtract(
    (firstDayOfMonth.day() - weekStart + 7) % 7,
    "days",
  );

  const currentMonth = navigationDate.get("month");

  const days: DayProps[] = [];

  const daysOfWeek: string[] = [];

  for (let i = 0; i < 7; i++) {
    daysOfWeek.push(
      formatDateParts(firstDayOfFirstWeek.add(i, "days").toDate(), { locale })
        .weekday,
    );
  }

  let reachedEnd = false;
  let i = 0;
  do {
    const d = firstDayOfFirstWeek.add(i, "days");
    days.push({
      date: d.toDate(),
      day: formatDateParts(d.toDate(), { locale }).day,
      weekend: d.day() === 0 || d.day() === 6,
      outOfMonth: d.month() !== currentMonth,
      today: d.isSame(today, "day"),
      selected: selection.some((selectedDate) => d.isSame(selectedDate, "day")),
      isPast: d.isBefore(today, "day"),
    });
    i++;
    reachedEnd =
      i > 34 && i % 7 === 0 && d.add(1, "day").month() !== currentMonth;
  } while (reachedEnd === false);

  return {
    navigationDate: navigationDate.toDate(),
    label: formatDateTime(navigationDate.toDate(), {
      preset: "monthYear",
      locale,
    }),
    next: () => {
      const newDate = navigationDate.add(1, "month").startOf("month").toDate();
      if (!options?.date) {
        setNavigationDate(newDate);
      }
      options?.onNavigationChange?.(newDate);
    },
    prev: () => {
      const newDate = navigationDate.add(-1, "month").startOf("month").toDate();
      if (!options?.date) {
        setNavigationDate(newDate);
      }
      options?.onNavigationChange?.(newDate);
    },
    today: () => {
      const newDate = today;
      if (!options?.date) {
        setNavigationDate(newDate);
      }
      options?.onNavigationChange?.(newDate);
    },
    days,
    daysOfWeek,
    selection: options?.selection ?? selection,
    toggle: (date) => {
      if (options?.selection) {
        // ignore, selection is controlled externally
        return;
      }
      const index = selection.indexOf(date);
      if (index === -1) {
        setSelection((s) => [...s, date]);
      } else {
        setSelection((s) => s.splice(index, 1));
      }
    },
  };
};