Skip to content
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] Switch to Sonner for toast notifications #9394 #9405

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

nilay-v3rma
Copy link

@nilay-v3rma nilay-v3rma commented Dec 13, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new Toaster component for improved toast notifications.
  • Bug Fixes

    • Enhanced error handling in the DailyRounds component for clearer error reporting.
  • Chores

    • Updated dependencies by removing PNotify and adding Sonner and next-themes.
    • Removed unused CSS imports related to PNotify.
  • Refactor

    • Streamlined notification handling by replacing PNotify with Sonner across various components.

@nilay-v3rma nilay-v3rma requested a review from a team as a code owner December 13, 2024 06:38
Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

The pull request includes significant modifications to the notification handling system of the application. It transitions from using the PNotify library to the Sonner library for toast notifications. This involves removing PNotify dependencies from package.json, updating notification functions in Notifications.js, and adjusting components to utilize Sonner's API. Additionally, the Toaster component has been replaced with a new implementation that integrates with Sonner. The changes enhance the notification system's simplicity and maintainability.

Changes

File Change Summary
package.json Removed dependencies: @pnotify/core, @pnotify/mobile; Added: next-themes, sonner.
src/App.tsx Updated import path for Toaster from @/components/ui/toaster to @/components/ui/sonner.
src/CAREUI/icons/Index.tsx Removed useToast hook; replaced with direct toast calls from sonner.
src/Utils/Notifications.js Replaced PNotify notifications with Sonner; updated notification functions to use toast methods.
src/components/Patient/DailyRounds.tsx Enhanced error handling and refined form submission logic based on rounds_type.
src/components/ui/sonner.tsx Introduced new Toaster component utilizing Sonner and next-themes.
src/components/ui/toast.tsx Deleted file containing PNotify-based toast components.
src/components/ui/toaster.tsx Deleted file containing the old Toaster component.
src/hooks/useToast.ts Deleted custom hook for managing toast notifications.
src/style/index.css Removed PNotify-related CSS imports.

Assessment against linked issues

Objective Addressed Explanation
Switch to using Sonner for in-app toast notifications (#[9394])
Remove existing PNotify components to avoid conflicts (#[9394])
Update notification functions to use Sonner (#[9394])
Uninstall PNotify and related packages (#[9394])
Add development docs on changes (#[9394]) Documentation updates are not included.

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan
  • khavinshankar

🐇 In the meadow, notifications bloom,
From PNotify's shadow, we make room.
With Sonner's grace, our toasts now fly,
A simpler path, we wave goodbye!
Hopping along, our code's in tune,
Toasting successes, like flowers in June! 🌼


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. (Experiment)
  • @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

netlify bot commented Dec 13, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 5c0f052
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675bd6576d66370008101f09
😎 Deploy Preview https://deploy-preview-9405--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Outside diff range and nitpick comments (5)
src/components/ui/sonner.tsx (1)

9-28: Consider extracting theme-specific styles to a constants file

The implementation looks good, but the long class names for different toast elements could be moved to a separate constants file for better maintainability.

Consider creating a toasterStyles.ts:

export const TOAST_STYLES = {
  toast: "group toast group-[.toaster]:bg-white ...",
  description: "group-[.toast]:text-gray-500 ...",
  // ... other styles
};

Then import and use it in the component:

-      classNames: {
-        toast: "group toast group-[.toaster]:bg-white...",
-        description: "group-[.toast]:text-gray-500...",
+      classNames: TOAST_STYLES,
src/Utils/Notifications.js (3)

41-43: Consider adding error message sanitization.

While the error message handling is functional, consider sanitizing the error message before displaying it to prevent potential XSS attacks through error messages.

-  toast.error(errorMsg, { duration: 5000 });
+  const sanitizedMsg = DOMPurify.sanitize(errorMsg);
+  toast.error(sanitizedMsg, { duration: 5000 });

46-50: Consider adding a return value for closeAllNotifications.

The function should return a boolean or Promise to indicate whether the operation was successful.

 export const closeAllNotifications = () => {
   // Sonner doesn't require a close method, but you can manage this with custom logic if needed
   // Example: toast.dismiss() could be used to close all toasts if necessary.
-  toast.dismiss();
+  toast.dismiss();
+  return true;
 };

54-55: Standardize notification durations.

Consider extracting duration values into constants to maintain consistency across different notification types.

+const NOTIFICATION_DURATIONS = {
+  SUCCESS: 3000,
+  ERROR: 5000,
+  INFO: 3000,
+};

 export const Success = ({ msg }) => {
-  toast.success(msg, { duration: 3000 });
+  toast.success(msg, { duration: NOTIFICATION_DURATIONS.SUCCESS });
 };

 export const Error = ({ msg }) => {
-  toast.error(msg, { duration: 5000 });
+  toast.error(msg, { duration: NOTIFICATION_DURATIONS.ERROR });
 };

 export const Warn = ({ msg }) => {
-  toast.info(msg, { duration: 3000 });
+  toast.info(msg, { duration: NOTIFICATION_DURATIONS.INFO });
 };

Also applies to: 59-60, 64-65

src/components/Patient/DailyRounds.tsx (1)

341-343: Consider adding error recovery mechanism.

While the error handling is functional, consider adding a retry mechanism for failed investigation updates.

+const MAX_RETRIES = 3;
+const retryInvestigationUpdate = async (body, pathParams, retries = 0) => {
+  try {
+    const { error } = await request(routes.partialUpdateConsultation, {
+      body,
+      pathParams,
+    });
+    return { error };
+  } catch (err) {
+    if (retries < MAX_RETRIES) {
+      await new Promise(resolve => setTimeout(resolve, 1000 * (retries + 1)));
+      return retryInvestigationUpdate(body, pathParams, retries + 1);
+    }
+    return { error: err };
+  }
+};

 if (state.form.rounds_type === "DOCTORS_LOG" && state.form.investigations_dirty) {
-  const { error: investigationError } = await request(
-    routes.partialUpdateConsultation,
-    {
-      body: { investigation: state.form.investigations },
-      pathParams: { id: consultationId },
-    },
-  );
+  const { error: investigationError } = await retryInvestigationUpdate(
+    { investigation: state.form.investigations },
+    { id: consultationId }
+  );

   if (investigationError) {
     Notification.Error({
       msg: investigationError.message || investigationError,
     });
     return;
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ead041b and 5c0f052.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • package.json (2 hunks)
  • src/App.tsx (1 hunks)
  • src/CAREUI/icons/Index.tsx (2 hunks)
  • src/Utils/Notifications.js (2 hunks)
  • src/components/Patient/DailyRounds.tsx (1 hunks)
  • src/components/ui/sonner.tsx (1 hunks)
  • src/components/ui/toast.tsx (0 hunks)
  • src/components/ui/toaster.tsx (0 hunks)
  • src/hooks/useToast.ts (0 hunks)
  • src/style/index.css (0 hunks)
💤 Files with no reviewable changes (4)
  • src/style/index.css
  • src/components/ui/toaster.tsx
  • src/hooks/useToast.ts
  • src/components/ui/toast.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/Utils/Notifications.js

[error] 59-59: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (4)
src/components/ui/sonner.tsx (1)

4-8: LGTM: Clean type-safe implementation

The component properly inherits and forwards all props from the Sonner Toaster component while adding theme support. The type safety is well implemented.

src/App.tsx (1)

5-5: LGTM: Clean import update

The import path update correctly reflects the migration to Sonner, and the Toaster component placement remains appropriate at the application root level.

src/Utils/Notifications.js (1)

1-1: LGTM: Clean import of Sonner.

The import statement correctly imports the toast function from the Sonner library.

package.json (1)

89-89: Verify Sonner version compatibility.

The added dependencies look correct, but let's verify the version compatibility and check for any known security issues.

Also applies to: 101-101

✅ Verification successful

Sonner dependency version is up-to-date and secure

The installed version (1.7.1) matches the latest version from npm registry, and there are no known security vulnerabilities reported for the package.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for latest versions and security advisories
echo "Checking latest versions..."
curl -s https://registry.npmjs.org/sonner/latest | jq '.version'

echo "Checking for security advisories..."
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "sonner") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 558

description: "Icon copied to clipboard successfully",
variant: "success",
});
toast.success("Icon copied to clipboard successfully");
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add i18n support for the toast message

The success message is hardcoded. Since the project uses i18next (as seen in the imports), this message should be internationalized.

-    toast.success("Icon copied to clipboard successfully");
+    toast.success(t("icon.copy.success"));

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 18 to 22
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);

toast({
description: "Icon copied to clipboard successfully",
variant: "success",
});
toast.success("Icon copied to clipboard successfully");
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for clipboard operations

The clipboard operation could fail in certain scenarios (permissions, secure context, etc.). Consider adding error handling.

-  const copyToClipboard = (text: string) => {
-    navigator.clipboard.writeText(text);
-    toast.success("Icon copied to clipboard successfully");
+  const copyToClipboard = async (text: string) => {
+    try {
+      await navigator.clipboard.writeText(text);
+      toast.success(t("icon.copy.success"));
+    } catch (error) {
+      toast.error(t("icon.copy.error"));
+      console.error("Failed to copy to clipboard:", error);
+    }
   };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast({
description: "Icon copied to clipboard successfully",
variant: "success",
});
toast.success("Icon copied to clipboard successfully");
};
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
toast.success(t("icon.copy.success"));
} catch (error) {
toast.error(t("icon.copy.error"));
console.error("Failed to copy to clipboard:", error);
}
};

@nilay-v3rma nilay-v3rma marked this pull request as draft December 13, 2024 07:38
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.

Switch to using shadcn's Sonner for in-app toast notifications
1 participant