Skip to content

Enhance UI, add save button #3333

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft

Conversation

datnguyen-en
Copy link
Collaborator

@datnguyen-en datnguyen-en commented Jul 24, 2025

Summary by CodeRabbit

  • New Features

    • Added a "Save" button to the availability planner, allowing users to manually save their selected time blocks.
    • The save button indicates saving progress and is only enabled when there are unsaved changes.
  • Improvements

    • Enhanced alignment and spacing for availability and plan details sections to provide a more visually consistent and centered layout across devices.
    • Availability planner now supports external styling via an optional class setting.
    • Improved responsiveness and spacing for plan details and availability components.
    • Containers and titles now have consistent minimum widths and centered text for better visual balance.
  • Refactor

    • Time block synchronization is now performed manually via the "Save" button, rather than automatically, giving users more control over when changes are saved.

Copy link
Contributor

github-actions bot commented Jul 24, 2025

🔧 Biome Check Report

Issues Found: 0

📊 Analysis Summary

Metric Value Status
📁 Files Checked ✅ Complete
⚠️ Total Issues 0 ✅ All clear

🔍 Issue Breakdown

Issue Type Count Status
Errors ✅ None
⚠️ Warnings ✅ None
📝 Total Issues NaN 🎯 Perfect!

🎉 All Issues Resolved!

Your code is now 100% clean! Great job! 🏆


🤖 Auto-generated by Biome Check workflow • Last updated: 7/24/2025, 8:26:17 AM

Copy link

vercel bot commented Jul 24, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Updated (UTC)
calendar ⬜️ Skipped (Inspect) Jul 24, 2025 8:25am
nova ⬜️ Skipped (Inspect) Jul 24, 2025 8:25am
rewise ⬜️ Skipped (Inspect) Jul 24, 2025 8:25am

Copy link
Contributor

coderabbitai bot commented Jul 24, 2025

Walkthrough

The changes update the layout and alignment of several UI components related to plan availability and details, introducing explicit styling adjustments for improved centering and spacing. The AvailabilityPlanner component is enhanced with save functionality, tracking unsaved changes and synchronizing time blocks with the server via a new context-exposed syncTimeBlocks method. The synchronization logic is refactored to be manually triggered rather than automatic.

Changes

File(s) Summary
.../plans/[planId]/all-availabilities.tsx
.../plans/[planId]/plan-details-client.tsx
Updated container and element classes for improved centering, spacing, and layout; no logic changes.
.../plans/[planId]/availability-planner.tsx Enhanced with save functionality, local state for saving/dirty, UI for save button, and optional className prop.
.../plans/[planId]/time-blocking-provider.tsx Refactored time block sync logic: moved from automatic useEffect to explicit context method syncTimeBlocks.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AvailabilityPlanner
    participant TimeBlockingProvider
    participant Server

    User->>AvailabilityPlanner: Edit time blocks
    AvailabilityPlanner->>AvailabilityPlanner: Mark as dirty
    User->>AvailabilityPlanner: Click "Save"
    AvailabilityPlanner->>TimeBlockingProvider: syncTimeBlocks()
    TimeBlockingProvider->>Server: Fetch current time blocks
    TimeBlockingProvider->>Server: Add/remove time blocks as needed
    Server-->>TimeBlockingProvider: Responds with updated time blocks
    TimeBlockingProvider->>AvailabilityPlanner: Update local state
    AvailabilityPlanner->>User: Show saved state
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Suggested reviewers

  • vhpx

Poem

In fields of code, a bunny leaps,
Centering divs and layouts neat,
A save button sparkles, sync takes flight,
Time blocks align from left to right.
With paws on keys and whiskers twitch,
This rabbit’s work is quite the switch!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4ea78b and 670b3fe.

📒 Files selected for processing (1)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/availability-planner.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/availability-planner.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Deploy-Preview
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-save-button-tumeet

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @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

graphite-app bot commented Jul 24, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @datnguyen-en, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant enhancement to the user experience by providing explicit control over saving time block availability. It refactors the underlying synchronization mechanism from an automatic process to a user-initiated action via a new 'Save' button, alongside general UI improvements for better presentation and responsiveness.

Highlights

  • Manual Save Functionality: Implemented a 'Save' button within the AvailabilityPlanner component. This button allows users to explicitly save their time block changes, tracking a 'dirty' state to indicate unsaved modifications and displaying a 'Saving...' state during the process.
  • Time Block Synchronization Refactor: The logic for synchronizing time blocks with the backend, previously an automatic process triggered by a useEffect in TimeBlockingProvider, has been refactored into an explicit syncTimeBlocks function. This function is now exposed via the TimeBlockContext for manual invocation by the new save button.
  • UI Enhancements: Minor layout and styling adjustments were made across several components (AllAvailabilities, AvailabilityPlanner, PlanDetailsClient) to improve centering, spacing, and overall responsiveness, including setting minimum widths for certain UI elements.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

codecov bot commented Jul 24, 2025

Codecov Report

Attention: Patch coverage is 0% with 138 lines in your changes missing coverage. Please review.

Project coverage is 1.49%. Comparing base (60d90bd) to head (670b3fe).

Files with missing lines Patch % Lines
...together/plans/[planId]/time-blocking-provider.tsx 0.00% 89 Missing ⚠️
...t-together/plans/[planId]/availability-planner.tsx 0.00% 40 Missing ⚠️
...eet-together/plans/[planId]/all-availabilities.tsx 0.00% 7 Missing ⚠️
...et-together/plans/[planId]/plan-details-client.tsx 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3333      +/-   ##
==========================================
- Coverage    1.50%    1.49%   -0.01%     
==========================================
  Files        1918     1918              
  Lines      248066   248083      +17     
  Branches     2605     2601       -4     
==========================================
- Hits         3721     3718       -3     
- Misses     242779   242799      +20     
  Partials     1566     1566              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@vercel vercel bot temporarily deployed to Preview – calendar July 24, 2025 08:25 Inactive
@vercel vercel bot temporarily deployed to Preview – rewise July 24, 2025 08:25 Inactive
@vercel vercel bot temporarily deployed to Preview – nova July 24, 2025 08:25 Inactive
@datnguyen-en datnguyen-en self-assigned this Jul 24, 2025
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: 4

🔭 Outside diff range comments (1)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/time-blocking-provider.tsx (1)

277-390: Refactor complex sync function and add error handling

The syncTimeBlocks function is quite complex and lacks error handling. Consider breaking it down into smaller functions and adding proper error handling.

Here's a suggested refactoring approach:

+  const compareTimeblocks = (tb1: Timeblock, tb2: Timeblock) => 
+    tb1.date === tb2.date &&
+    tb1.start_time === tb2.start_time &&
+    tb1.end_time === tb2.end_time;
+
+  const findTimeblocksToSync = (serverTimeblocks: Timeblock[], localTimeblocks: Timeblock[]) => {
+    const toRemove = serverTimeblocks.filter(
+      server => !localTimeblocks.some(local => compareTimeblocks(local, server))
+    );
+    const toAdd = localTimeblocks.filter(
+      local => !serverTimeblocks.some(server => compareTimeblocks(server, local))
+    );
+    return { toRemove, toAdd };
+  };

   const syncTimeBlocks = useCallback(async () => {
     if (!plan.id || !user?.id) return;

     const fetchCurrentTimeBlocks = async (planId: string) => {
-      const res = await fetch(`/api/meet-together/plans/${planId}/timeblocks`);
-      if (!res.ok) return [];
-      const timeblocks = (await res.json()) as Timeblock[];
+      try {
+        const res = await fetch(`/api/meet-together/plans/${planId}/timeblocks`);
+        if (!res.ok) throw new Error(`Failed to fetch timeblocks: ${res.status}`);
+        const timeblocks = (await res.json()) as Timeblock[];
+      } catch (error) {
+        console.error('Error fetching timeblocks:', error);
+        throw error;
+      }

Also consider implementing batch operations instead of multiple individual API calls.

🧹 Nitpick comments (4)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/all-availabilities.tsx (1)

38-38: Remove redundant text-center class

The parent div already has text-center class, making this redundant.

-      <div className="text-center font-semibold">
+      <div className="font-semibold">
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/plan-details-client.tsx (1)

146-146: Consider reducing the extra-large gap value

The xl:gap-80 (20rem/320px) gap seems excessive and might cause layout issues on ultra-wide screens, pushing the content too far apart.

-          <div className="mx-auto mt-8 flex w-full flex-col items-center justify-center gap-8 md:flex-row md:gap-16 lg:gap-32 xl:gap-80">
+          <div className="mx-auto mt-8 flex w-full flex-col items-center justify-center gap-8 md:flex-row md:gap-16 lg:gap-32 xl:gap-48">
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/availability-planner.tsx (1)

64-72: Extract inline styles to Tailwind classes

The extensive inline styles on the button could be replaced with Tailwind classes for better maintainability.

       <button
-        className="mx-auto mt-8 block rounded-full bg-gradient-to-r from-indigo-500 via-sky-500 to-emerald-500 px-8 py-3 text-lg font-semibold text-white shadow-md transition-all duration-150 ease-in-out hover:scale-105 hover:from-indigo-600 hover:via-sky-600 hover:to-emerald-600 focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:outline-none active:scale-100 disabled:cursor-not-allowed disabled:from-gray-400 disabled:via-gray-400 disabled:to-gray-400"
-        style={{
-          minWidth: '120px',
-          minHeight: '48px',
-          letterSpacing: '0.01em',
-        }}
+        className="mx-auto mt-8 block min-w-[120px] min-h-12 rounded-full bg-gradient-to-r from-indigo-500 via-sky-500 to-emerald-500 px-8 py-3 text-lg font-semibold text-white shadow-md transition-all duration-150 ease-in-out hover:scale-105 hover:from-indigo-600 hover:via-sky-600 hover:to-emerald-600 focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:outline-none active:scale-100 disabled:cursor-not-allowed disabled:from-gray-400 disabled:via-gray-400 disabled:to-gray-400 tracking-tight"
         onClick={handleSave}
         disabled={!dirty || isSaving}
       >
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/time-blocking-provider.tsx (1)

325-327: Optimize API calls with batch operations

Multiple sequential API calls using Promise.all with individual requests could be optimized with batch endpoints.

Instead of:

await Promise.all(
  localTimeblocks.map((timeblock) => addTimeBlock(timeblock))
);

Consider implementing batch endpoints:

await fetch(`/api/meet-together/plans/${planId}/timeblocks/batch`, {
  method: 'POST',
  body: JSON.stringify({ 
    timeblocks: localTimeblocks,
    user_id: user?.id 
  }),
});

This would reduce the number of HTTP requests and improve performance, especially when syncing many timeblocks.

Also applies to: 331-333, 376-384

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60d90bd and d4ea78b.

📒 Files selected for processing (4)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/all-availabilities.tsx (1 hunks)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/availability-planner.tsx (2 hunks)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/plan-details-client.tsx (1 hunks)
  • apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/time-blocking-provider.tsx (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DennieDan
PR: tutur3u/platform#2891
File: packages/ui/src/hooks/use-calendar.tsx:1511-1513
Timestamp: 2025-05-21T09:22:15.348Z
Learning: In the `GoogleCalendarSettings` component's `handleSyncNow` function, the boolean return value from `syncGoogleCalendarNow` is used to determine if changes were made during a successful sync, while errors are handled through a separate try/catch block with detailed error messages.
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/time-blocking-provider.tsx (1)

Learnt from: DennieDan
PR: #2891
File: packages/ui/src/hooks/use-calendar.tsx:1511-1513
Timestamp: 2025-05-21T09:22:15.348Z
Learning: In the GoogleCalendarSettings component's handleSyncNow function, the boolean return value from syncGoogleCalendarNow is used to determine if changes were made during a successful sync, while errors are handled through a separate try/catch block with detailed error messages.

🧬 Code Graph Analysis (2)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/plan-details-client.tsx (1)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/edit-plan-dialog.tsx (1)
  • EditPlanDialog (53-235)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/availability-planner.tsx (2)
packages/types/src/primitives/MeetTogetherPlan.ts (1)
  • MeetTogetherPlan (1-13)
apps/web/src/app/[locale]/(marketing)/meet-together/plans/[planId]/time-blocking-provider.tsx (1)
  • useTimeBlocking (435-435)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Deploy-Preview
  • GitHub Check: Verify generated types
  • GitHub Check: Deploy-Preview
  • GitHub Check: Deploy-Preview

@datnguyen-en datnguyen-en requested review from vhpx and VNOsST July 24, 2025 08:28
@VNOsST
Copy link
Collaborator

VNOsST commented Jul 24, 2025

Can you resolve all of the AI-generated reviews? If it looks good integrate them into the code, if not you can just resolve them and report back. I'll put this as draft for now, you can decide again later on.

@VNOsST VNOsST marked this pull request as draft July 24, 2025 08:31
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request enhances the UI by adding a save button and improving the layout of the availability planner. It also introduces a syncTimeBlocks function to synchronize time blocks between the client and server. The review focuses on error handling and potential improvements to the useEffect hook.

Comment on lines 317 to 318
);
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

It's crucial to handle potential errors when calling removeTimeBlock. If removeTimeBlock fails, the application state might become inconsistent between the client and server. Implement error handling to catch any exceptions thrown by removeTimeBlock and take appropriate action, such as logging the error or displaying an error message to the user. This will improve the reliability and robustness of the application.

    if (timeblocksToRemove.length > 0)
      await Promise.all(
        timeblocksToRemove.map(async (timeblock) => {
          try {
            if (timeblock.id) await removeTimeBlock(timeblock);
          } catch (error) {
            console.error("Failed to remove timeblock:", error);
            // Handle error appropriately, e.g., display a message to the user
          }
        })
      );

Comment on lines +324 to 327
if (serverTimeblocks.length === 0 && localTimeblocks.length > 0) {
await Promise.all(
localTimeblocks.map((timeblock) => addTimeBlock(timeblock))
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

It's crucial to handle potential errors when calling addTimeBlock. If addTimeBlock fails, the application state might become inconsistent between the client and server. Implement error handling to catch any exceptions thrown by addTimeBlock and take appropriate action, such as logging the error or displaying an error message to the user. This will improve the reliability and robustness of the application.

    if (serverTimeblocks.length === 0 && localTimeblocks.length > 0) {
      await Promise.all(
        localTimeblocks.map(async (timeblock) => {
          try {
            await addTimeBlock(timeblock);
          } catch (error) {
            console.error("Failed to add timeblock:", error);
            // Handle error appropriately, e.g., display a message to the user
          }
        })
      );
      return;
    }

Comment on lines +381 to +384
if (timeblocksToAdd.length > 0)
await Promise.all(
timeblocksToAdd.map((timeblock) => addTimeBlock(timeblock))
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

It's crucial to handle potential errors when calling addTimeBlock. If addTimeBlock fails, the application state might become inconsistent between the client and server. Implement error handling to catch any exceptions thrown by addTimeBlock and take appropriate action, such as logging the error or displaying an error message to the user. This will improve the reliability and robustness of the application.

    if (timeblocksToAdd.length > 0)
      await Promise.all(
        timeblocksToAdd.map(async (timeblock) => {
          try {
            await addTimeBlock(timeblock);
          } catch (error) {
            console.error("Failed to add timeblock:", error);
            // Handle error appropriately, e.g., display a message to the user
          }
        })
      );

Comment on lines +385 to +390
const syncedServerTimeblocks = await fetchCurrentTimeBlocks(plan?.id);
setSelectedTimeBlocks({
planId: plan.id,
data: syncedServerTimeblocks,
});
}, [plan.id, user, selectedTimeBlocks]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Consider adding a try-catch block around the fetchCurrentTimeBlocks call to handle potential network errors or server-side issues. If the fetch fails, log the error and potentially retry the fetch after a delay. This will make the application more resilient to transient network issues and improve the user experience.

    try {
      const syncedServerTimeblocks = await fetchCurrentTimeBlocks(plan?.id);
      setSelectedTimeBlocks({
        planId: plan.id,
        data: syncedServerTimeblocks,
      });
    } catch (error) {
      console.error("Failed to fetch current timeblocks:", error);
      // Handle error appropriately, e.g., display a message to the user or retry the fetch
    }

Comment on lines +25 to +29
useEffect(() => {
if (!editing.enabled) {
setDirty(true);
}
}, [editing.enabled]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider adding a dependency array to the useEffect hook that includes dirty. This will ensure that the effect is triggered whenever the dirty state changes, preventing potential issues where the component doesn't react to changes in the dirty state as expected. This is especially important if other parts of your component rely on the dirty state to be up-to-date.

  useEffect(() => {
    if (!editing.enabled) {
      setDirty(true);
    }
  }, [editing.enabled, dirty]);

@@ -290,12 +304,10 @@ const TimeBlockingProvider = ({

const removeTimeBlock = async (timeblock: Timeblock) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider adding a check to ensure timeblock.id exists before attempting to remove the timeblock. This will prevent potential errors if a timeblock without an ID is accidentally passed to the removeTimeBlock function.

    if (timeblocksToRemove.length > 0)
      await Promise.all(
        timeblocksToRemove.map((timeblock) =>
          timeblock.id ? removeTimeBlock(timeblock) : null
        )
      );

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.

2 participants