All files / src/components/charts/LineCharts/hooks useTimeConfig.tsx

0% Statements 0/26
0% Branches 0/14
0% Functions 0/5
0% Lines 0/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                                                                             
import { useMemo } from "react";
import { TTimeConfig, TTimeUnits } from "@components/LineGraph/types";
import { TimeLineChartData } from "../types";
import { intervalToDuration } from "date-fns";
import { useFormatDateInTimezone } from "@utils/date.helpers";
import moment from "moment";
 
type KeyType = "months" | "days";
type ArrayType = Record<KeyType, number | undefined>;
 
const getMaxValue = (key: KeyType, array: ArrayType[]) => {
  return array.reduce((acc, v) => {
    const value = v[key];
    if (value && value > acc) return value;
    return acc;
  }, 0);
};
 
const useTimeConfig = (data: TimeLineChartData[], useTimezone?: boolean) => {
  const { currentTimezone } = useFormatDateInTimezone();
  const timeUnit: TTimeUnits = useMemo(() => {
    const datasetMaxPeriod = data.map((dataset) => {
      if (dataset.entries.length === 0) {
        return { months: undefined, years: undefined, days: 1 };
      }
 
      const startDate = dataset.entries[0].x;
      const endDate = dataset.entries[dataset.entries.length - 1].x;
      const duration = intervalToDuration({
        start: useTimezone
          ? moment(startDate).tz(currentTimezone).toDate()
          : new Date(startDate),
        end: useTimezone
          ? moment(endDate).tz(currentTimezone).toDate()
          : new Date(endDate),
      });
      const { months, days } = duration;
      return { months, days };
    });
 
    const maxMonthsPeriod = getMaxValue("months", datasetMaxPeriod);
    const maxDaysPeriod = getMaxValue("days", datasetMaxPeriod);
 
    if (maxMonthsPeriod > 12) return "year";
    if (maxDaysPeriod > 31) return "month";
    return "day";
  }, [data]);
 
  const timeConfig: TTimeConfig = {
    unit: timeUnit,
    minUnit: "day",
    displayFormats: {
      day: "MMM DD",
      month: "MMM",
      year: "YYYY",
    },
  };
 
  return { timeConfig };
};
 
export default useTimeConfig;