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

Switch to Sonner for toast notifications #9405

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.
    • Updated notification verification in Cypress tests to align with the new notification system.
    • Simplified reset logic in the AssetCreate component.
    • Adjusted online status logic in the UserStatusIndicator component to always reflect the authenticated user's status.

@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

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

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; downgraded @radix-ui/react-dialog; Added: next-themes, sonner.
src/App.tsx Updated import path for Toaster from @/components/ui/toaster to @/components/ui/sonner; updated props for Toaster.
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 previous Toaster component.
src/hooks/useToast.ts Deleted custom hook for managing toast notifications.
src/style/index.css Removed PNotify-related CSS imports.
cypress/pageobject/Facility/FacilityManage.ts Updated selector for success message verification to use Sonner's format.
cypress/support/commands.ts Added verifyNotification command; updated closeNotification to use Sonner's selector.

Assessment against linked issues

Objective Addressed Explanation
Switch to using shadcn's Sonner for in-app toast notifications (#9394)
Remove existing shadcn's Toaster to avoid conflicts with Sonner (#9394)
Update functions in Notifications.js to trigger the toast of Sonner instead of PNotify (#9394)
Uninstall PNotify and related packages (#9394)
Add development docs on: https://github.com/ohcnetwork/docs/tree/master/docs/care/development (#9394) Development docs were not included in this PR.

Possibly related PRs

Suggested reviewers

  • rithviknishad
  • Jacobjeevan
  • nihal467

🐇 In the meadow, where toasts once bloomed,
PNotify's gone, and Sonner's resumed.
With colors bright and messages clear,
Our notifications now bring cheer!
So hop along, let the new toasts play,
In a world of joy, we’ll toast all day! 🎉


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

netlify bot commented Dec 13, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit de2ff2e
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676fcefb25a11900083895f3
😎 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
@nilay-v3rma nilay-v3rma marked this pull request as ready for review December 18, 2024 11:04
@rithviknishad rithviknishad self-requested a review December 18, 2024 14:01
@rithviknishad rithviknishad changed the title [DRAFT] Switch to Sonner for toast notifications #9394 Switch to Sonner for toast notifications Dec 18, 2024
src/App.tsx Outdated Show resolved Hide resolved
@rithviknishad
Copy link
Member

You'll also have to modify the cypress tests btw.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 19, 2024
Copy link

👋 Hi, @nilay-v3rma,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

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

🔭 Outside diff range comments (2)
cypress/support/commands.ts (2)

Line range hint 213-219: Update or remove legacy closeNotification command

The closeNotification command still uses the .pnotify selector, which should be updated to use Sonner's implementation.

Consider replacing it with:

-Cypress.Commands.add("closeNotification", () => {
-  cy.get(".pnotify")
-    .should("exist")
-    .each(($div) => {
-      cy.wrap($div).click();
-    });
-});
+Cypress.Commands.add("closeNotification", () => {
+  cy.get("li[data-sonner-toast]")
+    .should("exist")
+    .each(($toast) => {
+      cy.wrap($toast).find('[data-close-button]').click();
+    });
+});

Migration to Sonner is incomplete - PNotify reference found in Cypress commands

The migration from PNotify to Sonner is mostly complete with Sonner properly configured in App.tsx, but there's still a remaining PNotify reference in the Cypress test commands:

  • cypress/support/commands.ts: The closeNotification command still uses the .pnotify selector

This Cypress command should be updated to use Sonner's toast elements instead of PNotify's for consistency with the new implementation.

🔗 Analysis chain

Line range hint 1-1: Verify complete removal of PNotify

Let's ensure the migration to Sonner is complete across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Comprehensive check for complete migration to Sonner

# Check for any remaining PNotify dependencies
echo "Checking package.json for PNotify..."
jq '.dependencies + .devDependencies' package.json | grep -i pnotify

# Check for PNotify imports
echo "Checking for PNotify imports..."
rg "import.*pnotify" --type ts --type tsx --type js --type jsx

# Check for PNotify CSS classes
echo "Checking for PNotify CSS classes..."
rg "\.pnotify" --type css --type scss --type less

# Verify Sonner is properly installed
echo "Verifying Sonner installation..."
jq '.dependencies["sonner"]' package.json

# Check for Toaster component implementation
echo "Checking for Toaster component..."
rg "<Toaster" --type tsx --type jsx

Length of output: 752


Script:

#!/bin/bash
# Let's modify our search approach to handle file extensions correctly

# Check for any PNotify-related code
echo "Checking for any PNotify references..."
rg -t js -t ts "PNotify|pnotify" 

# Check for Toaster component usage
echo "Checking for Toaster component usage..."
rg -t js -t ts "<Toaster"

# List all files that might contain toast-related code
echo "Listing potential toast-related files..."
fd -e ts -e js -e tsx -e jsx | grep -i "toast"

Length of output: 458


Script:

#!/bin/bash
# Let's check the specific PNotify reference in commands.ts and look for toast-related code

# Check the context of PNotify usage in commands.ts
echo "Checking context of PNotify in commands.ts..."
rg -B 5 -A 5 "\.pnotify" cypress/support/commands.ts

# Look for toast/notification related functions
echo "Checking toast-related functions..."
rg -t js -t ts "toast\(" -B 2 -A 2

# Check App.tsx Toaster implementation
echo "Checking Toaster implementation in App.tsx..."
rg -B 5 -A 5 "<Toaster" src/App.tsx

Length of output: 1077

🧹 Nitpick comments (1)
cypress/support/commands.ts (1)

116-122: Consider enhancing the verifyNotification command with timeout and error handling

The implementation correctly uses Sonner's selectors and follows Cypress best practices. However, we can make it more robust.

Consider these enhancements:

 //check sonner toast notification
-Cypress.Commands.add("verifyNotification", (text) => {
+Cypress.Commands.add("verifyNotification", (text, timeout = 10000) => {
   return cy
     .get("li[data-sonner-toast] div[data-title]", { timeout })
     .should("exist")
     .and("be.visible")
-    .contains(text);
+    .contains(text)
+    .should((toast) => {
+      // Additional validation that toast is actually visible in viewport
+      const rect = toast[0].getBoundingClientRect();
+      expect(rect.top).to.be.greaterThan(-rect.height);
+      expect(rect.top).to.be.lessThan(Cypress.config('viewportHeight'));
+    });
 });

This enhancement:

  1. Adds configurable timeout
  2. Ensures toast is actually visible in viewport
  3. Maintains chainability
📜 Review details

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

📥 Commits

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

📒 Files selected for processing (4)
  • cypress/pageobject/Facility/FacilityManage.ts (1 hunks)
  • cypress/support/commands.ts (1 hunks)
  • src/App.tsx (2 hunks)
  • src/CAREUI/icons/Index.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/CAREUI/icons/Index.tsx
  • src/App.tsx

cypress/pageobject/Facility/FacilityManage.ts Show resolved Hide resolved
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: 1

🧹 Nitpick comments (1)
cypress/support/commands.ts (1)

116-122: Enhance the verifyNotification command with better typing and documentation.

The implementation correctly uses data attributes for testing and has proper visibility checks. Consider these improvements:

-//check sonner toast notification
+/**
+ * Verifies that a Sonner toast notification with specific text is visible
+ * @param text - The expected text content of the notification
+ * @param timeout - Optional timeout in ms (default: Cypress default timeout)
+ */
-Cypress.Commands.add("verifyNotification", (text) => {
+Cypress.Commands.add("verifyNotification", (text: string, timeout?: number) => {
   return cy
     .get("li[data-sonner-toast] div[data-title]")
+    .timeout(timeout || Cypress.config('defaultCommandTimeout'))
     .should("exist")
     .and("be.visible")
     .contains(text);
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a828352 and 9434c27.

📒 Files selected for processing (1)
  • cypress/support/commands.ts (2 hunks)
🔇 Additional comments (1)
cypress/support/commands.ts (1)

116-122: Verify consistent notification selectors across all test files.

Let's ensure all test files have been updated to use the new Sonner selectors.

Also applies to: 223-223

✅ Verification successful

Migration to Sonner toast notifications is consistent across the codebase

The verification shows that:

  • All toast notifications use the new Sonner selector li[data-sonner-toast] div[data-title]
  • No legacy PNotify selectors were found
  • The implementation is consistent between commands.ts and FacilityManage.ts
  • All notification-related tests are using the new verifyNotification command or the equivalent Sonner selectors
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining PNotify selectors and verify consistent Sonner selector usage

echo "Checking for old PNotify selectors..."
rg -l "pnotify|PNotify" "cypress/"

echo "Verifying consistent Sonner selector usage..."
rg -l "data-sonner-toast" "cypress/"

echo "Checking for direct notification assertions that might need updating..."
rg "\.should\(.*contain.*notification" "cypress/"

Length of output: 532


Script:

#!/bin/bash
# Let's examine the notification-related assertions in the test files more thoroughly

echo "Checking all notification-related selectors and assertions..."
rg -A 2 "notification|toast" "cypress/" --type ts

echo "Examining FacilityManage.ts specifically..."
cat "cypress/pageobject/Facility/FacilityManage.ts"

echo "Looking for any cy.get patterns that might be notification-related..."
rg "cy\.get\(.*toast" "cypress/" --type ts

Length of output: 10140

cypress/support/commands.ts Outdated Show resolved Hide resolved
@rithviknishad
Copy link
Member

LGTM, do resolve the conflicts.

@rithviknishad rithviknishad added needs testing and removed changes required merge conflict pull requests with merge conflict labels Dec 19, 2024
package-lock.json Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (2)
src/Utils/Notifications.js (2)

Line range hint 21-43: Add JSDoc documentation for consistency.

Consider adding JSDoc documentation to the notifyError function for consistency with other utility functions like formatKey.

+/**
+ * Formats and displays an error notification
+ * @param {string|object} error - The error to display
+ */
const notifyError = (error) => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: 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)


50-63: Refactor notification functions for consistency and maintainability.

The Success, Error, and Warn functions share similar patterns but have different durations. Consider centralizing the duration configuration and making the implementation more consistent.

+const NOTIFICATION_DURATION = {
+  success: 3000,
+  error: 5000,
+  info: 3000,
+};
+
 /** Success message handler */
 export const Success = ({ msg }) => {
-  toast.success(msg, { duration: 3000 });
+  toast.success(msg, { duration: NOTIFICATION_DURATION.success });
 };
 
 /** Error message handler */
-export const Error = ({ msg }) => {
-  toast.error(msg, { duration: 5000 });
+export const ShowError = ({ msg }) => {
+  toast.error(msg, { duration: NOTIFICATION_DURATION.error });
 };
 
 /** Warning message handler */
 export const Warn = ({ msg }) => {
-  toast.info(msg, { duration: 3000 });
+  toast.info(msg, { duration: NOTIFICATION_DURATION.info });
 };
🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: 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)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc2efc2 and 7007e04.

📒 Files selected for processing (2)
  • cypress/support/commands.ts (2 hunks)
  • src/Utils/Notifications.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/support/commands.ts
🧰 Additional context used
🪛 Biome (1.9.4)
src/Utils/Notifications.js

[error] 56-56: 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 (1)
src/Utils/Notifications.js (1)

46-48: LGTM! Verify toast cleanup.

The closeAllNotifications implementation looks good. However, ensure that Sonner's dismiss() properly cleans up all toast notifications, especially during route changes or component unmounts.

✅ Verification successful

Toast cleanup implementation is properly used across error pages

Based on the search results, closeAllNotifications is consistently used in error-related components (404, InvalidReset, SessionExpired) to ensure a clean notification state when these error pages are rendered. The implementation using Sonner's toast.dismiss() is the only toast cleanup method used in the codebase, which prevents any potential conflicts with other cleanup approaches.

  • Used in error pages:
    • src/components/ErrorPages/404.tsx
    • src/components/ErrorPages/InvalidReset.tsx
    • src/components/ErrorPages/SessionExpired.tsx
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for places where closeAllNotifications is called
rg "closeAllNotifications"

# Search for other toast cleanup methods that might conflict
rg -g '*.{tsx,jsx,js}' "toast\.(dismiss|clear|remove)"

Length of output: 449

Comment on lines 56 to 58
export const Error = ({ msg }) => {
notify(msg, "error");
toast.error(msg, { duration: 5000 });
};
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

Rename Error function to avoid shadowing global Error.

The function name 'Error' shadows the built-in Error object. Consider renaming it to be more specific.

-export const Error = ({ msg }) => {
+export const ShowError = ({ msg }) => {
   toast.error(msg, { duration: 5000 });
 };
📝 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
export const Error = ({ msg }) => {
notify(msg, "error");
toast.error(msg, { duration: 5000 });
};
export const ShowError = ({ msg }) => {
toast.error(msg, { duration: 5000 });
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 56-56: 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)

@@ -36,3 +1,4 @@
import { toast } from "sonner";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential z-index conflict with Sonner toast notifications

Based on the analysis of z-index values in the codebase and Sonner's configuration:

  • Found z-index values up to 100000 in src/style/index.css
  • Sonner's Toaster component is configured in App.tsx but lacks explicit z-index configuration
  • By default, Sonner uses a z-index of 9999, which is lower than some existing z-index values (100000) in the codebase

To resolve potential overlay issues:

  • Add a zIndex prop to the Toaster component with a value higher than 100000
<Toaster
  position="top-right"
  theme="light"
  richColors
  zIndex={100001}
/>
🔗 Analysis chain

LGTM! Verify z-index configuration with Sonner.

The import change looks good. However, based on the PR comments about toast notifications being overlaid by other elements, ensure Sonner's z-index configuration is properly set.


Let me check the Sonner toast configuration in the codebase to ensure proper z-index setup.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any custom z-index configurations that might conflict with Sonner
rg -g '*.{css,scss,tsx,jsx}' 'z-index:'

Length of output: 755


Script:

#!/bin/bash
# Search for Sonner Toaster component configuration
rg -g '*.{tsx,jsx,js}' -A 5 '<Toaster'

Length of output: 382

@rithviknishad rithviknishad added needs testing needs review and removed Cypress Test Pending The Cypress test are to be verified labels Dec 26, 2024
.each(($div) => {
cy.wrap($div).click();
});
cy.wait(5000); //wait for the notification to disappear
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
cy.wait(5000); //wait for the notification to disappear
cy.wait(5000); //wait for the notification to disappear

don't use hardcorded wait, look into another solution

Copy link
Author

Choose a reason for hiding this comment

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

don't use hardcorded wait, look into another solution

I understand this is not the best solution, but I have tried the following methods to drag the notification upwards to close it, unfortunately they did not work

  1. using mousemove
Cypress.Commands.add("closeNotification", () => {
  cy.get("li[data-sonner-toast] div[data-title]")
    .should("exist")
    .trigger('mousedown', { which: 1, force: true }) //start the drag
    .trigger('mousemove', { clientY: -100, force: true }) // drag upward
    .trigger('mouseup', { force: true }); // end the drag
    });

  // ensure the toast is removed from the DOM
  cy.get("li[data-sonner-toast]").should("not.exist");
});
  1. using pointermove

    Cypress.Commands.add("closeNotification", () => {
      cy.get("li[data-sonner-toast]")
        .trigger('pointerdown', { which: 1, force: true }) // start the drag
        .trigger('pointermove', { clientX: 0, clientY: -100, force: true }) // drag upward
        .trigger('pointerup', { force: true }); // end the drag
    
      // ensure the toast is removed from the DOM
      cy.get("li[data-sonner-toast]").should('not.exist');
    });
  2. using toast.dismiss()

    Cypress.Commands.add("closeNotification", () => {
      cy.window().then((win) => {
        if (win.toast) {
          win.toast.dismiss(); // dismiss all toasts programmatically
        } else {
          throw new Error("Sonner `toast` object not found.");
        }
      });
    
      // ensure the toast is removed from the DOM
      cy.get("li[data-sonner-toast]").should("not.exist");
    });

I am continuing to explore better solutions and would greatly appreciate any advice or suggestions you might have!

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Dec 28, 2024
@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Dec 28, 2024
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Dec 28, 2024
@rithviknishad rithviknishad force-pushed the issues/9394/use-sonner-notifications branch from e49cab2 to 7007e04 Compare December 28, 2024 06:44
@nihal467
Copy link
Member

@nilay-v3rma can you clear the merge conflict

@nihal467 nihal467 removed the Deploy-Failed Deplyment is not showing preview label Dec 28, 2024
pranavchaitu and others added 9 commits December 28, 2024 14:56
Bumps [@yudiel/react-qr-scanner](https://github.com/yudielcurbelo/react-qr-scanner) from 2.0.8 to 2.1.0.
- [Release notes](https://github.com/yudielcurbelo/react-qr-scanner/releases)
- [Commits](yudielcurbelo/react-qr-scanner@v2.0.8...v2.1.0)

---
updated-dependencies:
- dependency-name: "@yudiel/react-qr-scanner"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [@sentry/browser](https://github.com/getsentry/sentry-javascript) from 8.45.1 to 8.47.0.
- [Release notes](https://github.com/getsentry/sentry-javascript/releases)
- [Changelog](https://github.com/getsentry/sentry-javascript/blob/8.47.0/CHANGELOG.md)
- [Commits](getsentry/sentry-javascript@8.45.1...8.47.0)

---
updated-dependencies:
- dependency-name: "@sentry/browser"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [@radix-ui/react-popover](https://github.com/radix-ui/primitives) from 1.1.2 to 1.1.4.
- [Changelog](https://github.com/radix-ui/primitives/blob/main/release-process.md)
- [Commits](https://github.com/radix-ui/primitives/commits)

---
updated-dependencies:
- dependency-name: "@radix-ui/react-popover"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [react-i18next](https://github.com/i18next/react-i18next) from 15.1.3 to 15.2.0.
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](i18next/react-i18next@v15.1.3...v15.2.0)

---
updated-dependencies:
- dependency-name: react-i18next
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
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: 0

🧹 Nitpick comments (5)
src/components/Notifications/NoticeBoard.tsx (1)

48-48: Consider centering the content both horizontally and vertically
Currently, you're only using justify-center to center the items horizontally. If your intention is to center them both horizontally and vertically (especially with a flex container), you may also include items-center to ensure vertical alignment is consistent with horizontal alignment.

-<div className="m-auto flex max-w-xs justify-center">
+<div className="m-auto flex max-w-xs items-center justify-center">
src/components/Users/UserListAndCard.tsx (3)

147-147: Consider externalizing color classes for easier theming.

Right now, green-themed classes (bg-green-100) are embedded inline. If multiple components reuse identical color schemes, you can centralize these Tailwind classes under a theme-based utility or variable for maintainability.


154-160: Retain consistent color values for offline vs online states.

Between lines 154 and 160, there’s a slight mismatch in color intensity for offline elements (bg-gray-400 vs text-gray-500). For clarity and visual uniformity, consider aligning these intensity values (e.g., using the same “400” or “500” variants).


163-163: Confirm the intended behavior for authenticated users always being “online”.

Although showing the authenticated user as online makes sense from a local perspective, verify that the rest of the system tracks online status in a complementary manner. If the user is considered online even if idle for extended periods, you may want to reconcile this with server-side checks or session-based status.

src/components/Medicine/MedibaseAutocompleteFormField.tsx (1)

Line range hint 14-83: Consider performance optimizations.

The component is well-structured, but could benefit from these optimizations:

  1. Memoize the child components to prevent unnecessary re-renders
  2. Memoize the switch callback using useCallback

Consider applying these changes:

+ import { useState, useCallback, memo } from "react";
- import { useState } from "react";

- const OptionDescription = ({ medicine }: { medicine: MedibaseMedicine }) => {
+ const OptionDescription = memo(({ medicine }: { medicine: MedibaseMedicine }) => {
    return (
      // ... component implementation
    );
- };
+ });

- const OptionChip = (props: { name?: string; value: string }) => {
+ const OptionChip = memo((props: { name?: string; value: string }) => {
    return (
      // ... component implementation
    );
- };
+ });

  // Inside MedibaseAutocompleteFormField component
- const handleTypeChange = (type) => {
+ const handleTypeChange = useCallback((type) => {
    setType(type === "all" ? undefined : type);
- };
+ }, []);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ba432f and 0177534.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts (0 hunks)
  • package.json (2 hunks)
  • src/components/Medicine/MedibaseAutocompleteFormField.tsx (1 hunks)
  • src/components/Notifications/NoticeBoard.tsx (1 hunks)
  • src/components/Users/UserListAndCard.tsx (1 hunks)
💤 Files with no reviewable changes (2)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (2)
src/components/Users/UserListAndCard.tsx (1)

137-139: Validate authUser existence and handle potential null cases.

If useAuthUser() can return undefined (for instance, before authentication or if an unexpected error occurs), referencing authUser.id might lead to runtime errors. To ensure safety, consider adding a conditional check or a fallback value.

If you'd like, I can provide an extended check to ensure authUser is properly defined everywhere.

src/components/Medicine/MedibaseAutocompleteFormField.tsx (1)

Line range hint 58-62: LGTM! Simplified options handling improves UX.

The change to always include field.value in options when it exists is a good improvement. It ensures the selected value remains visible in the dropdown regardless of the search query state, providing better user experience.

Let's verify that mergeQueryOptions properly handles potential duplicates when the selected value also appears in the API results:

✅ Verification successful

LGTM! The mergeQueryOptions utility correctly handles duplicates

The implementation in src/Utils/utils.ts confirms that mergeQueryOptions properly handles duplicate entries by:

  1. Preserving all selected items at the start of the array
  2. Filtering out any query results that match the selected items using the provided comparison function
  3. Using the id field as the comparison key for medicines, which ensures proper deduplication

The change to always include field.value in the options is safe and improves the UX without risking duplicate entries.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for mergeQueryOptions implementation to verify duplicate handling
ast-grep --pattern 'export function mergeQueryOptions($_) {
  $$$
}'

Length of output: 70


Script:

#!/bin/bash
# Let's try a different approach to find mergeQueryOptions
# First, let's search for the file containing mergeQueryOptions
rg -l "mergeQueryOptions"

# Then, let's see the implementation with context
rg "mergeQueryOptions" -A 10

Length of output: 10884

@rithviknishad
Copy link
Member

Closing as completed in #9262

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Switch to using shadcn's Sonner for in-app toast notifications
7 participants