Untitled

mail@pastecode.io avatar
unknown
plain_text
13 days ago
4.6 kB
3
Indexable
Never
"use client";
import { useEffect, useRef, useState } from "react";
import { DateRange, Range } from "react-date-range";
import { addDays, format, getTime } from "date-fns";

import { DictionariesType } from "@/lib/dictionary";
import { usePathname } from "next/navigation";
import arLocale from "date-fns/locale/ar";
import { UseFormRegisterReturn } from "react-hook-form";

import "react-date-range/dist/styles.css"; // main css file
import "react-date-range/dist/theme/default.css"; // theme css file

type Props = {
  addItem_content: DictionariesType;
  register: UseFormRegisterReturn;
};

export default function InputDateRange({ addItem_content, register }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const pathname = usePathname();
  const lang = pathname.split("/")[1];
  const [range, setRange] = useState<Range[]>([
    {
      startDate: new Date(),
      endDate: addDays(new Date(), 7),
      key: "selection",
    },
  ]);
  const calendarRef = useRef<HTMLDivElement>(null);

  const [startUnix, setStartUnix] = useState(getTime(new Date()));
  const [endUnix, setEndUnix] = useState(getTime(addDays(new Date(), 7)));

  useEffect(() => {
    const hideOnEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") setIsOpen(false);
    };
    const hideOnClickOutside = (e: MouseEvent) => {
      if (calendarRef.current && !calendarRef.current.contains(e.target as Node))
        setIsOpen(false);
    };

    document.addEventListener("keydown", hideOnEscape, true);
    document.addEventListener("click", hideOnClickOutside, true);

    return () => {
      document.removeEventListener("keydown", hideOnEscape, true);
      document.removeEventListener("click", hideOnClickOutside, true);
    };
  }, []);

  function handleDateChange(ranges: { [key: string]: Range }) {
    const { startDate, endDate } = ranges.selection;
    setRange([ranges.selection]);
    setStartUnix(getTime(startDate!));
    setEndUnix(getTime(endDate!));
    console.log(ranges);
  }

  function handleStartTimeChange(event: React.ChangeEvent<HTMLInputElement>) {
    const date = new Date(startUnix);
    const [hours, minutes] = event.target.value.split(":").map(Number);
    date.setHours(hours, minutes);
    setStartUnix(getTime(date));
    console.log("startUnix:", startUnix);
  }

  function handleEndTimeChange(event: React.ChangeEvent<HTMLInputElement>) {
    const date = new Date(endUnix);
    const [hours, minutes] = event.target.value.split(":").map(Number);
    date.setHours(hours, minutes);
    setEndUnix(getTime(date));
    console.log("endUnix:", endUnix);
  }

  return (
    <div className="relative inline-block w-full">
      <input
        type="text"
        id="range"
        value={`${format(new Date(startUnix), "MM/dd/yyyy")} ${addItem_content.to} ${format(new Date(endUnix), "MM/dd/yyyy")}`}
        readOnly
        onClick={() => setIsOpen((open) => !open)}
        placeholder={`"Start Date - End Date"`}
        className="w-full px-4 py-6 text-xl text-center bg-transparent border outline-none cursor-pointer rounded-xl border-fuze-grey-50 text-fuze-grey-400 dark:text-fuze-grey-100"
        {...register}
      />
      {isOpen && (
        <div ref={calendarRef}>
          <DateRange
            editableDateInputs={true}
            locale={lang === "ar" ? arLocale : undefined}
            onChange={handleDateChange}
            moveRangeOnFirstSelection={false}
            ranges={range}
            months={1}
            minDate={new Date()}
            direction="horizontal"
            className="absolute top-20 border border-fuze-grey-50 z-10 rounded-xl w-full"
          />
        </div>
      )}
      <div>
        <label>Start Time</label>
        <input
          type="time"
          value={format(new Date(startUnix), "HH:mm")}
          onChange={handleStartTimeChange}
          className="w-full px-4 py-6 text-xl text-center bg-transparent border outline-none cursor-pointer rounded-xl border-fuze-grey-50 text-fuze-grey-400 dark:text-fuze-grey-100"
        />
      </div>
      <div>
        <label>End Time</label>
        <input
          type="time"
          value={format(new Date(endUnix), "HH:mm")}
          onChange={handleEndTimeChange}
          className="w-full px-4 py-6 text-xl text-center bg-transparent border outline-none cursor-pointer rounded-xl border-fuze-grey-50 text-fuze-grey-400 dark:text-fuze-grey-100"
        />
      </div>
    </div>
  );
}
Leave a Comment