Skip to content

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

Merged
merged 1 commit into from
Feb 25, 2025
Merged

Add calendar event management #2257

merged 1 commit into from
Feb 25, 2025

Conversation

vhpx
Copy link
Member

@vhpx vhpx commented Feb 25, 2025

Summary by CodeRabbit

  • New Features

    • Added a floating action button for quick event creation.
    • Introduced an event modal for creating, editing, and deleting calendar events.
    • Launched an intuitive date-time picker for streamlined scheduling.
    • Implemented new API endpoints to enhance calendar event management.
  • Enhancements

    • Improved event filtering and calendar grid layout.
    • Refined event card interactions for a smoother, more responsive experience.

@vhpx vhpx self-assigned this Feb 25, 2025
Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This 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

File(s) Change Summary
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/[eventId]/route.ts
apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.ts
Added API routes: individual event endpoints (GET, PUT, DELETE) and bulk event endpoints (GET with date range, POST) with Supabase queries and standardized error handling.
apps/web/src/components/calendar/Calendar.tsx
apps/web/src/components/calendar/CalendarCell.tsx
apps/web/src/components/calendar/CalendarEventMatrix.tsx
apps/web/src/components/calendar/EventCard.tsx
apps/web/src/components/calendar/EventModal.tsx
apps/web/src/components/calendar/MonthCalendar.tsx
Enhanced Calendar UI: integrated a floating CreateEventButton, removed deprecated components, introduced EventModal for event creation/editing, updated event filtering, styling, and interaction logic across cells, event cards, and calendar grids.
apps/web/src/hooks/useCalendar.tsx Overhauled CalendarContext: replaced useSWR with React Query, improved type definitions, and added methods/properties for CRUD operations and modal state management.
packages/ui/src/components/ui/date-time-picker.tsx Added a new DateTimePicker component that allows users to select a date and, optionally, a time with a calendar popover and time dropdowns.

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
Loading

Suggested labels

enhancement, rewise

Poem

I'm a bunny in the code garden, hopping with delight,
Through API routes and modal views that shine so bright.
With each click on the button, new features bloom,
In the ecosystem of code, there's always room.
My paws dance on keys, crafting changes with cheer,
Celebrating these updates, a carrot of joy is near!
Hop, hop, hooray!

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/[eventId]/route.ts

Oops! Something went wrong! :(

ESLint: 9.21.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

apps/web/src/components/calendar/CalendarEventMatrix.tsx

Oops! Something went wrong! :(

ESLint: 9.21.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

apps/web/src/app/api/v1/workspaces/[wsId]/calendar/events/route.ts

Oops! Something went wrong! :(

ESLint: 9.21.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@typescript-eslint/parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

  • 7 others
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 increments

The 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 selection

While 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 with useQuery.
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 older getModalStatus() and the new isModalOpen.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1f87aa and 974d2db.

📒 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 logic

The change to pass the day parameter to getCurrentEvents 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 logic

The 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:

  1. Fetches all events first
  2. Filters them based on the visible dates
  3. Handles all-day events (checking date ranges)
  4. Handles regular events (checking if event starts on the visible date)

45-45: Properly structured grid style

Using 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 rendering

The addition of col-span-full ensures events span across the entire grid properly, and using visibleEvents instead of all events improves rendering efficiency.

packages/ui/src/components/ui/date-time-picker.tsx (2)

18-22: Well-designed component interface

The props structure is clean and provides good flexibility with the optional date and showTimeSelect parameters.


32-44: Smart date selection handling

The 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 functionality

The simplified handleCreateEvent function correctly sets the time for new events without unnecessary date manipulation.


33-41: Improved UI feedback for event creation

The addition of title attributes and transition effects for the time indicators provides better user feedback and accessibility.


23-26: Enhanced styling with proper conditional classes

Using 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 prop wsId carefully.
The wsId 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.
Using isDragging and isResizing 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 to blue, 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 in getCurrentEvents.
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 with addEmptyEvent.
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.
Using activeEventId with 'new' for brand-new events and a stored ID for existing events is a clean approach. Toggling isModalHidden for show/hide states is tidy.

@vhpx vhpx merged commit 64ad2fb into main Feb 25, 2025
12 checks passed
@vhpx vhpx deleted the feat/improve-calendar branch February 25, 2025 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant