-
-
Notifications
You must be signed in to change notification settings - Fork 19
Add calendar event management #2257
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis update adds new API endpoints for managing calendar events and introduces several UI enhancements. Two API route files now handle event-specific operations (GET, PUT, DELETE) and bulk event operations (GET, POST) for workspaces using Supabase. Several calendar components have been modified, including the addition of a floating create event button and new modal for event creation/editing. The calendar cells, event matrix, event card, and month calendar now incorporate updated filtering, styling, and interactive behaviors. Additionally, the calendar context hook has been overhauled for improved type safety with React Query, and a new DateTimePicker component has been introduced. Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant CEB as CreateEventButton
participant HC as useCalendar Hook
participant EM as EventModal
participant API as POST /calendar/events API
participant DB as Database (Supabase)
U->>CEB: Click "Create Event"
CEB->>HC: Trigger modal open
HC->>EM: Render EventModal
U->>EM: Fill in event details and click "Save"
EM->>HC: Invoke addEvent() with event data
HC->>API: Send POST request with event payload
API->>DB: Insert new event
DB-->>API: Return created event
API-->>HC: Respond with success data
HC-->>EM: Update modal state and close
EM-->>U: Display newly created event
Suggested labels
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure. 🔧 ESLint
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/[eventId]/route.tsOops! Something went wrong! :( ESLint: 9.21.0 Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs apps/web/src/components/calendar/CalendarEventMatrix.tsxOops! Something went wrong! :( ESLint: 9.21.0 Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.tsOops! Something went wrong! :( ESLint: 9.21.0 Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Nitpick comments (10)
packages/ui/src/components/ui/date-time-picker.tsx (2)
65-73
: Consider using constants for time incrementsThe hard-coded values for generating hour and minute options work well, but consider extracting the minute increment (5) to a named constant for better maintainability.
+const MINUTE_INCREMENT = 5; // Generate hour and minute options const hours = Array.from({ length: 24 }, (_, i) => { const hour = i.toString().padStart(2, '0'); return { value: hour, label: hour }; }); -const minutes = Array.from({ length: 12 }, (_, i) => { - const minute = (i * 5).toString().padStart(2, '0'); +const minutes = Array.from({ length: 60 / MINUTE_INCREMENT }, (_, i) => { + const minute = (i * MINUTE_INCREMENT).toString().padStart(2, '0'); return { value: minute, label: minute }; });
104-135
: Consider accessibility improvements for time selectionWhile the time selection UI works well, consider adding aria-label attributes to the hour and minute selects to improve screen reader support.
<Select value={date ? format(date, 'HH') : undefined} onValueChange={handleHourChange} > - <SelectTrigger className="w-[70px]"> + <SelectTrigger className="w-[70px]" aria-label="Select hour"> <SelectValue placeholder="Hour" /> </SelectTrigger> <SelectContent> {hours.map((hour) => ( <SelectItem key={hour.value} value={hour.value}> {hour.label} </SelectItem> ))} </SelectContent> </Select> <span className="text-muted-foreground">:</span> <Select value={date ? format(date, 'mm') : undefined} onValueChange={handleMinuteChange} > - <SelectTrigger className="w-[70px]"> + <SelectTrigger className="w-[70px]" aria-label="Select minute"> <SelectValue placeholder="Min" /> </SelectTrigger> <SelectContent> {minutes.map((minute) => ( <SelectItem key={minute.value} value={minute.value}> {minute.label} </SelectItem> ))} </SelectContent> </Select>apps/web/src/components/calendar/EventModal.tsx (2)
37-38
: Consider using a constant for default event duration.Setting the default end time to be 1 hour after start time is a good UX pattern, but this logic is duplicated between the initial state and the reset logic in the useEffect.
- const [event, setEvent] = useState<Partial<CalendarEvent>>({ - title: '', - description: '', - start_at: new Date().toISOString(), - end_at: new Date(new Date().getTime() + 60 * 60 * 1000).toISOString(), // Default to 1 hour - color: 'blue', - }); + const DEFAULT_DURATION_MS = 60 * 60 * 1000; // 1 hour in milliseconds + + const [event, setEvent] = useState<Partial<CalendarEvent>>({ + title: '', + description: '', + start_at: new Date().toISOString(), + end_at: new Date(new Date().getTime() + DEFAULT_DURATION_MS).toISOString(), + color: 'blue', + });Then use this constant in the reset logic as well (at line 64).
136-153
: Consider adding a validation for multi-day all-day events.The current implementation sets all-day events to start at 00:00 and end at 23:59:59.999 of the same day. This works for single-day events but doesn't properly handle multi-day all-day events.
const handleAllDayChange = (checked: boolean) => { setIsAllDay(checked); if (checked) { // Set times to start of day and end of day const startDate = new Date(event.start_at || ''); startDate.setHours(0, 0, 0, 0); - const endDate = new Date(event.end_at || ''); + // Preserve multi-day events by only changing the time portion + // If start and end dates are different, maintain the end date + const endDate = new Date(event.end_at || ''); + const sameDay = startDate.toDateString() === endDate.toDateString(); + + // If it's the same day or a newly created event, set end to 23:59:59.999 endDate.setHours(23, 59, 59, 999); setEvent((prev) => ({ ...prev, start_at: startDate.toISOString(), end_at: endDate.toISOString(), })); } };apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.ts (1)
27-44
: Add date format validation for enhanced error handling.The current implementation assumes valid date strings in the query parameters but doesn't handle potential date parsing errors.
try { + // Validate date formats + try { + const startDate = new Date(start_at); + const endDate = new Date(end_at); + + if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) { + return NextResponse.json( + { error: 'Invalid date format' }, + { status: 400 } + ); + } + } catch (e) { + return NextResponse.json( + { error: 'Invalid date format' }, + { status: 400 } + ); + } + const { data: events, error } = await supabase .from('workspace_calendar_events') .select('*') .eq('ws_id', wsId) .gte('start_at', new Date(start_at).toISOString()) .lte('end_at', new Date(end_at).toISOString());apps/web/src/components/calendar/Calendar.tsx (1)
272-276
: Consider adding context for screen readers.While the button has screen reader text, it would be helpful to add an aria-label to the modal for better accessibility.
{/* Event Creation/Editing Modal */} - <EventModal /> + <EventModal aria-label="Calendar event form" /> {/* Floating action button */} <CreateEventButton />apps/web/src/components/calendar/EventCard.tsx (1)
145-225
: Repeated logic for drag and resize can be extracted into a reusable hook.
Both blocks manage similar mouse events, dynamic styling, and server updates. Refactoring them into a dedicated hook (e.g.,useResizeAndDrag
) can reduce duplication and improve maintainability.apps/web/src/hooks/useCalendar.tsx (3)
70-139
: Query-based approach for the entire month withuseQuery
.
Fetching events for the active month is logical. However, if your calendar view changes to multi-month or infinite scrolling, you may need to dynamically adjust the date range or provide a more flexible approach.
194-225
: Recursively computing overlap levels might cause performance issues for many events.
getEventLevel
calls itself to handle overlaps. In large calendars with many events, repeated recursion could become expensive. Caching or iterative logic might help performance.
460-473
: Legacy and new APIs are well integrated.
Maintaining backward compatibility is helpful. Just stay cautious about potential usage conflicts between the oldergetModalStatus()
and the newisModalOpen
.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/[eventId]/route.ts
(1 hunks)apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.ts
(1 hunks)apps/web/src/components/calendar/Calendar.tsx
(4 hunks)apps/web/src/components/calendar/CalendarCell.tsx
(1 hunks)apps/web/src/components/calendar/CalendarEventMatrix.tsx
(1 hunks)apps/web/src/components/calendar/EventCard.tsx
(2 hunks)apps/web/src/components/calendar/EventModal.tsx
(1 hunks)apps/web/src/components/calendar/MonthCalendar.tsx
(1 hunks)apps/web/src/hooks/useCalendar.tsx
(4 hunks)packages/ui/src/components/ui/date-time-picker.tsx
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Deploy-Preview
🔇 Additional comments (25)
apps/web/src/components/calendar/MonthCalendar.tsx (1)
159-159
: Good improvement to event retrieval logicThe change to pass the
day
parameter togetCurrentEvents
ensures that only events for the specific calendar day are retrieved, which is likely more efficient than fetching all events regardless of date.apps/web/src/components/calendar/CalendarEventMatrix.tsx (3)
10-35
: Enhanced event filtering logicThe new implementation properly filters events based on visibility in the calendar view, with distinct handling for all-day events versus regular events. This is a significant improvement over the previous approach.
The logic correctly:
- Fetches all events first
- Filters them based on the visible dates
- Handles all-day events (checking date ranges)
- Handles regular events (checking if event starts on the visible date)
45-45
: Properly structured grid styleUsing dynamic grid template columns based on the dates array length ensures the calendar will adapt correctly to different view configurations.
46-47
: Improved layout and event renderingThe addition of
col-span-full
ensures events span across the entire grid properly, and usingvisibleEvents
instead of all events improves rendering efficiency.packages/ui/src/components/ui/date-time-picker.tsx (2)
18-22
: Well-designed component interfaceThe props structure is clean and provides good flexibility with the optional date and showTimeSelect parameters.
32-44
: Smart date selection handlingThe handleSelect function correctly preserves the time when selecting a new date, which provides a better user experience when modifying existing events.
apps/web/src/components/calendar/CalendarCell.tsx (3)
14-18
: Streamlined event creation functionalityThe simplified handleCreateEvent function correctly sets the time for new events without unnecessary date manipulation.
33-41
: Improved UI feedback for event creationThe addition of title attributes and transition effects for the time indicators provides better user feedback and accessibility.
23-26
: Enhanced styling with proper conditional classesUsing the cn utility for class name management improves code readability and maintainability. The hover effect provides good visual feedback.
apps/web/src/components/calendar/EventModal.tsx (1)
119-125
: LGTM! Good handling of automatic date adjustment.The logic to automatically push end time forward when start time is moved later is a great UX improvement.
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.ts (1)
20-25
: Good validation of required query parameters.Proper validation of the required query parameters with a clear error message.
apps/web/src/components/calendar/Calendar.tsx (2)
19-39
: Well-structured floating action button for event creation.The CreateEventButton component is well-implemented with proper accessibility features including tooltip and screen reader text.
238-244
: Good use of dynamic class names based on view.The conditional class names for different calendar views enhance the layout appropriately.
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/[eventId]/route.ts (1)
69-90
: LGTM! Well-structured DELETE endpoint.The DELETE endpoint is properly implemented with good error handling and appropriate response message.
apps/web/src/components/calendar/EventCard.tsx (5)
14-15
: Remove unused propwsId
carefully.
ThewsId
prop has been removed, but please confirm there's no external reference relying on it. If it was once used downstream or for event-level calculations, ensure that all calls are indeed updated.
36-37
: Good addition of local states for dragging/resizing.
UsingisDragging
andisResizing
to manage interactions is clear and intuitive. No issues here.
39-84
: Potential concern with single.calendar-cell
query.
document.querySelector('.calendar-cell')
might only capture the first cell if multiple cells are rendered. If each day cell has the same class, you could be unintentionally placing all events in the first matching element. Ensure that.calendar-cell
is unique or handle multiple cells properly.
242-294
: Color styles configuration is comprehensive.
Defining a well-structured record for color classes is good. Just ensure you handle unexpected color values gracefully. If external code passes an unsupported color, it defaults toblue
, which is fine.
295-339
: Clean and cohesive event card UI rendering.
The JSX layout clearly differentiates content and resize handle. The double-click event to open the modal is intuitive. Everything looks consistent with your drag/resize states.apps/web/src/hooks/useCalendar.tsx (6)
1-61
: Improved context typing is valuable.
Defining explicit return types for each method (e.g.,getEvent
,updateEvent
) clarifies usage. The default no-ops ensure no crashes if the context is uninitialized. Good practice.
141-174
: Watch out for date edge cases ingetCurrentEvents
.
When events span midnight or vary in hours, ensuring correctness for partial-day events might require more robust checks. Also, consider cross-month or cross-year spans if needed.
227-265
:addEvent
error handling looks reasonable.
You catch Supabase errors and refresh the query cache. Looks solid. Just ensure that any front-end error states (toasts, alerts) are displayed if it fails, so users are aware of the issue.
268-294
: Nice approach to pending events withaddEmptyEvent
.
Storing intermediate event data in state simplifies the logic. Confirm that newly created events outside the current month are either fetched or intentionally clipped.
349-380
: Clearing pending new events is straightforward.
The flow for deleting unsaved events is well-handled. Good job ensuring you refresh the cache for consistent local and remote state.
382-445
: Modal logic is intuitive.
UsingactiveEventId
with'new'
for brand-new events and a stored ID for existing events is a clean approach. TogglingisModalHidden
for show/hide states is tidy.
Summary by CodeRabbit
New Features
Enhancements