Duffer Derek

Current Path : /var/www/api-mk-planner.bitkit.dk/httpdocs/Frontend/src/utils/
Upload File :
Current File : /var/www/api-mk-planner.bitkit.dk/httpdocs/Frontend/src/utils/CalculateTaskStyle.js

import { useMemo } from "react";
import { useDataContext } from "../hooks/useDataContext.js";
import { differenceInDays } from "date-fns";

/**
 * Calculate the style for a task based on its start and end dates.
 * @param {Date} taskStartDate - The start date of the task.
 * @param {Date} taskEndDate - The end date of the task.
 * @param {Array} propDates - Optional dates array from props (takes precedence over context).
 * @param {number} propColumnWidth - Optional column width from props (takes precedence over context).
 * @returns {Object} - An object representing the CSS style for the task.
 */
function CalculateTaskStyle(taskStartDate, taskEndDate, propDates = null, propColumnWidth = null) {
  const contextData = useDataContext();
  // Use props if provided, otherwise fallback to context
  const dates = propDates || contextData?.dates;
  const columnWidth = propColumnWidth !== null && propColumnWidth !== undefined ? propColumnWidth : contextData?.columnWidth;
  
  // Use useMemo to memoize the CSS style object - must be called unconditionally
  return useMemo(() => {
    // Return default style if dates or columnWidth are not available
    if (!dates || !dates.length || columnWidth === null || columnWidth === undefined) {
      return {
        width: "auto",
        position: "absolute",
        left: "-1px",
        right: "0px",
      };
    }
    
    const yearStartDate = new Date(dates[0].date);
    const yearEndDate = new Date(dates[dates.length - 1].date);

    // Calculate the left and right values for positioning the task
    const taskLeftValue = columnWidth * (-(differenceInDays(yearStartDate, taskStartDate)));
    const taskRightValue = columnWidth * differenceInDays(yearEndDate, taskEndDate);

    return {
      width: "auto",
      position: "absolute",
      left: `${taskLeftValue > -1 ? taskLeftValue + 3 : -1}px`,
      right: `${taskRightValue > -1 ? taskRightValue + 3 : 0}px`,
    };
  }, [dates, columnWidth, taskStartDate, taskEndDate]);
}

export default CalculateTaskStyle;

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists