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

feat: Use sonner for toast instead of chakra #538

Merged
merged 6 commits into from
Oct 18, 2024
Merged

Conversation

ivan-dalmet
Copy link
Member

@ivan-dalmet ivan-dalmet commented Oct 11, 2024

Describe your changes

Add sonner for toasts instead of Chakra toasts.

Screenshots

image

Documentation

BearStudio/start-ui-web-docs#57

Checklist

  • I performed a self review of my code
  • I ensured that everything is written in English
  • I tested the feature or fix on my local environment
  • I ran the pnpm storybook command and everything is working
  • If applicable, I updated the translations for english and french files
    (If you cannot update the french language, just let us know in the PR description)
  • If applicable, I updated the README.md
  • If applicable, I created a PR or an issue on the documentation repository
  • If applicable, I’m sure that my feature or my component is mobile first and available correctly on desktop

Summary by CodeRabbit

  • New Features

    • Introduced a customizable toast notification system using the new toastCustom function, enhancing user feedback for various actions.
    • Added multiple stories in Storybook for the Toast component to showcase its functionality.
  • Bug Fixes

    • Streamlined toast notifications across various components, ensuring consistent user experience.
  • Chores

    • Updated project dependencies and versioning in package.json.
    • Enhanced localization for toast notifications in multiple languages, including new entries for closing messages and password visibility.

Copy link

vercel bot commented Oct 11, 2024

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

Name Status Preview Comments Updated (UTC)
start-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 14, 2024 3:44pm

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The pull request updates the package.json for the start-ui-web project to version 2.0.0, introducing a new dependency on the sonner library for toast notifications. The Providers component now incorporates a Toaster for displaying notifications. A new Storybook file for the Toast component has been created, showcasing various notification scenarios. Additionally, several components have been modified to utilize the new toastCustom function instead of the previous toast hooks, streamlining the notification process across the application.

Changes

File Path Change Summary
package.json Updated to version 2.0.0, requiring Node.js >=20, added dependency "sonner": "1.5.0".
src/app/Providers.tsx Updated to include a Toaster component in the returned JSX.
src/components/Toast/docs.stories.tsx Created new stories: Default, WithDescription, WithActions, HideIcon.
src/components/Toast/index.ts Removed file containing old toast hooks and configurations.
src/components/Toast/index.tsx Introduced toastCustom function for customizable toast notifications.
src/features/account/AccountDeleteButton.tsx Updated to use toastCustom instead of useToastError.
src/features/account/AccountEmailForm.tsx Updated to use toastCustom, removed useToastError.
src/features/account/AccountProfileForm.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/account/EmailVerificationCodeModal.tsx Updated to use toastCustom, removed useToastSuccess.
src/features/auth/LoginForm.tsx Updated to use toastCustom, removed useToastError.
src/features/auth/PageRegister.tsx Updated to use toastCustom, removed useToastError.
src/features/repositories/AdminRepositoryActions.tsx No changes made.
src/features/repositories/PageAdminRepository.tsx Updated to use toastCustom, removed useToastError.
src/features/repositories/PageAdminRepositoryCreate.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/repositories/PageAdminRepositoryUpdate.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/users/AdminUserActions.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/users/PageAdminUserCreate.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/users/PageAdminUserUpdate.tsx Updated to use toastCustom, removed useToastError and useToastSuccess.
src/features/demo-mode/DemoModalInterceptor.tsx Updated to use toast from sonner, replaced toast.closeAll with toast.dismiss, added cleanup function.
src/locales/ar/components.json Updated with new entries for toast notifications.
src/locales/en/components.json Updated with new entries for toast notifications.
src/locales/fr/components.json Updated with new entries for toast notifications.
src/locales/sw/components.json Updated with new entries for toast notifications.

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d12811d and 1578d1b.

📒 Files selected for processing (1)
  • src/features/demo-mode/DemoModalInterceptor.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/features/demo-mode/DemoModalInterceptor.tsx

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (23)
src/app/Providers.tsx (2)

32-32: Consider adjusting the Toaster component placement

The Toaster component is correctly added with appropriate props for position and offset. However, consider moving it before the {children} prop to ensure it renders consistently across all pages:

 <ChakraProvider
   colorModeManager={localStorageManager}
   theme={{
     ...theme,
     direction:
       AVAILABLE_LANGUAGES.find(({ key }) => key === i18n.language)?.dir ??
       'ltr',
   }}
 >
+  <Toaster position="top-right" offset={16} />
   {children}
-  <Toaster position="top-right" offset={16} />
 </ChakraProvider>

This adjustment ensures that the Toaster is always rendered, regardless of what the children components might be.


Incomplete Removal of Chakra Toast Implementations

The following Chakra toast usages are still present in the codebase:

  • src/features/demo-mode/DemoModalInterceptor.tsx

Please ensure that all Chakra toast-related code is removed or replaced with Sonner's Toaster to maintain consistency across the application.

🔗 Analysis chain

Line range hint 1-36: Overall implementation looks good, consider follow-up actions

The changes successfully introduce Sonner's Toaster component to replace Chakra toasts, aligning well with the PR objectives. The implementation is clean and straightforward.

To ensure a complete transition:

  1. Verify that all Chakra toast-related code has been removed from other parts of the application.
  2. Update any relevant documentation to reflect the switch to Sonner for toast notifications.
  3. Consider adding a brief comment in the Providers component explaining the purpose of the Toaster for future maintainers.

To help verify the complete removal of Chakra toast-related code, you can run the following script:

This will search for any remaining uses of Chakra's useToast hook or createStandaloneToast function in your TypeScript and TSX files, excluding the node_modules directory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining Chakra toast-related imports or usages
rg --type typescript --type tsx 'useToast|createStandaloneToast' -g '!node_modules'

Length of output: 120


Script:

#!/bin/bash
# Search for any remaining Chakra toast-related imports or usages
rg --type ts --type tsx 'useToast|createStandaloneToast' -g '!node_modules'

Length of output: 105


Script:

#!/bin/bash
# List all available file types in rg to identify correct type identifiers
rg --list-types

Length of output: 432


Script:

#!/bin/bash
# Search for any remaining Chakra toast-related imports or usages by file extension
rg 'useToast|createStandaloneToast' --glob '*.ts' --glob '*.tsx' -g '!node_modules'

Length of output: 221

src/features/account/AccountDeleteButton.tsx (1)

39-42: LGTM: Error handling updated to use new toast system

The error handling has been successfully updated to use the new toastCustom function, maintaining the existing functionality while adapting to the new toast system. The explicit status: 'error' property ensures the correct type of toast is displayed.

For consistency, consider extracting the error message to a constant or using a more specific error key. This could improve maintainability and make it easier to update error messages in the future.

You might want to consider the following minor improvement:

 toastCustom({
   status: 'error',
-  title: t('account:deleteAccount.feedbacks.updateError.title'),
+  title: t('account:deleteAccount.feedbacks.deleteError.title'),
 });
src/features/auth/LoginForm.tsx (1)

40-43: LGTM: Error handling updated to use toastCustom.

The error handling logic has been successfully updated to use the new toastCustom function, aligning with the PR objective of replacing Chakra toasts with Sonner. The implementation maintains internationalization support and provides consistent user feedback.

Consider enhancing the error message by including more specific details about the login failure, if available from the API response. This could provide users with more actionable information. For example:

onError: (error) => {
  toastCustom({
    status: 'error',
    title: t('auth:login.feedbacks.loginError.title'),
    description: error.message || t('auth:login.feedbacks.loginError.defaultMessage'),
  });
},
src/features/account/EmailVerificationCodeModal.tsx (1)

58-61: LGTM: Updated toast notification implementation.

The change from toastSuccess to toastCustom aligns with the PR objective. The addition of the status parameter is appropriate for this success scenario.

Consider extracting the toast message to a constant or using a translation key for better maintainability:

const SUCCESS_MESSAGE = t('account:email.feedbacks.updateSuccess.title');
toastCustom({
  status: 'success',
  title: SUCCESS_MESSAGE,
});

This approach would make it easier to update the message in the future and potentially reuse it elsewhere if needed.

src/features/repositories/AdminRepositoryActions.tsx (1)

Line range hint 40-46: LGTM: Error handling updated correctly

The error handling logic has been successfully updated to use toastCustom instead of the previous method. The implementation is correct and maintains the use of translation keys for internationalization.

Consider destructuring the t function at the beginning of the onError callback to slightly improve readability:

onError: () => {
  const { t } = useTranslation(['repositories']);
  toastCustom({
    status: 'error',
    title: t('feedbacks.deleteRepositoryError.title'),
    description: t('feedbacks.deleteRepositoryError.description'),
  });
},

This change is optional and doesn't affect functionality.

src/features/users/PageAdminUserCreate.tsx (3)

32-35: LGTM: Success toast updated correctly

The success toast has been correctly updated to use the new toastCustom function. The functionality remains the same, and localization is maintained.

For consistency with the error handling below, consider extracting the toast title to a variable:

const successTitle = t('users:create.feedbacks.updateSuccess.title');
toastCustom({
  status: 'success',
  title: successTitle,
});

This minor refactoring would make the code more uniform across different toast calls.


43-46: LGTM: Error toast updated correctly

The error toast has been correctly updated to use the new toastCustom function. The functionality remains the same, and localization is maintained.

For consistency and to improve readability, consider extracting the toast title to a variable:

const errorTitle = t('users:create.feedbacks.updateError.title');
toastCustom({
  status: 'error',
  title: errorTitle,
});

This minor refactoring would make the code more uniform across different toast calls and improve maintainability.


Line range hint 10-46: Overall: Toast mechanism successfully updated

The changes in this file successfully implement the new toast mechanism using toastCustom from Sonner, replacing the previous Chakra toast implementation. The functionality of the component remains intact, and localization is preserved.

To further improve the code, consider refactoring the toast calls into a separate function:

const showToast = (status: 'success' | 'error') => {
  const title = t(`users:create.feedbacks.update${status.charAt(0).toUpperCase() + status.slice(1)}.title`);
  toastCustom({ status, title });
};

// Usage in onSuccess and onError:
showToast('success');
showToast('error');

This refactoring would centralize the toast logic, making it easier to maintain and modify in the future.

src/features/account/AccountEmailForm.tsx (2)

44-47: LGTM: Error handling updated correctly with a minor suggestion.

The error handling in the updateEmail mutation has been successfully updated to use toastCustom, which aligns with the PR objective of replacing Chakra toasts with Sonner. The implementation maintains the use of translations and sets the appropriate error status.

For consistency with other parts of the codebase, consider extracting the error message to a translation key. This would make it easier to manage and update error messages across the application. Here's a suggested improvement:

 toastCustom({
   status: 'error',
-  title: t('account:email.feedbacks.updateError.title'),
+  title: t('account:email.errors.updateFailed'),
 });

Don't forget to add the corresponding translation key to your localization files.


Line range hint 1-114: Summary: Successfully implemented Sonner toast in AccountEmailForm

The changes in this file successfully implement the replacement of Chakra toasts with Sonner, as per the PR objectives. The toastCustom function is now correctly imported and used for error handling in the updateEmail mutation. The overall structure and functionality of the AccountEmailForm component remain intact, ensuring that the email update process continues to work as expected.

To further improve the implementation and maintain consistency across the application:

  1. Consider creating a centralized error handling utility that uses toastCustom. This would allow for consistent error messaging and easier management of toast notifications throughout the application.

  2. Ensure that all other components that previously used Chakra toasts have been updated to use Sonner in a similar manner. This will maintain consistency across the entire application.

  3. Update the project documentation to reflect the change from Chakra toasts to Sonner, including any new APIs or patterns that developers should follow when implementing toast notifications.

src/features/account/AccountProfileForm.tsx (3)

37-40: LGTM: Success toast updated correctly

The success toast notification has been correctly updated to use the new toastCustom function, which is consistent with the PR objective. The translation key for the success message has been retained, ensuring continuity in the user experience.

Consider adding a description property to the toast for more detailed feedback:

toastCustom({
  status: 'success',
  title: t('account:profile.feedbacks.updateSuccess.title'),
  description: t('account:profile.feedbacks.updateSuccess.description'),
});

43-46: LGTM: Error toast updated correctly

The error toast notification has been correctly updated to use the new toastCustom function, maintaining consistency with the success toast implementation. The translation key for the error message has been retained, ensuring a consistent user experience.

Consider adding a description property to the toast for more detailed error feedback:

toastCustom({
  status: 'error',
  title: t('account:profile.feedbacks.updateError.title'),
  description: t('account:profile.feedbacks.updateError.description'),
});

Line range hint 1-114: Overall assessment: Changes implemented correctly

The modifications to AccountProfileForm.tsx have been implemented correctly, aligning well with the PR objective of replacing Chakra toasts with Sonner. The new toastCustom function is consistently used for both success and error notifications, maintaining a unified approach to toast handling.

To further improve the implementation:

  1. Consider adding more detailed feedback using the description property in the toast notifications.
  2. Ensure that this pattern of using toastCustom is consistently applied across all components in the application.
  3. If not already done, consider creating a custom hook (e.g., useCustomToast) that wraps the toastCustom function and includes commonly used toast configurations. This could help maintain consistency and reduce code duplication across the application.
src/components/Toast/docs.stories.tsx (2)

20-41: LGTM: Default story effectively demonstrates basic toast functionality.

The implementation is clean and showcases the different toast statuses well.

Consider adding a brief description or comment above the story to explain its purpose, which would enhance the documentation aspect of the Storybook.


1-113: Overall, excellent implementation of Storybook stories for the Toast component.

The file successfully demonstrates various configurations of the new toast component, providing good coverage of its features. Each story focuses on a specific aspect, making it easy for developers to understand and test different use cases.

To further improve the documentation:

  1. Consider adding brief comments above each story explaining its purpose and what it demonstrates.
  2. Ensure consistency in language usage across all UI elements (e.g., changing the French button label to English).
  3. Double-check for and correct any remaining typos or grammatical errors in button labels.

These minor improvements will enhance the overall quality and usefulness of the Storybook documentation.

src/features/auth/PageRegister.tsx (1)

41-44: LGTM: Error handling updated to use new toast implementation.

The change to use toastCustom for error handling is consistent with the PR objective. The error message is still properly internationalized.

A minor suggestion for consistency:

Consider extracting the error message to a variable for better readability:

 onError: () => {
+  const errorMessage = t('auth:register.feedbacks.registrationError.title');
   toastCustom({
     status: 'error',
-    title: t('auth:register.feedbacks.registrationError.title'),
+    title: errorMessage,
   });
 },

This change would improve code readability and make it easier to reuse the error message if needed.

src/features/users/PageAdminUserUpdate.tsx (1)

56-59: LGTM: Error toast updated to use new system

The error toast implementation has been correctly updated to use the new toastCustom function. The change maintains the existing functionality by using the 'error' status and the same translation key for the title. This update is consistent with the PR's objective of transitioning to the Sonner toast system.

For consistency, consider updating the error handling for database conflicts (email already used) to also use the toastCustom function. This would ensure all toast notifications in this component use the new system. Here's a suggested implementation:

if (isErrorDatabaseConflict(error, 'email')) {
  form.setError('email', { message: t('users:data.email.alreadyUsed') });
  toastCustom({
    status: 'error',
    title: t('users:data.email.alreadyUsed'),
  });
  return;
}
src/features/repositories/PageAdminRepository.tsx (1)

Line range hint 50-57: LGTM: Toast notification updated correctly

The toastCustom function is correctly implemented in the onError callback, maintaining the same error handling logic and user feedback mechanism. The usage is consistent with typical toast notification patterns.

For consistency with other parts of the codebase, consider using template literals for the translation keys:

 toastCustom({
   status: 'error',
-  title: t('repositories:feedbacks.deleteRepositoryError.title'),
-  description: t(
-    'repositories:feedbacks.deleteRepositoryError.description'
-  ),
+  title: t(`repositories:feedbacks.deleteRepositoryError.title`),
+  description: t(
+    `repositories:feedbacks.deleteRepositoryError.description`
+  ),
 });
src/features/users/AdminUserActions.tsx (4)

20-20: LGTM! Consider grouping related imports.

The change from importing individual toast hooks to a single toastCustom function aligns well with the PR objective of replacing Chakra toasts with Sonner. This unified approach should simplify toast management across the component.

Consider grouping related imports together. You could move this import statement closer to other UI-related imports for better organization.


Line range hint 38-54: LGTM! Consider extracting common toast options.

The changes consistently apply the new toastCustom function for both success and error scenarios in the activateUser mutation. The use of the status parameter effectively differentiates between toast types while maintaining the existing message content.

To improve code maintainability, consider extracting common toast options into a separate function or object. This could help reduce duplication across different mutation callbacks. For example:

const createUserActionToast = (status: 'success' | 'error', action: string, login: string) => ({
  status,
  title: t(`users:feedbacks.${action}UserSuccess.title`),
  description: t(`users:feedbacks.${action}UserSuccess.description`, { login }),
});

// Usage
toastCustom(createUserActionToast('success', 'activate', name ?? email));

Line range hint 83-89: LGTM! Consider adding a success toast for consistency.

The change in the removeUser mutation error handling is consistent with the new toast implementation. The use of toastCustom with the 'error' status maintains the existing error notification behavior.

For consistency with other user actions, consider adding a success toast notification after successfully removing a user. This would provide feedback to the admin user that the action was completed successfully. For example:

onSuccess: async ({ email, name }) => {
  await trpcUtils.users.getAll.invalidate();
  toastCustom({
    status: 'success',
    title: t('users:feedbacks.deleteUserSuccess.title'),
    description: t('users:feedbacks.deleteUserSuccess.description', {
      login: name ?? email,
    }),
  });
},

Don't forget to add the corresponding translation keys if you implement this suggestion.


Line range hint 1-153: Overall, the changes effectively implement the new toast system.

The modifications to this component successfully replace the Chakra toast system with the new toastCustom function from Sonner. These changes are well-contained and don't affect the core functionality or user interactions of the AdminUserActions component.

To further improve the component:

  1. Consider implementing a custom hook (e.g., useUserActions) to encapsulate the mutation logic and toast notifications. This would make the component more focused on rendering and improve separation of concerns.
  2. Evaluate if any of the toast messages need adjustment to better fit Sonner's styling or capabilities.
  3. Ensure that the new toast implementation is accessible and meets any relevant UI/UX standards your project adheres to.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ff723c0 and e4fdd36.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (18)
  • package.json (1 hunks)
  • src/app/Providers.tsx (2 hunks)
  • src/components/Toast/docs.stories.tsx (1 hunks)
  • src/components/Toast/index.ts (0 hunks)
  • src/components/Toast/index.tsx (1 hunks)
  • src/features/account/AccountDeleteButton.tsx (2 hunks)
  • src/features/account/AccountEmailForm.tsx (2 hunks)
  • src/features/account/AccountProfileForm.tsx (2 hunks)
  • src/features/account/EmailVerificationCodeModal.tsx (2 hunks)
  • src/features/auth/LoginForm.tsx (2 hunks)
  • src/features/auth/PageRegister.tsx (2 hunks)
  • src/features/repositories/AdminRepositoryActions.tsx (2 hunks)
  • src/features/repositories/PageAdminRepository.tsx (2 hunks)
  • src/features/repositories/PageAdminRepositoryCreate.tsx (3 hunks)
  • src/features/repositories/PageAdminRepositoryUpdate.tsx (3 hunks)
  • src/features/users/AdminUserActions.tsx (4 hunks)
  • src/features/users/PageAdminUserCreate.tsx (3 hunks)
  • src/features/users/PageAdminUserUpdate.tsx (3 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Toast/index.ts
🧰 Additional context used
🔇 Additional comments (32)
src/app/Providers.tsx (1)

6-6: LGTM: Correct import of Sonner's Toaster component

The import statement for the Toaster component from the 'sonner' library is correctly placed and properly formatted. This aligns with the PR objective of replacing Chakra toasts with Sonner.

src/features/account/AccountDeleteButton.tsx (2)

7-7: LGTM: Import change aligns with PR objective

The change from useToastError to toastCustom is consistent with the PR's goal of replacing Chakra toasts with Sonner. This modification suggests that the toast functionality has been centralized into a custom function, which is a good practice for maintaining consistency across the application.


Line range hint 1-63: Verify toast functionality in various scenarios

The changes to this component are minimal and focused, successfully updating the toast mechanism without altering the core functionality. This approach is commendable for its maintainability and alignment with the PR objective.

To ensure the new toast system works as expected across different scenarios:

Please run the following script to check for any remaining uses of the old toast system in the codebase:

This will help ensure that all instances of the old toast system have been updated consistently across the project.

src/features/auth/LoginForm.tsx (2)

16-16: LGTM: Import statement for toastCustom added correctly.

The import statement for toastCustom from the Toast component is correctly placed and follows the project's import convention. This addition is necessary for the updated error handling logic.


Line range hint 1-93: Overall assessment: Changes successfully implement Sonner for toast notifications.

The modifications in this file effectively replace the Chakra toast with Sonner, as intended in the PR objectives. The changes are minimal and focused, which reduces the risk of introducing new bugs. The code maintains its previous functionality while updating the toast mechanism, ensuring a smooth transition to the new notification system.

To ensure that all instances of Chakra toast have been replaced in the codebase, run the following verification script:

src/features/account/EmailVerificationCodeModal.tsx (2)

16-16: LGTM: Import statement for new toast functionality.

The addition of the toastCustom import aligns with the PR objective of replacing Chakra toasts with Sonner. This change is correctly implemented and follows the existing import structure.


Line range hint 1-93: Overall assessment: Changes align with PR objectives, but verification needed.

The visible changes in this file successfully implement the switch from Chakra toasts to Sonner, which aligns with the PR objectives. The modifications are minimal and focused, maintaining the overall structure and functionality of the component.

However, there's a discrepancy between the AI-generated summary and the visible code changes regarding updates to the onClose function. This inconsistency should be addressed to ensure all intended changes are properly implemented and reviewed.

Please verify the onClose function changes and update the code or the summary accordingly.

src/features/repositories/AdminRepositoryActions.tsx (2)

19-19: LGTM: Import of toastCustom is correct

The import of toastCustom from the new Toast component is correctly implemented and aligns with the PR objective of replacing Chakra toasts with Sonner.


Line range hint 1-92: Verify consistent toast usage across the component

The changes to this component are minimal and focused, which is good for maintainability. The toast notification mechanism has been successfully updated without affecting other parts of the component.

To ensure consistency, let's verify that no other toast-related imports or usages remain in this file:

If these tests pass without any unexpected output, we can be confident that the toast migration is complete for this component.

✅ Verification successful

Toast usage successfully migrated

The component no longer contains any Chakra useToast imports or usages. All toast notifications are now handled exclusively by toastCustom.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining toast-related imports or usages

# Test 1: Check for any remaining imports related to Chakra toast
echo "Checking for Chakra toast imports:"
rg --type typescript 'import.*useToast.*from.*@chakra-ui/react' src/features/repositories/AdminRepositoryActions.tsx

# Test 2: Check for any usage of Chakra toast hooks
echo "Checking for Chakra toast hook usage:"
rg --type typescript 'useToast\(' src/features/repositories/AdminRepositoryActions.tsx

# Test 3: Double-check that toastCustom is the only toast-related import
echo "Verifying toastCustom import:"
rg --type typescript 'import.*toast.*from' src/features/repositories/AdminRepositoryActions.tsx

Length of output: 643


Script:

#!/bin/bash
# Description: Check for any remaining toast-related imports or usages

# Test 1: Check for any remaining imports related to Chakra toast
echo "Checking for Chakra toast imports:"
rg --type ts --type tsx 'import.*useToast.*from.*@chakra-ui/react' src/features/repositories/AdminRepositoryActions.tsx

# Test 2: Check for any usage of Chakra toast hooks
echo "Checking for Chakra toast hook usage:"
rg --type ts --type tsx 'useToast\(' src/features/repositories/AdminRepositoryActions.tsx

# Test 3: Double-check that toastCustom is the only toast-related import
echo "Verifying toastCustom import:"
rg --type ts --type tsx 'import.*toast.*from' src/features/repositories/AdminRepositoryActions.tsx

Length of output: 631


Script:

#!/bin/bash
# Description: Check for any remaining toast-related imports or usages using file extensions

# Test 1: Check for any remaining imports related to Chakra toast
echo "Checking for Chakra toast imports:"
rg 'import.*useToast.*from.*@chakra-ui/react' src/features/repositories/AdminRepositoryActions.tsx --glob '*.ts' --glob '*.tsx'

# Test 2: Check for any usage of Chakra toast hooks
echo "Checking for Chakra toast hook usage:"
rg 'useToast\(' src/features/repositories/AdminRepositoryActions.tsx --glob '*.ts' --glob '*.tsx'

# Test 3: Double-check that toastCustom is the only toast-related import
echo "Verifying toastCustom import:"
rg 'import.*toast.*from' src/features/repositories/AdminRepositoryActions.tsx --glob '*.ts' --glob '*.tsx'

Length of output: 621

src/features/users/PageAdminUserCreate.tsx (1)

10-10: LGTM: Import statement updated correctly

The import statement has been updated to use the new toastCustom function, which aligns with the PR objective of replacing Chakra toasts with Sonner. This change simplifies the toast handling approach in the component.

src/features/repositories/PageAdminRepositoryCreate.tsx (4)

10-10: LGTM: Import statement updated correctly

The import statement has been properly updated to use the new toastCustom function, aligning with the PR's objective of replacing Chakra toasts with Sonner.


34-37: LGTM: Success toast implementation updated correctly

The success toast implementation has been properly updated to use the new toastCustom function. The status is correctly set to 'success', and the translation key for the message remains unchanged, ensuring consistency with the previous behavior while adopting the new Sonner toast system.


47-50: LGTM: Error toast implementation updated correctly

The error toast implementation has been properly updated to use the new toastCustom function. The status is correctly set to 'error', and the translation key for the message remains unchanged. This change maintains the existing error handling logic while successfully integrating the new Sonner toast system.


Line range hint 1-93: Summary: Successful migration to Sonner toast system

The changes in this file successfully implement the migration from Chakra toasts to the Sonner toast system. The modifications are consistent, maintaining the existing functionality while adopting the new toastCustom function. The error handling logic remains intact, and the translation keys are preserved, ensuring a smooth transition to the new toast implementation.

src/features/account/AccountEmailForm.tsx (1)

17-17: LGTM: Import statement updated correctly.

The import statement for toastCustom has been added, which aligns with the PR objective of replacing Chakra toasts with Sonner. This change is correct and follows the existing import structure.

To ensure the complete removal of the old toast implementation, let's verify that useToastError is not used anywhere else in the file:

✅ Verification successful

Verified: No remaining usage of useToastError found.

The useToastError import has been fully removed from AccountEmailForm.tsx, ensuring that the error handling now consistently uses toastCustom.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of useToastError in the file

# Test: Search for useToastError in the file. Expect: No matches
rg --type typescript 'useToastError' src/features/account/AccountEmailForm.tsx

Length of output: 113


Script:

#!/bin/bash
# Description: Check for any remaining usage of useToastError in the file

# Test: Search for useToastError in the file. Expect: No matches
rg 'useToastError' src/features/account/AccountEmailForm.tsx

Length of output: 60

src/features/account/AccountProfileForm.tsx (1)

16-16: LGTM: Import statement updated correctly

The import statement has been updated to use the new toastCustom function, which aligns with the PR objective of replacing Chakra toasts with Sonner. This change promotes a more unified approach to handling toast notifications across the application.

src/components/Toast/docs.stories.tsx (1)

1-18: LGTM: Imports and Storybook configuration are well-structured.

The imports cover all necessary dependencies, and the Storybook configuration with the decorator ensures consistent presentation of the stories.

src/features/repositories/PageAdminRepositoryUpdate.tsx (4)

12-12: LGTM: Import statement for toastCustom is correct.

The import statement for toastCustom is properly added and consistent with the changes made in the component.


48-51: LGTM: Success callback updated correctly.

The toastCustom function is properly implemented in the success callback. It maintains the internationalization support and correctly sets the success status.


61-64: LGTM: Error callback updated correctly.

The toastCustom function is properly implemented in the error callback. It maintains the internationalization support, correctly sets the error status, and preserves the existing error handling logic for database conflicts.


Line range hint 1-124: Summary: Successful implementation of Sonner toasts.

The changes in this file successfully replace the Chakra toast hooks with the new toastCustom function from Sonner. The implementation is consistent throughout the file, maintaining the existing functionality while updating the toast notification system. The changes are minimal and focused, which reduces the risk of introducing new bugs.

Key points:

  1. The import statement for toastCustom is correctly added.
  2. Both success and error callbacks in the updateRepository mutation are updated to use toastCustom.
  3. Internationalization support is maintained.
  4. Existing error handling logic, particularly for database conflicts, remains intact.

These changes align well with the PR objectives and contribute to a consistent user experience across the application.

src/features/auth/PageRegister.tsx (2)

Line range hint 1-144: Summary: Changes successfully implement new toast notification system.

The modifications in this file are focused and align well with the PR objective of replacing Chakra toasts with Sonner. The changes are minimal, affecting only the import statement and the error handling in the register mutation. This approach maintains the core functionality of the registration page while successfully implementing the new toast notification system.

The limited scope of changes reduces the risk of introducing new bugs and makes the code easier to review and maintain. Good job on keeping the changes focused and consistent with the project goals.


16-16: LGTM: Import statement updated for new toast implementation.

The import of toastCustom is consistent with the PR objective of replacing Chakra toasts with Sonner.

Let's verify the removal of the old import:

✅ Verification successful

LGTM: useToastError import successfully removed.

No instances of useToastError import remain in src/features/auth/PageRegister.tsx.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the removal of useToastError import
# Test: Search for useToastError import in the file. Expect: No matches.
rg --type typescript 'import.*useToastError.*from.*@/components/Toast' src/features/auth/PageRegister.tsx

Length of output: 142


Script:

#!/bin/bash
# Description: Verify the removal of useToastError import with correct file type
# Test: Search for useToastError import in the file. Expect: No matches.
rg --type typescriptreact 'import.*useToastError.*from.*@/components/Toast' src/features/auth/PageRegister.tsx

Length of output: 152


Script:

#!/bin/bash
# Description: Verify the removal of useToastError import by targeting the .tsx file directly
# Test: Search for useToastError import in the specified file. Expect: No matches.
rg 'import.*useToastError.*from.*@/components/Toast' src/features/auth/PageRegister.tsx

Length of output: 89

src/features/users/PageAdminUserUpdate.tsx (3)

12-12: LGTM: Import statement updated to use new toast system

The import statement has been correctly updated to use the new toastCustom function, which aligns with the PR objective of replacing Chakra toasts with Sonner. This change sets the foundation for updating toast calls throughout the component.


45-48: LGTM: Success toast updated to use new system

The success toast implementation has been correctly updated to use the new toastCustom function. The change maintains the existing functionality by using the 'success' status and the same translation key for the title. This update is consistent with the PR's objective of transitioning to the Sonner toast system.


Line range hint 1-138: Summary: Successful implementation of new toast system

The changes in this file successfully implement the new toastCustom function from Sonner, replacing the previous Chakra toast system. The modifications are consistent across both success and error cases, maintaining the existing functionality while adapting to the new toast system. The changes align well with the PR objective and should improve the consistency of toast notifications throughout the application.

A minor suggestion was made to update the error handling for database conflicts to also use the new toastCustom function, which would further enhance consistency.

Overall, these changes effectively contribute to the goal of using Sonner for toast notifications instead of Chakra, as outlined in the PR objectives.

src/features/repositories/PageAdminRepository.tsx (2)

23-23: LGTM: Import statement updated correctly

The import statement has been updated to use toastCustom from the new Toast component, which aligns with the PR objective of replacing Chakra toasts with Sonner.


Line range hint 1-157: Overall impact: Successful implementation of new toast system

The changes in this file successfully implement the new Sonner toast notification system, replacing the previous Chakra toast. The modifications are well-contained and do not alter the core functionality of the PageAdminRepository component. The error handling logic and user feedback mechanism remain intact, ensuring a consistent user experience. These changes align well with the PR objectives and should integrate smoothly with the rest of the application.

src/features/users/AdminUserActions.tsx (1)

Line range hint 59-75: LGTM! Consider applying the previous suggestion here as well.

The changes in the deactivateUser mutation consistently apply the new toastCustom function, mirroring the pattern used in the activateUser mutation. This maintains a uniform approach to toast notifications throughout the component.

As suggested in the previous comment, consider applying the same refactoring to extract common toast options here. This would further enhance code consistency and maintainability across different user actions.

package.json (2)

Line range hint 7-7: Verify Node.js version requirement

The update to require Node.js version >=20 is a significant change that could affect development and deployment environments.

Please ensure that:

  1. All team members are aware of this change and have updated their local environments.
  2. CI/CD pipelines have been updated to use Node.js 20 or later.
  3. Deployment environments (staging, production) support Node.js 20+.
  4. Any performance improvements or new features utilized from Node.js 20 are documented.

Run the following script to check if there are any other files specifying Node.js version that might need updating:

#!/bin/bash
# Search for Node.js version specifications in other files
rg --type-not json "node" . | rg -i "version|engine"

Line range hint 4-4: Verify major version bump and document breaking changes

The update to version 2.0.0 indicates a major change with potential breaking modifications. This aligns with the significant change of replacing Chakra toasts with Sonner. However, it's crucial to ensure that all breaking changes are properly documented.

Please confirm that:

  1. All breaking changes are documented in the changelog or release notes.
  2. The major version bump is justified by the scope of changes in this PR.

Additionally, run the following script to check for any mentions of the previous version in the codebase that might need updating:

✅ Verification successful

Version Bump Verified

The update to version 2.0.0 has no hardcoded references to the previous version 1.x.x in the codebase. This confirms that the major version bump is appropriate and correctly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any hardcoded references to the previous version
rg --type-not json "1\\.\\d+\\.\\d+" .

Length of output: 54794

src/components/Toast/index.tsx (1)

1-101: Overall implementation of the custom toast is well-structured

The toastCustom function is efficiently designed, making good use of Chakra UI components and the Sonner library to create customizable toast notifications. The code is clean, readable, and follows best practices for React and TypeScript.

src/components/Toast/docs.stories.tsx Outdated Show resolved Hide resolved
src/components/Toast/docs.stories.tsx Outdated Show resolved Hide resolved
src/components/Toast/docs.stories.tsx Outdated Show resolved Hide resolved
package.json Show resolved Hide resolved
src/components/Toast/index.tsx 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: 1

🧹 Outside diff range and nitpick comments (8)
src/locales/ar/components.json (1)

97-99: LGTM: Toast close action translation added.

The new "toast" section with the "closeToast" translation is appropriate and aligns with the PR objective of implementing Sonner for toast notifications. The translation "إغلاق الرسالة" (Close the message) is suitable for the context.

Consider adding more toast-related translations if Sonner supports other actions or states, such as "success", "error", or "loading". This would ensure comprehensive localization support for the new toast implementation.

src/locales/en/components.json (1)

96-99: LGTM! Consider adding more toast-related translations.

The addition of the "toast" section with the "closeToast" entry is appropriate and aligns with the PR objective of implementing Sonner for toast notifications. The placement and structure are consistent with the rest of the file.

Consider adding more toast-related translations if Sonner supports other customizable text elements, such as:

"toast": {
  "closeToast": "Close message",
  "success": "Success",
  "error": "Error",
  "info": "Information",
  "warning": "Warning"
}

This would provide a more comprehensive set of localized strings for the new toast implementation.

src/locales/sw/components.json (3)

94-95: LGTM! Consider adding a comment for context.

The new translations for showing and hiding passwords are appropriate and consistent with the existing structure. Great job on improving the user experience for Swahili-speaking users.

Consider adding a comment above this section to provide context for future maintainers:

+  // Translations for password field visibility toggle
   "fieldPassword": {
     "showPassword": "Onyesha nenosiri",
     "hidePassword": "Ficha nenosiri"
   },

97-99: LGTM! Consider adding more toast-related translations.

The addition of the "toast" section with the "closeToast" translation is appropriate and aligns with the PR objective of implementing Sonner for toast notifications.

For consistency and future-proofing, consider adding translations for common toast actions or types, such as "success", "error", or "info". This would ensure a complete set of translations for the new toast functionality. For example:

  "toast": {
    "closeToast": "Funga ujumbe",
    "success": "Imefanikiwa",
    "error": "Hitilafu",
    "info": "Taarifa"
  }

Please verify these translations with a native Swahili speaker before implementing.


94-99: Overall, great additions to the Swahili localization!

The new translations for password visibility toggle and toast notifications are well-implemented and consistent with the existing structure. These additions will improve the user experience for Swahili-speaking users, aligning well with the PR objectives.

To ensure comprehensive localization coverage:

  1. Consider adding more toast-related translations as suggested earlier.
  2. Verify that all new UI elements introduced with Sonner are properly localized.
  3. Maintain consistency across all language files by adding these new translations to other supported languages as well.
src/locales/fr/components.json (1)

97-99: LGTM! Consider adding more toast-related translations.

The addition of the "closeToast" translation is correct and aligns with the PR objective of implementing Sonner for toast notifications. The French translation "Fermer le message" is appropriate for this context.

Consider adding translations for other common toast-related actions or messages, such as:

  • Success message
  • Error message
  • Warning message
  • Info message

This would provide a more comprehensive localization for the new toast implementation.

src/features/demo-mode/DemoModalInterceptor.tsx (1)

26-31: Approve changes with a minor suggestion

The modifications to the useEffect hook are well-implemented:

  1. Using a timer variable to store the setTimeout reference is a good practice.
  2. The cleanup function prevents potential memory leaks.
  3. The empty dependency array ensures the effect runs only once when the component mounts.

However, I have a minor suggestion to improve code readability.

Consider extracting the timeout duration into a named constant for better readability and maintainability:

+ const TOAST_DISMISS_DELAY = 0; // or whatever milliseconds you intend

  useEffect(() => {
-   const timer = setTimeout(() => {
+   const timer = setTimeout(() => {
      toast.dismiss();
-   });
+   }, TOAST_DISMISS_DELAY);

    return () => clearTimeout(timer);
  }, []);

This change makes the intention of the timeout clearer and allows for easy adjustment if needed.

src/components/Toast/docs.stories.tsx (1)

67-90: LGTM: WithActions story effectively demonstrates toasts with interactive elements.

The WithActions story showcases toasts with action buttons well. The implementation correctly demonstrates how to add interactive elements to toast notifications.

The action button label is now in English, addressing the previous suggestion and ensuring consistency in the UI language.

However, there's a minor typo in one of the button labels:

-        Info toast with with actions
+        Info toast with actions

This small correction will improve the consistency of the button labels.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e4fdd36 and d12811d.

📒 Files selected for processing (7)
  • src/components/Toast/docs.stories.tsx (1 hunks)
  • src/components/Toast/index.tsx (1 hunks)
  • src/features/demo-mode/DemoModalInterceptor.tsx (1 hunks)
  • src/locales/ar/components.json (1 hunks)
  • src/locales/en/components.json (1 hunks)
  • src/locales/fr/components.json (1 hunks)
  • src/locales/sw/components.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Toast/index.tsx
🧰 Additional context used
🔇 Additional comments (7)
src/locales/ar/components.json (2)

94-96: LGTM: Password visibility toggle translations added.

The new translations for showing and hiding passwords are appropriate and consistent with the file structure. These additions will improve the user experience for Arabic-speaking users when interacting with password fields.


Line range hint 1-99: Summary: Arabic translations updated for new features.

The changes to this file are minimal and focused, adding necessary translations for password visibility toggle and toast notifications. These additions improve the Arabic localization and are consistent with the PR objectives of implementing Sonner for toasts.

To ensure consistency across all language files, let's verify if similar changes have been made to other language files:

This will help identify any missing translations in other language files that should be addressed for consistency.

✅ Verification successful

Verified: Translation keys are consistently updated across all language files.

All necessary translation keys ("showPassword", "hidePassword", "closeToast") have been added to the Swahili, French, Arabic, and English language files, ensuring consistency and comprehensive localization across the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar translation keys in other language files

# Test: Search for "showPassword", "hidePassword", and "closeToast" in all JSON files under src/locales
echo "Checking for new translation keys in other language files:"
rg --type json '"(showPassword|hidePassword|closeToast)"' src/locales

Length of output: 1032

src/features/demo-mode/DemoModalInterceptor.tsx (1)

Line range hint 1-105: Overall component structure and functionality approved

The changes made to this component are focused on updating the toast notification system from Chakra UI to Sonner, which aligns with the PR objectives. The overall structure and functionality of the DemoModalInterceptor component remain intact and appropriate for its purpose.

The modal content, including the demo mode explanation, code snippet, and contact information, is unchanged and continues to serve its intended purpose.

src/components/Toast/docs.stories.tsx (4)

1-18: LGTM: Imports and Storybook configuration are well-structured.

The imports and Storybook configuration are appropriate for the Toast component stories. The decorator wrapping each story in a Box component with a specified height is a good practice for consistent story presentation.


20-41: LGTM: Default story effectively demonstrates basic toast notifications.

The Default story showcases the basic functionality of the toast component with success, error, and info statuses. The implementation is correct and provides a clear example of how to use the toastCustom function.


43-65: LGTM: WithDescription story effectively demonstrates toasts with additional content.

The WithDescription story showcases toasts with descriptions well. The implementation correctly demonstrates how to add detailed descriptions to toast notifications.

The previously reported typo in the button labels has been fixed, improving the clarity of the user interface.


92-113: LGTM: HideIcon story effectively demonstrates toasts without icons.

The HideIcon story showcases the ability to hide icons in toasts correctly. The implementation demonstrates how to use the hideIcon property in the toastCustom function.

The previously reported grammatical errors in the button labels have been fixed, improving the clarity of the user interface.

Copy link

sonarcloud bot commented Oct 14, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
8.0% Duplication on New Code (required ≤ 3%)

See analysis details on SonarCloud

@ivan-dalmet ivan-dalmet merged commit 6b6f3b2 into master Oct 18, 2024
7 of 8 checks passed
@ivan-dalmet ivan-dalmet deleted the feat/sonner branch October 18, 2024 07:44
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