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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 | 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 1x 84x 84x 84x 84x 84x 84x 84x 84x 1x 207x 207x 207x 1x 85x 85x 1x 2601x 2601x 2601x 2601x 1x 51x 51x 51x 51x 51x 51x 51x 51x 51x 36x 36x 1x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 725x 725x 725x 725x 725x 725x 725x 725x 725x 725x 725x 725x 725x 209x 209x 339x 209x 209x 209x 209x 12x 12x 209x 141x 141x 209x 68x 65x 65x 65x 3x 68x 68x 68x 68x 68x 63x 6x 6x 6x 209x 3x 3x 3x 3x 3x 2x 2x 2x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 209x 584x 584x 516x 725x 8x 8x 8x 8x 8x 8x 8x 584x 584x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 9x 9x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 10x 10x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 47x 47x 47x 47x 47x 3x 47x 14x 47x 47x 47x 47x 47x 1x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 10x 2x 2x 2x 2x 1x 22x 22x 22x 22x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 1x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 116x 2x 2x 114x 114x 114x 114x 114x 114x 114x 113x 116x 1x 1x 113x 113x 113x 1x 25x 25x 25x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 25x 25x 25x 25x 1x 15x 15x 15x 15x 15x 10x 10x 15x 3x 6x 6x 3x 3x 15x 4x 4x 6x 6x 2x 4x 4x 4x 15x 3x 3x 15x 10x 10x 1x 3x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x | import { addDays, format } from 'date-fns';
import { Matcher } from 'react-day-picker';
import { MONTHLY_FORMAT, QUARTERLY_FORMAT, WEEKLY_FORMAT } from '@/constants';
import { ChartMode } from '@/types';
import {
ColorVariant,
ModeItemMap,
MonthObj,
QuarterBgStyleParams,
QuarterObj,
Selected,
ToggleQuarterParams,
WeekRange,
YearSelectionProps,
} from '@/types/calendar';
import { parseTimeRanges } from './date';
/**
* Generate an array of years between a start and end year (inclusive).
*/
export const getYears = (startYear: number, endYear: number): number[] => {
return Array.from(
{ length: endYear - startYear + 1 },
(_, i) => startYear + i,
);
};
/**
* Given a date, return the Monday–Friday range of that week.
*/
export const getMondayToFridayRange = (date: Date) => {
const day = date.getDay();
const diffToMonday = (day + 6) % 7;
const monday = new Date(date);
monday.setDate(date.getDate() - diffToMonday);
const friday = new Date(monday);
friday.setDate(monday.getDate() + 4);
return { from: monday, to: friday };
};
/**
* Get all months belonging to the quarter of the given month index.
* @param monthIndex 0 = January, 11 = December
*/
export const getQuarterMonths = (monthIndex: number): number[] => {
const quarter = Math.floor(monthIndex / 3);
return [quarter * 3, quarter * 3 + 1, quarter * 3 + 2];
};
/**
* Create a unique key string for a quarter (e.g., "2025-0" for Q1 2025).
*/
export const getQuarterKey = (year: number, monthIndex: number) => {
return `${year}-${Math.floor(monthIndex / 3)}`;
};
/**
* Check if a specific year+month is in the selected list.
*/
export const isMonthSelected = (
year: number,
monthIndex: number,
selected: { year: number; month: number }[],
) => selected.some((m) => m.year === year && m.month === monthIndex);
/**
* Determine if a given year+month is in the future relative to today.
*/
export const isIncompleteMonth = (
year: number,
monthIndex: number,
today: Date,
) => {
const currentYear = today.getFullYear();
const currentMonth = today.getMonth();
// Future month
if (year > currentYear) return true;
if (year === currentYear && monthIndex > currentMonth) return true;
// Current month (still ongoing)
if (year === currentYear && monthIndex === currentMonth) return true;
return false;
};
/**
* Toggle a single month in the selection list (max selection limit applies).
*/
export const toggleSingleMonth = (
year: number,
monthIndex: number,
selected: { year: number; month: number }[],
maxSelection = 3,
) => {
const exists = isMonthSelected(year, monthIndex, selected);
if (exists) {
return selected.filter((m) => !(m.year === year && m.month === monthIndex));
}
if (selected.length >= maxSelection) return selected;
return [...selected, { year, month: monthIndex }];
};
/**
* Toggle a full quarter in the selection list (max quarter limit applies).
* Adds or removes all months of that quarter at once.
*/
export const toggleQuarter = ({
year,
monthIndex,
selected,
selectedQuarterKeys,
maxQuarters = 3,
}: ToggleQuarterParams) => {
const quarterMonths = getQuarterMonths(monthIndex);
const isSelected = quarterMonths.every((m) =>
isMonthSelected(year, m, selected),
);
let updated = [...selected];
if (isSelected) {
// Remove quarter
updated = updated.filter(
(m) => !(m.year === year && quarterMonths.includes(m.month)),
);
} else {
// Add quarter if under limit
if (selectedQuarterKeys.length >= maxQuarters) return selected;
const newQuarter = quarterMonths.map((m) => ({ year, month: m }));
updated = [
...updated,
...newQuarter.filter(
(nm) =>
!updated.some((sm) => sm.year === nm.year && sm.month === nm.month),
),
];
}
return updated;
};
/**
* Determine whether to render a background highlight for a month/quarter cell.
* Returns the style and color needed for visualizing the selection.
*/
export const getQuarterBgStyle = ({
index,
quarterMonths,
selectedQuarterKeys,
selectionColors,
mode,
selected,
currentYear,
hoveredQuarter,
}: QuarterBgStyleParams) => {
let renderBg = false;
let bgStyle: React.CSSProperties = {};
let bgColor = '';
if (mode === ChartMode.Quarter && quarterMonths.length >= 3) {
const [first, second, third] = quarterMonths as [number, number, number];
// --- Selection check
const quarterSelected = quarterMonths.every((m) =>
isMonthSelected(currentYear, m, selected),
);
// --- Hover check
const quarterHovered =
mode === ChartMode.Quarter &&
hoveredQuarter !== null &&
hoveredQuarter !== undefined &&
getQuarterMonths(hoveredQuarter).includes(index);
if (!quarterSelected && !quarterHovered) {
return { renderBg, bgStyle, bgColor };
}
// --- Color
if (quarterSelected || quarterHovered) {
bgColor = quarterSelected
? (selectionColors[
selectedQuarterKeys.indexOf(getQuarterKey(currentYear, index))
] ?? '')
: 'bg-blue-300';
}
// --- Layout
const startRow = Math.floor(first / 4);
const midRow = Math.floor(second / 4);
const endRow = Math.floor(third / 4);
if (startRow === endRow) {
// All months on same row
if (index === first) {
renderBg = true;
bgStyle = { left: 0, width: `calc(300% + 2*1rem)` };
}
} else if (startRow === midRow) {
// First two in one row, last in next
const styles: Record<number, React.CSSProperties> = {
[first]: { left: 0, width: `calc(200% + 1rem)` },
[third]: { left: 0, width: '100%' },
};
if (styles[index]) {
renderBg = true;
bgStyle = styles[index];
}
} else {
// Last two in one row, first in previous
const styles: Record<number, React.CSSProperties> = {
[first]: { left: 0, width: '100%' },
[second]: { left: 0, width: `calc(200% + 1rem)` },
};
if (styles[index]) {
renderBg = true;
bgStyle = styles[index];
}
}
}
if (
mode === ChartMode.Month &&
isMonthSelected(currentYear, index, selected)
) {
renderBg = true;
const order = selected.findIndex(
(m) => m.year === currentYear && m.month === index,
);
bgColor = selectionColors[order] ?? '';
bgStyle = { left: 0, width: '100%' };
}
return { renderBg, bgStyle, bgColor };
};
/**
* Returns a new array of selected years after toggling a single year
*/
export const toggleYearSelection = ({
selected,
year,
minYear,
maxYear,
maxSelection = 3,
}: YearSelectionProps): number[] => {
if (year > maxYear || year < minYear) return selected;
if (selected.includes(year)) {
return selected.filter((y) => y !== year);
}
if (selected.length >= maxSelection) return selected;
return [...selected, year];
};
/**
* Returns an array of years for a decade (12 years: previous, 10 in decade, next)
*/
export const getDecadeYears = (decadeStart: number): number[] => {
return Array.from({ length: 12 }, (_, i) => decadeStart - 1 + i);
};
/**
* Returns an array of color variants for legend boxes based on the number of items.
* @param count - The number of items to display in the legend.
* @returns Array of ColorVariant strings corresponding to each item.
*/
export const getLegendColors = (
count: number,
customColors?: ColorVariant[],
): ColorVariant[] => {
// Default color sets
const defaultColorSets: ColorVariant[][] = [
[],
['primary'],
['primary', 'secondaryResult'],
['primary', 'secondaryResult', 'goldResult'],
];
// If custom colors are provided, use them (slice to match count)
if (customColors && customColors.length >= count) {
return customColors.slice(0, count);
}
// Otherwise, fallback to default set
return defaultColorSets[count] ?? [];
};
/**
* Toggles the calendar dropdown open/closed and prepares state for editing.
* Copies the current selected items into a temporary state to allow modifications.
*
* @param index - The index of the legend box being edited, or null for a new item.
* @param setEditIndex - React state setter for the current edit index.
* @param setTempSelected - React state setter for the temporary selected items.
* @param selected - The current selected items (months, quarters, years).
* @param setOpen - React state setter for controlling whether the calendar dropdown is open.
*/
export const toggleCalendar = (
index: number | null,
setEditIndex: React.Dispatch<React.SetStateAction<number | null>>,
setTempSelected: React.Dispatch<
React.SetStateAction<{
months: MonthObj[];
quarters: QuarterObj[];
years: number[];
}>
>,
selected: { months: MonthObj[]; quarters: QuarterObj[]; years: number[] },
setOpen: React.Dispatch<React.SetStateAction<boolean>>,
) => {
setEditIndex(index);
setTempSelected({ ...selected });
setOpen((prev) => !prev);
};
/**
* Formats a label string for the given ChartMode and item.
* Ensures type-safe mapping between mode and its corresponding item type.
*
* @param mode - The active chart mode (Week, Month, Quarter, or Year).
* @param item - The item to format (WeekRange, MonthObj, QuarterObj, or number).
* @returns A human-readable label for the item.
*/
export const formatLabel = <M extends ChartMode>(
mode: M,
item: ModeItemMap[M],
): string => {
const formatters: { [K in ChartMode]: (item: ModeItemMap[K]) => string } = {
[ChartMode.Week]: (item) =>
`${format(item.from, 'MMM dd')} - ${format(item.to, 'MMM dd, yyyy')}`,
[ChartMode.Month]: (item) =>
format(new Date(item.year, item.month, 1), 'MMM yyyy'),
[ChartMode.Quarter]: (item) => `Q${item.quarter} ${item.year}`,
[ChartMode.Year]: (item) => `${item}`,
};
return formatters[mode](item);
};
/**
* Counts the number of selections for the given ChartMode.
*
* @param mode - The active chart mode.
* @param selectedRanges - Array of selected weeks.
* @param selected - Object containing selected months, quarters, and years.
* @returns The number of selections for the active mode.
*/
export const countSelections = (
mode: ChartMode,
selectedRanges: WeekRange[],
selected: Selected,
): number => {
const counters: Record<ChartMode, number> = {
[ChartMode.Week]: selectedRanges.length,
[ChartMode.Month]: selected.months.length,
[ChartMode.Quarter]: selected.quarters.length,
[ChartMode.Year]: selected.years.length,
};
return counters[mode];
};
/**
* Retrieves the selected items for the given ChartMode.
*
* @param mode - The active chart mode.
* @param selectedRanges - Array of selected weeks.
* @param selected - Object containing selected months, quarters, and years.
* @returns The array of items corresponding to the active mode.
*/
export const getItemsForMode = <M extends ChartMode>(
mode: M,
selectedRanges: WeekRange[],
selected: Selected,
): ModeItemMap[M][] => {
const selectors: { [K in ChartMode]: ModeItemMap[K][] } = {
[ChartMode.Week]: selectedRanges,
[ChartMode.Month]: selected.months,
[ChartMode.Quarter]: selected.quarters,
[ChartMode.Year]: selected.years,
};
return selectors[mode];
};
/**
* Expands an array of quarters into their corresponding months.
*
* @param quarters - Array of QuarterObj items to expand.
* @returns An array of MonthObj items representing the months in each quarter.
*/
export const expandQuarterToMonths = (quarters: QuarterObj[]): MonthObj[] =>
quarters.flatMap((q) => [
{ year: q.year, month: (q.quarter - 1) * 3 },
{ year: q.year, month: (q.quarter - 1) * 3 + 1 },
{ year: q.year, month: (q.quarter - 1) * 3 + 2 },
]);
/**
* Parses a time range string into an array of months, based on the chart mode.
*
* - Month mode: returns one {year, month}.
* - Quarter mode: expands to three months belonging to the quarter.
*
* @param timeRange - A time range string (e.g. "2024-05" or "2024-Q2").
* @param mode - Either Month or Quarter mode.
* @returns An array of MonthObj representing the parsed months.
*/
export const parseTimeRangeToMonths = (
timeRange: string | undefined,
mode: ChartMode.Month | ChartMode.Quarter,
): { year: number; month: number }[] => {
if (!timeRange) return [];
if (mode === ChartMode.Month) {
const match = MONTHLY_FORMAT.exec(timeRange);
if (match) {
const year = parseInt(match[1]!, 10);
const month = parseInt(match[2]!, 10) - 1;
return [{ year, month }];
}
}
if (mode === ChartMode.Quarter) {
const match = QUARTERLY_FORMAT.exec(timeRange);
if (match) {
const year = parseInt(match[1]!, 10);
const quarter = parseInt(match[2]!, 10);
return [0, 1, 2].map((m) => ({
year,
month: m + (quarter - 1) * 3,
}));
}
}
return [];
};
/**
* Build a list of `Matcher`s to disable dates in the calendar.
*
* Rules:
* 1. Disable all future days (anything after today).
* 2. Disable the current week's weekdays (Mon–Fri) if the week has not finished yet.
* - Sundays are intentionally left enabled so the user can still click them.
*
* @param today - The reference date (usually new Date()).
* @returns Matcher[] - An array of matchers for the `disabled` prop in Calendar.
*/
export const getDisabledMatchers = (today: Date): Matcher[] => {
const matchers: (Matcher | undefined)[] = [
// Disable all future days
{ from: addDays(today, 1), to: new Date(9999, 11, 31) },
// Disable current unfinished weekdays (Mon–Fri), but NOT Sunday
(() => {
const currentWeek = getMondayToFridayRange(today);
const weekEnd = new Date(currentWeek.to).setHours(23, 59, 59, 999);
if (today.getTime() <= weekEnd) {
return { from: currentWeek.from, to: currentWeek.to };
}
return;
})(),
];
return matchers.filter(Boolean) as Matcher[];
};
/**
* Formats a raw YYYYMMDD string into a week range string (Mon–Fri).
*
* Example:
* "20250915" → "Sep 15 - Sep 19, 2025"
*
* - If input is not in YYYYMMDD format, it is returned unchanged.
* - If the date cannot be parsed, the raw value is returned unchanged.
*/
export const formatWeekRange = (raw: string): string => {
if (!/^\d{8}$/.test(raw)) return raw; // Not a week string
const year = Number(raw.slice(0, 4));
const month = Number(raw.slice(4, 6)) - 1;
const day = Number(raw.slice(6, 8));
const start = new Date(year, month, day);
if (isNaN(start.getTime())) return raw;
const end = new Date(start);
end.setDate(start.getDate() + 4); // Monday → Friday
return `${format(start, 'MMM d')} - ${format(end, 'MMM d, yyyy')}`;
};
/**
* Parses a YYYYMMDD string and returns a Date object.
* The time of the returned Date object is set to the beginning of the day (midnight UTC).
* * @param periodCode A string in YYYYMMDD format (e.g., "20231026").
* @returns A Date object, or null if the input is invalid.
*/
export const parseDateFromYYYYMMDD = (periodCode?: string): Date | null => {
// Input validation: checks for existence and format length.
if (!periodCode || periodCode.length < 8) {
return null;
}
const year = Number(periodCode.slice(0, 4));
const month = Number(periodCode.slice(4, 6)) - 1; // Months are 0-indexed in JS.
const day = Number(periodCode.slice(6, 8));
const date = new Date(year, month, day);
if (
date.getFullYear() !== year ||
date.getMonth() !== month ||
date.getDate() !== day
) {
return null; // Invalid date (e.g., "20230230").
}
// Set time to the start of the day for consistent comparisons.
date.setHours(0, 0, 0, 0);
return date;
};
/**
* Converts a time range string into an array of week ranges (Monday to Friday).
* Each range has `from` (start of Monday) and `to` (end of Friday, 23:59:59.999).
*
* @param timeRange - A string representing selected weeks (e.g., "2025-09-22,2025-09-29")
* @returns An array of objects with `from` and `to` Date properties for each week.
*/
export const createWeekSelectedRanges = (timeRange: string) => {
const weeks = parseTimeRanges(timeRange);
const ranges = weeks
.map((w) => {
const match = WEEKLY_FORMAT.exec(w);
if (!match) return null;
const year = parseInt(match[1]!, 10);
const month = parseInt(match[2]!, 10) - 1;
const day = parseInt(match[3]!, 10);
const date = new Date(year, month, day);
if (isNaN(date.getTime())) return null;
const range = getMondayToFridayRange(date);
const endDate = new Date(range.to);
endDate.setHours(23, 59, 59, 999);
return { from: range.from, to: endDate };
})
.filter(Boolean) as { from: Date; to: Date }[];
return ranges;
};
/**
* Converts a time range string into selected ranges for months, quarters, or years.
* Used for chart modes other than weekly.
*
* @param timeRange - A string representing selected time periods (e.g., "202509,202510" for months)
* @param mode - Chart mode to determine the type of range (Month, Quarter, Year)
* @returns An object containing arrays for months, quarters, and years.
*/
export const createNotWeekSelectedRanges = (
timeRange: string,
mode: ChartMode,
) => {
const ranges: Selected = { months: [], quarters: [], years: [] };
if (!timeRange) return ranges;
const items = parseTimeRanges(timeRange);
switch (mode) {
case ChartMode.Month:
ranges.months = items.map((m) => ({
year: parseInt(m.slice(0, 4), 10),
month: parseInt(m.slice(4, 6), 10) - 1,
}));
break;
case ChartMode.Quarter:
ranges.quarters = items
.map((q) => {
const match = q.match(QUARTERLY_FORMAT);
if (!match) return null;
return { year: Number(match[1]), quarter: Number(match[2]) };
})
.filter(Boolean) as QuarterObj[];
break;
case ChartMode.Year:
ranges.years = items.map((y) => Number(y)).filter((y) => !isNaN(y));
break;
}
return ranges;
};
/**
* Get selected ranges based on the provided chart mode and time range.
*
* @param timeRange - A string representing the selected time range
* (e.g., "2022Q1", "202401", "20220502").
* @param chartMode - The chart display mode (Week, Month, Quarter, or Year).
* @returns An object containing week ranges or non-week ranges
* depending on the selected chart mode.
*/
export const getSelectedRangesByMode = (
timeRange: string,
chartMode: ChartMode,
) => {
if (chartMode === ChartMode.Week) {
return {
weekRanges: createWeekSelectedRanges(timeRange),
notWeekRanges: { months: [], quarters: [], years: [] },
};
}
return {
weekRanges: [],
notWeekRanges: createNotWeekSelectedRanges(timeRange, chartMode),
};
};
/**
* Build a date range using start date + meal count, including makeup days.
*/
export const getRangeByMealLength = (start: Date, length: number) => {
const startDate = new Date(start);
const endDate = new Date(start);
endDate.setDate(startDate.getDate() + (length - 1));
return { from: startDate, to: endDate };
};
|