1"use client";
2
3import { getDay, getDaysInMonth, isSameDay } from "date-fns";
4import { atom, useAtom } from "jotai";
5import {
6 Check,
7 ChevronLeftIcon,
8 ChevronRightIcon,
9 ChevronsUpDown,
10} from "lucide-react";
11import {
12 createContext,
13 memo,
14 type ReactNode,
15 useCallback,
16 useContext,
17 useMemo,
18 useState,
19} from "react";
20import { Button } from "@/components/ui/button";
21import {
22 Command,
23 CommandEmpty,
24 CommandGroup,
25 CommandInput,
26 CommandItem,
27 CommandList,
28} from "@/components/ui/command";
29import {
30 Popover,
31 PopoverContent,
32 PopoverTrigger,
33} from "@/components/ui/popover";
34import { cn } from "@/lib/utils";
35
36export type CalendarState = {
37 month: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;
38 year: number;
39};
40
41const monthAtom = atom<CalendarState["month"]>(
42 new Date().getMonth() as CalendarState["month"]
43);
44const yearAtom = atom<CalendarState["year"]>(new Date().getFullYear());
45
46export const useCalendarMonth = () => useAtom(monthAtom);
47export const useCalendarYear = () => useAtom(yearAtom);
48
49type CalendarContextProps = {
50 locale: Intl.LocalesArgument;
51 startDay: number;
52};
53
54const CalendarContext = createContext<CalendarContextProps>({
55 locale: "en-US",
56 startDay: 0,
57});
58
59export type Status = {
60 id: string;
61 name: string;
62 color: string;
63};
64
65export type Feature = {
66 id: string;
67 name: string;
68 startAt: Date;
69 endAt: Date;
70 status: Status;
71};
72
73type ComboboxProps = {
74 value: string;
75 setValue: (value: string) => void;
76 data: {
77 value: string;
78 label: string;
79 }[];
80 labels: {
81 button: string;
82 empty: string;
83 search: string;
84 };
85 className?: string;
86};
87
88export const monthsForLocale = (
89 localeName: Intl.LocalesArgument,
90 monthFormat: Intl.DateTimeFormatOptions["month"] = "long"
91) => {
92 const format = new Intl.DateTimeFormat(localeName, { month: monthFormat })
93 .format;
94
95 return [...new Array(12).keys()].map((m) =>
96 format(new Date(Date.UTC(2021, m, 2)))
97 );
98};
99
100export const daysForLocale = (
101 locale: Intl.LocalesArgument,
102 startDay: number
103) => {
104 const weekdays: string[] = [];
105 const baseDate = new Date(2024, 0, startDay);
106
107 for (let i = 0; i < 7; i++) {
108 weekdays.push(
109 new Intl.DateTimeFormat(locale, { weekday: "short" }).format(baseDate)
110 );
111 baseDate.setDate(baseDate.getDate() + 1);
112 }
113
114 return weekdays;
115};
116
117const Combobox = ({
118 value,
119 setValue,
120 data,
121 labels,
122 className,
123}: ComboboxProps) => {
124 const [open, setOpen] = useState(false);
125
126 return (
127 <Popover onOpenChange={setOpen} open={open}>
128 <PopoverTrigger asChild>
129 <Button
130 aria-expanded={open}
131 className={cn("w-40 justify-between capitalize", className)}
132 variant="outline"
133 >
134 {value
135 ? data.find((item) => item.value === value)?.label
136 : labels.button}
137 <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
138 </Button>
139 </PopoverTrigger>
140 <PopoverContent className="w-40 p-0">
141 <Command
142 filter={(value, search) => {
143 const label = data.find((item) => item.value === value)?.label;
144
145 return label?.toLowerCase().includes(search.toLowerCase()) ? 1 : 0;
146 }}
147 >
148 <CommandInput placeholder={labels.search} />
149 <CommandList>
150 <CommandEmpty>{labels.empty}</CommandEmpty>
151 <CommandGroup>
152 {data.map((item) => (
153 <CommandItem
154 className="capitalize"
155 key={item.value}
156 onSelect={(currentValue) => {
157 setValue(currentValue === value ? "" : currentValue);
158 setOpen(false);
159 }}
160 value={item.value}
161 >
162 <Check
163 className={cn(
164 "mr-2 h-4 w-4",
165 value === item.value ? "opacity-100" : "opacity-0"
166 )}
167 />
168 {item.label}
169 </CommandItem>
170 ))}
171 </CommandGroup>
172 </CommandList>
173 </Command>
174 </PopoverContent>
175 </Popover>
176 );
177};
178
179type OutOfBoundsDayProps = {
180 day: number;
181};
182
183const OutOfBoundsDay = ({ day }: OutOfBoundsDayProps) => (
184 <div className="relative h-full w-full bg-secondary p-1 text-muted-foreground text-xs">
185 {day}
186 </div>
187);
188
189export type CalendarBodyProps = {
190 features: Feature[];
191 children: (props: { feature: Feature }) => ReactNode;
192};
193
194export const CalendarBody = ({ features, children }: CalendarBodyProps) => {
195 const [month] = useCalendarMonth();
196 const [year] = useCalendarYear();
197 const { startDay } = useContext(CalendarContext);
198
199 // Memoize expensive date calculations
200 const currentMonthDate = useMemo(
201 () => new Date(year, month, 1),
202 [year, month]
203 );
204 const daysInMonth = useMemo(
205 () => getDaysInMonth(currentMonthDate),
206 [currentMonthDate]
207 );
208 const firstDay = useMemo(
209 () => (getDay(currentMonthDate) - startDay + 7) % 7,
210 [currentMonthDate, startDay]
211 );
212
213 // Memoize previous month calculations
214 const prevMonthData = useMemo(() => {
215 const prevMonth = month === 0 ? 11 : month - 1;
216 const prevMonthYear = month === 0 ? year - 1 : year;
217 const prevMonthDays = getDaysInMonth(new Date(prevMonthYear, prevMonth, 1));
218 const prevMonthDaysArray = Array.from(
219 { length: prevMonthDays },
220 (_, i) => i + 1
221 );
222 return { prevMonthDays, prevMonthDaysArray };
223 }, [month, year]);
224
225 // Memoize next month calculations
226 const nextMonthData = useMemo(() => {
227 const nextMonth = month === 11 ? 0 : month + 1;
228 const nextMonthYear = month === 11 ? year + 1 : year;
229 const nextMonthDays = getDaysInMonth(new Date(nextMonthYear, nextMonth, 1));
230 const nextMonthDaysArray = Array.from(
231 { length: nextMonthDays },
232 (_, i) => i + 1
233 );
234 return { nextMonthDaysArray };
235 }, [month, year]);
236
237 // Memoize features filtering by day to avoid recalculating on every render
238 const featuresByDay = useMemo(() => {
239 const result: { [day: number]: Feature[] } = {};
240 for (let day = 1; day <= daysInMonth; day++) {
241 result[day] = features.filter((feature) => {
242 return isSameDay(new Date(feature.endAt), new Date(year, month, day));
243 });
244 }
245 return result;
246 }, [features, daysInMonth, year, month]);
247
248 const days: ReactNode[] = [];
249
250 for (let i = 0; i < firstDay; i++) {
251 const day =
252 prevMonthData.prevMonthDaysArray[
253 prevMonthData.prevMonthDays - firstDay + i
254 ];
255
256 if (day) {
257 days.push(<OutOfBoundsDay day={day} key={`prev-${i}`} />);
258 }
259 }
260
261 for (let day = 1; day <= daysInMonth; day++) {
262 const featuresForDay = featuresByDay[day] || [];
263
264 days.push(
265 <div
266 className="relative flex h-full w-full flex-col gap-1 p-1 text-muted-foreground text-xs"
267 key={day}
268 >
269 {day}
270 <div>
271 {featuresForDay.slice(0, 3).map((feature) => children({ feature }))}
272 </div>
273 {featuresForDay.length > 3 && (
274 <span className="block text-muted-foreground text-xs">
275 +{featuresForDay.length - 3} more
276 </span>
277 )}
278 </div>
279 );
280 }
281
282 const remainingDays = 7 - ((firstDay + daysInMonth) % 7);
283 if (remainingDays < 7) {
284 for (let i = 0; i < remainingDays; i++) {
285 const day = nextMonthData.nextMonthDaysArray[i];
286
287 if (day) {
288 days.push(<OutOfBoundsDay day={day} key={`next-${i}`} />);
289 }
290 }
291 }
292
293 return (
294 <div className="grid flex-grow grid-cols-7">
295 {days.map((day, index) => (
296 <div
297 className={cn(
298 "relative aspect-square overflow-hidden border-t border-r",
299 index % 7 === 6 && "border-r-0"
300 )}
301 key={index}
302 >
303 {day}
304 </div>
305 ))}
306 </div>
307 );
308};
309
310export type CalendarDatePickerProps = {
311 className?: string;
312 children: ReactNode;
313};
314
315export const CalendarDatePicker = ({
316 className,
317 children,
318}: CalendarDatePickerProps) => (
319 <div className={cn("flex items-center gap-1", className)}>{children}</div>
320);
321
322export type CalendarMonthPickerProps = {
323 className?: string;
324};
325
326export const CalendarMonthPicker = ({
327 className,
328}: CalendarMonthPickerProps) => {
329 const [month, setMonth] = useCalendarMonth();
330 const { locale } = useContext(CalendarContext);
331
332 // Memoize month data to avoid recalculating date formatting
333 const monthData = useMemo(() => {
334 return monthsForLocale(locale).map((month, index) => ({
335 value: index.toString(),
336 label: month,
337 }));
338 }, [locale]);
339
340 return (
341 <Combobox
342 className={className}
343 data={monthData}
344 labels={{
345 button: "Select month",
346 empty: "No month found",
347 search: "Search month",
348 }}
349 setValue={(value) =>
350 setMonth(Number.parseInt(value, 10) as CalendarState["month"])
351 }
352 value={month.toString()}
353 />
354 );
355};
356
357export type CalendarYearPickerProps = {
358 className?: string;
359 start: number;
360 end: number;
361};
362
363export const CalendarYearPicker = ({
364 className,
365 start,
366 end,
367}: CalendarYearPickerProps) => {
368 const [year, setYear] = useCalendarYear();
369
370 return (
371 <Combobox
372 className={className}
373 data={Array.from({ length: end - start + 1 }, (_, i) => ({
374 value: (start + i).toString(),
375 label: (start + i).toString(),
376 }))}
377 labels={{
378 button: "Select year",
379 empty: "No year found",
380 search: "Search year",
381 }}
382 setValue={(value) => setYear(Number.parseInt(value, 10))}
383 value={year.toString()}
384 />
385 );
386};
387
388export type CalendarDatePaginationProps = {
389 className?: string;
390};
391
392export const CalendarDatePagination = ({
393 className,
394}: CalendarDatePaginationProps) => {
395 const [month, setMonth] = useCalendarMonth();
396 const [year, setYear] = useCalendarYear();
397
398 const handlePreviousMonth = useCallback(() => {
399 if (month === 0) {
400 setMonth(11);
401 setYear(year - 1);
402 } else {
403 setMonth((month - 1) as CalendarState["month"]);
404 }
405 }, [month, year, setMonth, setYear]);
406
407 const handleNextMonth = useCallback(() => {
408 if (month === 11) {
409 setMonth(0);
410 setYear(year + 1);
411 } else {
412 setMonth((month + 1) as CalendarState["month"]);
413 }
414 }, [month, year, setMonth, setYear]);
415
416 return (
417 <div className={cn("flex items-center gap-2", className)}>
418 <Button onClick={handlePreviousMonth} size="icon" variant="ghost">
419 <ChevronLeftIcon size={16} />
420 </Button>
421 <Button onClick={handleNextMonth} size="icon" variant="ghost">
422 <ChevronRightIcon size={16} />
423 </Button>
424 </div>
425 );
426};
427
428export type CalendarDateProps = {
429 children: ReactNode;
430};
431
432export const CalendarDate = ({ children }: CalendarDateProps) => (
433 <div className="flex items-center justify-between p-3">{children}</div>
434);
435
436export type CalendarHeaderProps = {
437 className?: string;
438};
439
440export const CalendarHeader = ({ className }: CalendarHeaderProps) => {
441 const { locale, startDay } = useContext(CalendarContext);
442
443 // Memoize days data to avoid recalculating date formatting
444 const daysData = useMemo(() => {
445 return daysForLocale(locale, startDay);
446 }, [locale, startDay]);
447
448 return (
449 <div className={cn("grid flex-grow grid-cols-7", className)}>
450 {daysData.map((day) => (
451 <div className="p-3 text-right text-muted-foreground text-xs" key={day}>
452 {day}
453 </div>
454 ))}
455 </div>
456 );
457};
458
459export type CalendarItemProps = {
460 feature: Feature;
461 className?: string;
462};
463
464export const CalendarItem = memo(
465 ({ feature, className }: CalendarItemProps) => (
466 <div className={cn("flex items-center gap-2", className)}>
467 <div
468 className="h-2 w-2 shrink-0 rounded-full"
469 style={{
470 backgroundColor: feature.status.color,
471 }}
472 />
473 <span className="truncate">{feature.name}</span>
474 </div>
475 )
476);
477
478CalendarItem.displayName = "CalendarItem";
479
480export type CalendarProviderProps = {
481 locale?: Intl.LocalesArgument;
482 startDay?: number;
483 children: ReactNode;
484 className?: string;
485};
486
487export const CalendarProvider = ({
488 locale = "en-US",
489 startDay = 0,
490 children,
491 className,
492}: CalendarProviderProps) => (
493 <CalendarContext.Provider value={{ locale, startDay }}>
494 <div className={cn("relative flex flex-col", className)}>{children}</div>
495 </CalendarContext.Provider>
496);
497