All files / src/components/Calendar/MonthCalendar index.tsx

100% Statements 232/232
91.3% Branches 63/69
100% Functions 3/3
100% Lines 232/232

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318    1x   1x 1x   1x   1x   1x                     1x 1x                         1x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x 60x 60x 60x   60x 26x 6x 20x   26x   26x 6x 6x 60x   60x   60x 731x 731x 731x 60x   60x 50x 50x 19x 19x 50x 50x 60x   60x 1x 1x 1x 60x   60x 1x 1x 1x 1x 1x 60x   60x 60x 4x     4x 2x 2x 6x 2x 2x 2x 2x 2x   4x   4x 2x 2x 2x 2x 2x   2x 6x 5x 5x 2x 2x 2x 2x   4x 4x 4x 60x 60x   60x 60x 7x 7x 7x 7x 4x 60x 60x   60x 60x 60x 60x     60x 60x 60x 60x 60x 60x   60x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x 60x 240x 240x 240x 240x   240x 240x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x 60x 60x 60x 60x 56x 4x   60x 60x 60x     60x 60x 720x   720x 720x 204x   720x 720x 204x 516x   720x   720x 720x 720x 720x 720x 720x 84x 636x 720x 720x 720x 720x 720x   720x 720x 516x 204x 12x 720x   720x 720x 720x 14x 14x 14x 14x     720x 720x 720x 720x 4x 4x 4x 4x 4x 4x 4x 720x 720x 720x 720x   720x 720x   720x 720x     720x 204x   68x   720x 204x   68x   720x 204x   68x   720x   516x     720x 164x     720x     720x 556x 407x     720x 495x 7x 5x 720x   720x 720x 720x   60x 60x 60x   60x  
'use client';
 
import { useCallback, useEffect, useMemo, useState } from 'react';
 
import { CURRENT_YEAR, MONTHS } from '@/constants/calendar';
import { ENV } from '@/constants/env';
 
import { ChartMode } from '@/types';
 
import { combineClasses } from '@shared/utils';
 
import {
  getQuarterKey,
  getQuarterMonths,
  isMonthSelected,
  toggleSingleMonth,
  getQuarterBgStyle,
  isIncompleteMonth,
  parseTimeRangeToMonths,
  parseDateFromYYYYMMDD,
} from '@/utils/calendar';
 
import { Button } from '@/components/Calendar/Shadcn/button';
import { ChevronIcon } from '@/components/icons/reacts';
 
interface MonthYearPickerProps {
  selectedMonths?: { year: number; month: number }[];
  selectedYear?: number;
  mode: ChartMode.Month | ChartMode.Quarter;
  onMonthsChange?: (months: { year: number; month: number }[]) => void;
  onYearChange?: (year: number) => void;
  onCancel?: () => void;
  onDone?: () => void;
  timeRange?: string;
}
 
export const MonthCalendar = ({
  selectedMonths,
  selectedYear = CURRENT_YEAR,
  mode = ChartMode.Month,
  onMonthsChange,
  onYearChange,
  timeRange,
}: MonthYearPickerProps) => {
  const today = new Date();
  const currentYearActual = today.getFullYear();
 
  const [currentYear, setCurrentYear] = useState(selectedYear);
  const [selected, setSelected] = useState<{ year: number; month: number }[]>(
    selectedMonths || [],
  );
  const [hoveredQuarter, setHoveredQuarter] = useState<number | null>(null);
 
  useEffect(() => {
    const initMonths = selectedMonths
      ? selectedMonths
      : parseTimeRangeToMonths(timeRange, mode);
 
    setSelected(initMonths);
 
    if (initMonths.length > 0) {
      setCurrentYear(initMonths[0]!.year);
    }
  }, [selectedMonths, timeRange, mode]);
 
  const goLiveDate = parseDateFromYYYYMMDD(ENV.GO_LIVE_DATE);
 
  const isBeforeGoLive = useCallback((year: number, month: number) => {
    if (!goLiveDate) return false;
    const compare = new Date(year, month, 1);
    return compare < goLiveDate;
  }, []);
 
  const selectedQuarterKeys = useMemo(() => {
    const keys: string[] = [];
    selected.forEach(({ year, month }) => {
      const key = getQuarterKey(year, month);
      if (!keys.includes(key)) keys.push(key);
    });
    return keys;
  }, [selected]);
 
  const handlePreviousYear = useCallback(() => {
    const newYear = currentYear - 1;
    setCurrentYear(newYear);
    onYearChange?.(newYear);
  }, [currentYear, onYearChange]);
 
  const handleNextYear = useCallback(() => {
    if (currentYear < currentYearActual) {
      const newYear = currentYear + 1;
      setCurrentYear(newYear);
      onYearChange?.(newYear);
    }
  }, [currentYear, currentYearActual, onYearChange]);
 
  const toggleMonthHandler = useCallback(
    (monthIndex: number) => {
      if (isBeforeGoLive(currentYear, monthIndex)) return;
 
      // Existing future/incomplete check
      if (mode === ChartMode.Quarter) {
        const quarterMonths = getQuarterMonths(monthIndex);
        const hasIncomplete = quarterMonths.some((m) =>
          isIncompleteMonth(currentYear, m, today),
        );
        if (hasIncomplete) return;
      } else if (mode === ChartMode.Month) {
        if (isIncompleteMonth(currentYear, monthIndex, today)) return;
      }
 
      let updated: { year: number; month: number }[] = [...selected];
 
      if (mode === ChartMode.Quarter) {
        const quarterMonths = getQuarterMonths(monthIndex);
        const isQuarterSelected = quarterMonths.every((m) =>
          selected.some((s) => s.year === currentYear && s.month === m),
        );
        if (isQuarterSelected) return;
 
        quarterMonths.forEach((m) => {
          if (!updated.some((s) => s.year === currentYear && s.month === m)) {
            updated.push({ year: currentYear, month: m });
          }
        });
      } else {
        updated = toggleSingleMonth(currentYear, monthIndex, selected);
      }
 
      setSelected(updated);
      onMonthsChange?.(updated);
    },
    [currentYear, mode, selected, onMonthsChange, today, isBeforeGoLive],
  );
 
  const monthClickHandlers = useMemo(() => {
    return MONTHS.map((_, index) => () => {
      if (isBeforeGoLive(currentYear, index)) return;
      const alreadySelected = isMonthSelected(currentYear, index, selected);
      const incomplete = isIncompleteMonth(currentYear, index, today);
      if (alreadySelected || incomplete) return;
      toggleMonthHandler(index);
    });
  }, [currentYear, selected, toggleMonthHandler, today, isBeforeGoLive]);
 
  return (
    <div
      data-testid="month-calendar"
      className="bg-white rounded-xl pt-3.75 pb-5 px-4 border border-secondary-300 w-[222px] dark:border-slate-700 dark:bg-slate-700"
    >
      {/* Year Navigation */}
      <div className="flex items-center justify-between mb-3.25 max-w-36 w-full mx-auto">
        <Button
          id="previous-year-button"
          variant="ghost"
          size="icon"
          onClick={handlePreviousYear}
        >
          <ChevronIcon
            direction="left"
            width={18}
            height={18}
            className="text-primary-350"
          />
        </Button>
        <div
          data-testid="calendar-year-label"
          className="flex items-center gap-1"
        >
          {String(currentYear)
            .split('')
            .map((digit, index) => (
              <span
                key={index}
                data-testid="calendar-year-digit"
                className="text-4xs leading-6 font-semibold text-primary-350"
              >
                {digit}
              </span>
            ))}
        </div>
        <Button
          id="next-year-button"
          variant="ghost"
          size="icon"
          onClick={handleNextYear}
          disabled={currentYear >= currentYearActual}
        >
          <ChevronIcon
            direction="right"
            width={18}
            height={18}
            className={
              currentYear >= currentYearActual
                ? 'text-secondary-300'
                : 'text-primary-350'
            }
          />
        </Button>
      </div>
 
      {/* Month Grid */}
      <div className="grid grid-cols-4 gap-y-[5px] gap-x-4 mb-[11px]">
        {MONTHS.map((month, index) => {
          const quarterMonths = getQuarterMonths(index);
 
          const isQuarterIncomplete =
            mode === ChartMode.Quarter &&
            quarterMonths.some((m) => isIncompleteMonth(currentYear, m, today));
 
          const isIncomplete =
            mode === ChartMode.Quarter
              ? isQuarterIncomplete
              : isIncompleteMonth(currentYear, index, today);
 
          const beforeGoLive = isBeforeGoLive(currentYear, index);
 
          const { renderBg, bgStyle, bgColor } = getQuarterBgStyle({
            index,
            quarterMonths,
            selectedQuarterKeys,
            selectionColors:
              selected.length === 1
                ? ['bg-blue-500']
                : ['bg-blue-500', 'bg-secondary-350', 'bg-secondary-400'],
            mode,
            selected,
            currentYear,
            hoveredQuarter,
          });
 
          const isHovered =
            mode === ChartMode.Month
              ? hoveredQuarter === index
              : hoveredQuarter !== null &&
                getQuarterMonths(hoveredQuarter).includes(index);
          const isDisabled = isIncomplete || beforeGoLive;
 
          return (
            <div key={month} className="relative">
              {renderBg && (
                <div
                  className={`absolute inset-0 h-full rounded-xl ${bgColor}`}
                  style={{ ...bgStyle, zIndex: 0 }}
                />
              )}
 
              <Button
                variant="ghost"
                onClick={monthClickHandlers[index]}
                onMouseEnter={() => {
                  if (
                    !isDisabled &&
                    (mode === ChartMode.Month || mode === ChartMode.Quarter)
                  ) {
                    setHoveredQuarter(index);
                  }
                }}
                onMouseLeave={() => setHoveredQuarter(null)}
                disabled={isDisabled}
                data-selected={
                  isMonthSelected(currentYear, index, selected) || undefined
                }
                data-hovered={(!isDisabled && isHovered) || undefined}
                className={combineClasses(
                  // Base
                  'relative z-10 text-4xs leading-6 font-medium dark:text-background transition-all duration-150',
                  'w-10 h-10 p-0 active:scale-95',
 
                  // Apply different corner rounding styles depending on mode and month position
                  mode === ChartMode.Quarter &&
                    index % 3 === 0 &&
                    // First month of the quarter → round left corners only
                    'rounded-l-xl rounded-r-none',
 
                  mode === ChartMode.Quarter &&
                    index % 3 === 1 &&
                    // Middle month of the quarter → no rounding (connects seamlessly)
                    'rounded-none',
 
                  mode === ChartMode.Quarter &&
                    index % 3 === 2 &&
                    // Last month of the quarter → round right corners only
                    'rounded-r-xl rounded-l-none',
 
                  mode === ChartMode.Month &&
                    // In Month mode → each button is individually rounded
                    'rounded-md',
 
                  // Selected state → apply bgColor + enforce hover with the same bgColor
                  isMonthSelected(currentYear, index, selected) &&
                    `${bgColor} text-white hover:${bgColor} hover:text-white`,
 
                  // Disabled (beforeGoLive OR incomplete)
                  isDisabled && 'text-gray-300 cursor-not-allowed opacity-50',
 
                  // Default (not selected, not disabled)
                  !isMonthSelected(currentYear, index, selected) &&
                    !isDisabled &&
                    'text-frost-900',
 
                  // Hover state for unselected months
                  !isDisabled &&
                    isHovered &&
                    !isMonthSelected(currentYear, index, selected) &&
                    'data-[hovered=true]:bg-blue-300 data-[hovered=true]:text-white',
                )}
              >
                {month}
              </Button>
            </div>
          );
        })}
      </div>
    </div>
  );
};