1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import { addDays, format, isSameDay, isToday } from "date-fns";
5import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
6import { Slot } from "radix-ui";
7import {
8 type ButtonHTMLAttributes,
9 type ComponentProps,
10 createContext,
11 type HTMLAttributes,
12 type MouseEventHandler,
13 type ReactNode,
14 useContext,
15} from "react";
16import { Button } from "@/components/ui/button";
17import { cn } from "@/lib/utils";
18
19// Context for sharing state between components
20type MiniCalendarContextType = {
21 selectedDate: Date | null | undefined;
22 onDateSelect: (date: Date) => void;
23 startDate: Date;
24 onNavigate: (direction: "prev" | "next") => void;
25 days: number;
26};
27
28const MiniCalendarContext = createContext<MiniCalendarContextType | null>(null);
29
30const useMiniCalendar = () => {
31 const context = useContext(MiniCalendarContext);
32
33 if (!context) {
34 throw new Error("MiniCalendar components must be used within MiniCalendar");
35 }
36
37 return context;
38};
39
40// Helper function to get array of consecutive dates
41const getDays = (startDate: Date, count: number): Date[] => {
42 const days: Date[] = [];
43 for (let i = 0; i < count; i++) {
44 days.push(addDays(startDate, i));
45 }
46 return days;
47};
48
49// Helper function to format date
50const formatDate = (date: Date) => {
51 const month = format(date, "MMM");
52 const day = format(date, "d");
53
54 return { month, day };
55};
56
57export type MiniCalendarProps = HTMLAttributes<HTMLDivElement> & {
58 value?: Date;
59 defaultValue?: Date;
60 onValueChange?: (date: Date | undefined) => void;
61 startDate?: Date;
62 defaultStartDate?: Date;
63 onStartDateChange?: (date: Date | undefined) => void;
64 days?: number;
65};
66
67export const MiniCalendar = ({
68 value,
69 defaultValue,
70 onValueChange,
71 startDate,
72 defaultStartDate = new Date(),
73 onStartDateChange,
74 days = 5,
75 className,
76 children,
77 ...props
78}: MiniCalendarProps) => {
79 const [selectedDate, setSelectedDate] = useControllableState<
80 Date | undefined
81 >({
82 prop: value,
83 defaultProp: defaultValue,
84 onChange: onValueChange,
85 });
86
87 const [currentStartDate, setCurrentStartDate] = useControllableState({
88 prop: startDate,
89 defaultProp: defaultStartDate,
90 onChange: onStartDateChange,
91 });
92
93 const handleDateSelect = (date: Date) => {
94 setSelectedDate(date);
95 };
96
97 const handleNavigate = (direction: "prev" | "next") => {
98 const newStartDate = addDays(
99 currentStartDate || new Date(),
100 direction === "next" ? days : -days
101 );
102 setCurrentStartDate(newStartDate);
103 };
104
105 const contextValue: MiniCalendarContextType = {
106 selectedDate: selectedDate || null,
107 onDateSelect: handleDateSelect,
108 startDate: currentStartDate || new Date(),
109 onNavigate: handleNavigate,
110 days,
111 };
112
113 return (
114 <MiniCalendarContext.Provider value={contextValue}>
115 <div
116 className={cn(
117 "flex items-center gap-2 rounded-lg border bg-background p-2",
118 className
119 )}
120 {...props}
121 >
122 {children}
123 </div>
124 </MiniCalendarContext.Provider>
125 );
126};
127
128export type MiniCalendarNavigationProps =
129 ButtonHTMLAttributes<HTMLButtonElement> & {
130 direction: "prev" | "next";
131 asChild?: boolean;
132 };
133
134export const MiniCalendarNavigation = ({
135 direction,
136 asChild = false,
137 children,
138 onClick,
139 ...props
140}: MiniCalendarNavigationProps) => {
141 const { onNavigate } = useMiniCalendar();
142 const Icon = direction === "prev" ? ChevronLeftIcon : ChevronRightIcon;
143
144 const handleClick: MouseEventHandler<HTMLButtonElement> = (event) => {
145 onNavigate(direction);
146 onClick?.(event);
147 };
148
149 if (asChild) {
150 return (
151 <Slot.Root onClick={handleClick} {...props}>
152 {children}
153 </Slot.Root>
154 );
155 }
156
157 return (
158 <Button
159 onClick={handleClick}
160 size={asChild ? undefined : "icon"}
161 type="button"
162 variant={asChild ? undefined : "ghost"}
163 {...props}
164 >
165 {children ?? <Icon className="size-4" />}
166 </Button>
167 );
168};
169
170export type MiniCalendarDaysProps = Omit<
171 HTMLAttributes<HTMLDivElement>,
172 "children"
173> & {
174 children: (date: Date) => ReactNode;
175};
176
177export const MiniCalendarDays = ({
178 className,
179 children,
180 ...props
181}: MiniCalendarDaysProps) => {
182 const { startDate, days: dayCount } = useMiniCalendar();
183 const days = getDays(startDate, dayCount);
184
185 return (
186 <div className={cn("flex items-center gap-1", className)} {...props}>
187 {days.map((date) => children(date))}
188 </div>
189 );
190};
191
192export type MiniCalendarDayProps = ComponentProps<typeof Button> & {
193 date: Date;
194};
195
196export const MiniCalendarDay = ({
197 date,
198 className,
199 ...props
200}: MiniCalendarDayProps) => {
201 const { selectedDate, onDateSelect } = useMiniCalendar();
202 const { month, day } = formatDate(date);
203 const isSelected = selectedDate && isSameDay(date, selectedDate);
204 const isTodayDate = isToday(date);
205
206 return (
207 <Button
208 className={cn(
209 "h-auto min-w-[3rem] flex-col gap-0 p-2 text-xs",
210 isTodayDate && !isSelected && "bg-accent",
211 className
212 )}
213 onClick={() => onDateSelect(date)}
214 size="sm"
215 type="button"
216 variant={isSelected ? "default" : "ghost"}
217 {...props}
218 >
219 <span
220 className={cn(
221 "font-medium text-[10px] text-muted-foreground",
222 isSelected && "text-primary-foreground/70"
223 )}
224 >
225 {month}
226 </span>
227 <span className="font-semibold text-sm">{day}</span>
228 </Button>
229 );
230};
231