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

Notification toast #581

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

kleyberthsantos
Copy link
Contributor

@kleyberthsantos kleyberthsantos commented Nov 20, 2024

Issue #496

Implementation Summary

Objective: Implement a unified notification system using Chakra UI's toast functionality to ensure a consistent user experience and improve code maintainability.

Key Changes:

  • NotificationProvider: Created to centralize and manage notifications (success, error, warning, info) using Chakra UI's useToast.

  • Updated Components:

    • SetupComplete.tsx: Added notifications for setup completion.
    • SendOnchainSuccess.tsx: Added notifications for successful on-chain transactions.

Features:

  • Notifications appear in the top-right corner.
  • Utilizes existing translations for consistent messaging.
  • Consistent notification system across the application.

Provider Implementation:

  • Before: Used SharedChakraProvider.
  • Now: Uses ChakraProvider with NotificationProvider for full toast functionality.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a notification system across various components to enhance user feedback during operations.
    • Added real-time notifications for processes like federation connection, DKG, and guardian verification.
  • Bug Fixes

    • Improved error handling and messaging for better user experience.
  • Documentation

    • Established a structured NotificationProvider to manage notifications throughout the application.

These updates aim to enhance user interaction and provide clearer feedback during key processes.

@kleyberthsantos kleyberthsantos requested review from a team as code owners November 20, 2024 01:27
Copy link

vercel bot commented Nov 20, 2024

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

Name Status Preview Comments Updated (UTC)
ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 20, 2024 1:29am

@kleyberthsantos kleyberthsantos changed the title Notification toast two Notification toast Nov 20, 2024
Copy link
Contributor

coderabbitai bot commented Nov 20, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a structured notification system across multiple components in the application. It adds a NotificationProvider to manage notifications using Chakra UI's toast functionality, allowing components to display success, error, and informational messages. Key components such as ConnectFederation, RunDKG, ConnectGuardians, VerifyGuardians, and FederationSetup have been updated to utilize this new notification system, enhancing user feedback during various processes. Additionally, minor adjustments were made to prop declarations in some components.

Changes

File Path Change Summary
apps/router/src/gateway-ui/components/federations/ConnectFederation.tsx Added useNotification import; integrated showError and showInfo for notifications; updated handleConnectFederation for better error handling; modified modal rendering logic.
apps/router/src/guardian-ui/components/setup/RunDKG.tsx Enhanced pollDkg function with showInfo and showSuccess notifications; updated error handling to use translated messages.
apps/router/src/guardian-ui/components/setup/screens/connectGuardians/ConnectGuardians.tsx Added useNotification import; integrated showSuccess in handleApprove for user feedback.
apps/router/src/guardian-ui/components/setup/screens/setConfiguration/SetConfiguration.tsx Removed explicit type annotation for next prop in component declaration.
apps/router/src/guardian-ui/components/setup/screens/verifyGuardians/VerifyGuardians.tsx Added useNotification import; integrated showSuccess, showError, and showInfo for notifications during verification and consensus processes.
apps/router/src/guardian-ui/setup/FederationSetup.tsx Added useNotification for handleBack and handleRestart functions to manage user feedback through notifications.
apps/router/src/home/NotificationProvider.tsx Introduced NotificationProvider component with context for managing notifications; created useNotification hook for accessing notification methods.
apps/router/src/index.tsx Integrated ChakraProvider and NotificationProvider into the application structure for better notification management.

Possibly related PRs

  • feat: new auth manager uncomplicated #558: The changes in the ConnectFederation.tsx component regarding the integration of the useNotification hook are related to the modifications in the GuardianApi.ts and GatewayApi.ts files, where similar notification handling and user feedback mechanisms are introduced, enhancing user interaction across components.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

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

apps/router/src/gateway-ui/components/federations/ConnectFederation.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /apps/router/.eslintrc.js
Error: Cannot find module '@fedimint/eslint-config'
Require stack:

  • /apps/router/.eslintrc.js
  • /node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/eslint/lib/eslint/index.js
  • /node_modules/eslint/lib/cli.js
  • /node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/apps/router/.eslintrc.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)

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

🧹 Outside diff range and nitpick comments (4)
apps/router/src/home/NotificationProvider.tsx (1)

15-69: Consider making notification defaults configurable

The component has hardcoded values for duration (5000ms) and position ('top-right'). Consider accepting these as props with defaults to make the provider more flexible for different use cases.

-export const NotificationProvider: React.FC<React.PropsWithChildren> = ({
+interface NotificationProviderProps extends React.PropsWithChildren {
+  defaultDuration?: number;
+  defaultPosition?: UseToastOptions['position'];
+}
+
+export const NotificationProvider: React.FC<NotificationProviderProps> = ({
   children,
+  defaultDuration = 5000,
+  defaultPosition = 'top-right',
 }) => {
   // ...
   const showNotification = useCallback(
     (message: string, status: UseToastOptions['status'], options?: UseToastOptions) => {
       toast({
         description: message,
         status,
-        duration: 5000,
+        duration: defaultDuration,
         isClosable: true,
-        position: 'top-right',
+        position: defaultPosition,
         ...options,
       });
     },
-    [toast]
+    [toast, defaultDuration, defaultPosition]
   );
apps/router/src/guardian-ui/components/setup/RunDKG.tsx (1)

Line range hint 1-18: Add missing notification imports

The notification functions (showInfo, showSuccess) are used but not imported. Add the required imports from the notification provider.

Add this import:

 import { useTranslation } from '@fedimint/utils';
+import { useNotification } from '../../../providers/NotificationProvider';
 import { useEllipsis } from '../../hooks';

Then initialize the notification hooks at the start of the component:

const { showInfo, showSuccess } = useNotification();
apps/router/src/gateway-ui/components/federations/ConnectFederation.tsx (1)

Line range hint 171-171: Fix modal onClose handler implementation

The onClose prop should be a function that checks the loading state, not a boolean expression.

-          <ConnectFedModal isOpen={loading} onClose={() => !loading} />
+          <ConnectFedModal isOpen={loading} onClose={() => loading ? undefined : onClose()} />
apps/router/src/guardian-ui/components/setup/screens/verifyGuardians/VerifyGuardians.tsx (1)

154-155: Consider combining success notifications

Two consecutive notifications (success and info) might overwhelm the user. Consider combining these into a single success message.

-          showSuccess(t('verify-guardians.verified'));
-          showInfo(t('verify-guardians.all-guardians-verified'));
+          showSuccess(t('verify-guardians.verified') + '. ' + t('verify-guardians.all-guardians-verified'));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cf02442 and 2df32c9.

📒 Files selected for processing (8)
  • apps/router/src/gateway-ui/components/federations/ConnectFederation.tsx (3 hunks)
  • apps/router/src/guardian-ui/components/setup/RunDKG.tsx (1 hunks)
  • apps/router/src/guardian-ui/components/setup/screens/connectGuardians/ConnectGuardians.tsx (2 hunks)
  • apps/router/src/guardian-ui/components/setup/screens/setConfiguration/SetConfiguration.tsx (1 hunks)
  • apps/router/src/guardian-ui/components/setup/screens/verifyGuardians/VerifyGuardians.tsx (4 hunks)
  • apps/router/src/guardian-ui/setup/FederationSetup.tsx (4 hunks)
  • apps/router/src/home/NotificationProvider.tsx (1 hunks)
  • apps/router/src/index.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/router/src/guardian-ui/components/setup/screens/setConfiguration/SetConfiguration.tsx
🧰 Additional context used
📓 Learnings (1)
apps/router/src/guardian-ui/setup/FederationSetup.tsx (1)
Learnt from: Kodylow
PR: fedimint/ui#570
File: apps/router/src/guardian-ui/setup/FederationSetup.tsx:23-23
Timestamp: 2024-11-12T07:32:55.886Z
Learning: In `apps/router/src/guardian-ui/setup/FederationSetup.tsx`, the hooks `useGuardianSetupApi` and `useGuardianSetupContext` are correctly imported from `'../../hooks'`.
🔇 Additional comments (7)
apps/router/src/home/NotificationProvider.tsx (3)

1-9: LGTM: Well-structured interface definition

The interface properly defines the notification methods with correct typing for messages and options.


11-13: LGTM: Proper context initialization

The undefined initial value ensures proper provider usage.


71-79: LGTM: Well-implemented custom hook

The hook follows React best practices and provides clear error messages.

apps/router/src/guardian-ui/components/setup/screens/connectGuardians/ConnectGuardians.tsx (1)

27-27: LGTM! Clean notification integration.

The notification system integration is well-implemented:

  • Proper hook usage and dependency management
  • Notification is shown before navigation
  • Translations are correctly utilized

Also applies to: 34-34, 60-62

apps/router/src/guardian-ui/components/setup/screens/verifyGuardians/VerifyGuardians.tsx (3)

44-44: LGTM: Notification hooks properly integrated

The NotificationProvider import and hook usage are correctly implemented.

Also applies to: 73-73


170-173: LGTM: Dependencies properly declared

The dependency arrays for both useEffect and handleNext are correctly updated to include the notification functions.

Also applies to: 187-187


180-180: Ensure error handling is comprehensive

The error notification is shown after setting the error state. Consider adding more specific error messages for different failure scenarios.

Also applies to: 184-184

Comment on lines +54 to +61
//showInfo(t('run-dkg.waiting-header'));
break;
case GuardianServerStatus.ReadyForConfigGen:
setIsWaitingForOthers(true);
//showInfo(t('run-dkg.waiting-for-others'));
break;
case GuardianServerStatus.VerifyingConfigs:
//showSuccess(t('run-dkg.completed'));
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

Critical: Uncomment notification calls for user feedback

The commented out notification calls at critical stages of the DKG process should be enabled to provide essential user feedback, as specified in the PR objectives. These notifications are crucial for:

  1. Informing users when DKG is running
  2. Indicating when the system is waiting for other peers
  3. Confirming successful verification

Apply this diff to restore the notifications:

-            //showInfo(t('run-dkg.waiting-header'));
+            showInfo(t('run-dkg.waiting-header'));
             break;
           case GuardianServerStatus.ReadyForConfigGen:
             setIsWaitingForOthers(true);
-            //showInfo(t('run-dkg.waiting-for-others'));
+            showInfo(t('run-dkg.waiting-for-others'));
             break;
           case GuardianServerStatus.VerifyingConfigs:
-            //showSuccess(t('run-dkg.completed'));
+            showSuccess(t('run-dkg.completed'));
             next();
📝 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
//showInfo(t('run-dkg.waiting-header'));
break;
case GuardianServerStatus.ReadyForConfigGen:
setIsWaitingForOthers(true);
//showInfo(t('run-dkg.waiting-for-others'));
break;
case GuardianServerStatus.VerifyingConfigs:
//showSuccess(t('run-dkg.completed'));
showInfo(t('run-dkg.waiting-header'));
break;
case GuardianServerStatus.ReadyForConfigGen:
setIsWaitingForOthers(true);
showInfo(t('run-dkg.waiting-for-others'));
break;
case GuardianServerStatus.VerifyingConfigs:
showSuccess(t('run-dkg.completed'));

Comment on lines +121 to +128
<SharedChakraProvider theme={theme}>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<AppContextProvider>
<NotificationProvider>
<App />
</NotificationProvider>
</AppContextProvider>
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

Consider moving ColorModeScript and Fonts inside NotificationProvider

The current provider order might prevent notifications from respecting theme/font settings since ColorModeScript and Fonts are outside the NotificationProvider.

Apply this diff to fix the provider order:

  <SharedChakraProvider theme={theme}>
-   <ColorModeScript />
-   <Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
    <AppContextProvider>
      <NotificationProvider>
+       <ColorModeScript />
+       <Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
        <App />
      </NotificationProvider>
    </AppContextProvider>
  </SharedChakraProvider>
📝 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
<SharedChakraProvider theme={theme}>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<AppContextProvider>
<NotificationProvider>
<App />
</NotificationProvider>
</AppContextProvider>
<SharedChakraProvider theme={theme}>
<AppContextProvider>
<NotificationProvider>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<App />
</NotificationProvider>
</AppContextProvider>

Comment on lines +120 to +130
<ChakraProvider>
<SharedChakraProvider theme={theme}>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<AppContextProvider>
<NotificationProvider>
<App />
</NotificationProvider>
</AppContextProvider>
</SharedChakraProvider>
</ChakraProvider>
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

Remove redundant ChakraProvider wrapper

The ChakraProvider wrapping SharedChakraProvider is redundant and could cause theme conflicts or performance issues, as SharedChakraProvider likely already includes ChakraProvider internally.

Apply this diff to fix the provider hierarchy:

- <ChakraProvider>
    <SharedChakraProvider theme={theme}>
      <ColorModeScript />
      <Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
      <AppContextProvider>
        <NotificationProvider>
          <App />
        </NotificationProvider>
      </AppContextProvider>
    </SharedChakraProvider>
- </ChakraProvider>
📝 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
<ChakraProvider>
<SharedChakraProvider theme={theme}>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<AppContextProvider>
<NotificationProvider>
<App />
</NotificationProvider>
</AppContextProvider>
</SharedChakraProvider>
</ChakraProvider>
<SharedChakraProvider theme={theme}>
<ColorModeScript />
<Fonts spaceGroteskTtf={spaceGroteskTtf} interTtf={interTtf} />
<AppContextProvider>
<NotificationProvider>
<App />
</NotificationProvider>
</AppContextProvider>
</SharedChakraProvider>

Comment on lines +107 to +110
// showSuccess(t('connect-federation.success-message'));
renderConnectedFedCallback(federation);
setConnectInfo('');
onClose();
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 success notification for federation connection

The success case should display a notification to maintain consistent user feedback across the application.

-        // showSuccess(t('connect-federation.success-message'));
+        showSuccess(t('connect-federation.success-message'));
         renderConnectedFedCallback(federation);
         setConnectInfo('');
         onClose();
📝 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
// showSuccess(t('connect-federation.success-message'));
renderConnectedFedCallback(federation);
setConnectInfo('');
onClose();
showSuccess(t('connect-federation.success-message'));
renderConnectedFedCallback(federation);
setConnectInfo('');
onClose();

Comment on lines +102 to +118
showInfo(t('connect-federation.progress-modal-text'));

api
.connectFederation(connectInfo.trim())
.then((federation) => {
// showSuccess(t('connect-federation.success-message'));
renderConnectedFedCallback(federation);
setConnectInfo('');
onClose();
})
.catch(({ message, error }) => {
console.error(error);
setErrorMsg(t('connect-federation.error-message', { error: message }));
const errorMessage = t('connect-federation.error-message', {
error: message,
});
showError(errorMessage);
setErrorMsg(errorMessage);
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

Clear error state before new connection attempt

The error message state should be cleared when starting a new connection to prevent stale errors from being displayed.

   const handleConnectFederation = () => {
     setLoading(true);
+    setErrorMsg('');
     showInfo(t('connect-federation.progress-modal-text'));

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

Comment on lines +64 to +65
showSuccess(t('common.back'));
}, [dispatch, prevProgress, showSuccess, t]);
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

Reconsider showing success notification for back navigation

Showing a success notification for back navigation doesn't align with typical UX patterns, as going back is generally considered a neutral action that doesn't warrant success feedback. Consider removing this notification to avoid unnecessary visual noise.

  const handleBack = useCallback(() => {
    if (!prevProgress) return;
    dispatch({ type: SETUP_ACTION_TYPE.SET_PROGRESS, payload: prevProgress });
    window.scrollTo(0, 0);
-    showSuccess(t('common.back'));
  }, [dispatch, prevProgress, showSuccess, t]);
📝 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
showSuccess(t('common.back'));
}, [dispatch, prevProgress, showSuccess, t]);
if (!prevProgress) return;
dispatch({ type: SETUP_ACTION_TYPE.SET_PROGRESS, payload: prevProgress });
window.scrollTo(0, 0);
}, [dispatch, prevProgress, showSuccess, t]);

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

Successfully merging this pull request may close these issues.

1 participant