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

Fix Notification Subscription Loading and Messaging Errors #9038

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

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Nov 7, 2024

Proposed Changes

Before :
Subscribe issue
Image

Image

Irrelevant Notification Message on clicking unsubscribe:
Image

After:
image

image

@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

  • New Features

    • Added clear notification messages for subscription actions, including success and failure confirmations.
  • Bug Fixes

    • Improved error handling for notification subscriptions, providing immediate feedback if permission is denied or if the subscription fails.
  • User Experience Enhancements

    • Streamlined user feedback during notification management, ensuring users are informed of their subscription status effectively.

@Mahendar0701 Mahendar0701 requested a review from a team as a code owner November 7, 2024 04:39
Copy link

coderabbitai bot commented Nov 7, 2024

Walkthrough

The changes in this pull request involve updates to the localization file en.json and modifications to the NotificationsList.tsx component. New entries have been added to the localization file to enhance user notifications related to subscription actions. In the NotificationsList.tsx, the subscription logic has been refined to improve error handling and user feedback, particularly addressing scenarios where notification permissions are denied or cancelled.

Changes

File Change Summary
public/locale/en.json Added new notification messages: "notification_cancelled", "subscribed_successfully", "subscription_failed", "unsubscribed_successfully"
src/components/Notifications/NotificationsList.tsx Refined subscription logic, improved error handling, and added user feedback for subscription status.

Assessment against linked issues

Objective Addressed Explanation
Show "permission denied" message when user closes permission prompt (#9021)
Stop loading the Subscribe button once API rejection is received (#9021)
Display relevant notification message upon Unsubscribe action (#9021)

Poem

🐇 In the realm of notifications bright,
New messages spring forth, a joyful sight.
"Subscribed successfully," they cheer,
"Cancelled?" No worries, we’re still here!
With clearer paths and feedback true,
A hop of joy for me and you! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 54588b2 and 115d9b1.

📒 Files selected for processing (1)
  • src/components/Notifications/NotificationsList.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Notifications/NotificationsList.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

netlify bot commented Nov 7, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 115d9b1
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672cb8098e3f0f00086e02ae
😎 Deploy Preview https://deploy-preview-9038--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

@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 (2)
src/components/Notifications/NotificationsList.tsx (1)

308-311: Consider using Success notification for unsubscribe confirmation

The unsubscribe confirmation uses a warning notification (Warn), but since unsubscribing is a successful action rather than a cautionary event, consider using Success instead to maintain consistent UX patterns.

-                Warn({
+                Success({
                   msg: t("unsubscribed_successfully"),
                 });
public/locale/en.json (1)

891-891: Fix inconsistent message formatting.

The notification messages should follow consistent formatting:

-  "notification_cancelled": "Notification cancelled",
+  "notification_cancelled": "Notification Cancelled",
   "subscribed_successfully": "Subscribed Successfully",
   "subscription_failed": "Subscription Failed",
-  "unsubscribed_successfully": "Unsubscribed Successfully.",
+  "unsubscribed_successfully": "Unsubscribed Successfully"

This ensures:

  1. Consistent title case capitalization across all words
  2. Consistent punctuation (no trailing periods)

Also applies to: 1161-1161, 1163-1163, 1206-1206

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c27f595 and 54588b2.

📒 Files selected for processing (2)
  • public/locale/en.json (3 hunks)
  • src/components/Notifications/NotificationsList.tsx (3 hunks)
🔇 Additional comments (2)
src/components/Notifications/NotificationsList.tsx (1)

246-253: LGTM: Permission check prevents infinite loading state

The implementation correctly checks the notification permission status before attempting to subscribe, preventing the infinite loading state when permission is denied. The error message is properly localized using the translation system.

public/locale/en.json (1)

891-891: LGTM! The notification messages are clear and appropriate.

The new localization entries properly support the notification subscription feature improvements mentioned in the PR objectives.

Also applies to: 1161-1161, 1163-1163, 1206-1206

Comment on lines +340 to +351
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
Copy link

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 key encoding

The btoa encoding of push notification keys could fail if the binary data contains invalid characters. Consider adding try-catch blocks around the encoding operations.

-      const p256dh = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("p256dh") as any) as any,
-        ),
-      );
-      const auth = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("auth") as any) as any,
-        ),
-      );
+      let p256dh, auth;
+      try {
+        p256dh = btoa(
+          String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
+        );
+        auth = btoa(
+          String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
+        );
+      } catch (error) {
+        throw new Error("Failed to encode push notification keys");
+      }
📝 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 p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
let p256dh, auth;
try {
p256dh = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
);
auth = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
);
} catch (error) {
throw new Error("Failed to encode push notification keys");
}

Comment on lines 332 to 396
try {
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_key,
});
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);

const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};
const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};

const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});

if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
Success({
msg: t("subscribed_successfully"),
});
setIsSubscribing(false);
} else {
Error({
msg: t("subscription_failed"),
});
setIsSubscribing(false);
}
} catch (error) {
const permission = Notification.permission;

if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
if (permission === "denied") {
Warn({
msg: t("notification_permission_denied"),
});
setIsSubscribing(false);
return;
} else if (permission === "default") {
Warn({
msg: t("notification_cancelled"),
});
setIsSubscribing(false);
return;
}
Error({
msg: t("subscription_failed"),
});
} finally {
setIsSubscribing(false);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor error handling and state management

While the error handling is comprehensive, there are a few improvements that could be made:

  1. The setIsSubscribing(false) is duplicated across the function
  2. The error handling in the catch block could be simplified
  3. The type casting could be more specific

Consider this refactoring:

  async function subscribe() {
    setIsSubscribing(true);
    try {
      const response = await request(routes.getPublicKey);
      const public_key = response.data?.public_key;
      const sw = await navigator.serviceWorker.ready;
      const push = await sw.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: public_key,
      });
-      const p256dh = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("p256dh") as any) as any,
-        ),
-      );
-      const auth = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("auth") as any) as any,
-        ),
-      );
+      const p256dh = btoa(
+        String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
+      );
+      const auth = btoa(
+        String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
+      );

      const data = {
        pf_endpoint: push.endpoint,
        pf_p256dh: p256dh,
        pf_auth: auth,
      };

      const { res } = await request(routes.updateUserPnconfig, {
        pathParams: { username: username },
        body: data,
      });

      if (res?.ok) {
        setIsSubscribed("SubscribedOnThisDevice");
        Success({
          msg: t("subscribed_successfully"),
        });
-        setIsSubscribing(false);
      } else {
        Error({
          msg: t("subscription_failed"),
        });
-        setIsSubscribing(false);
      }
    } catch (error) {
      const permission = Notification.permission;

-      if (permission === "denied") {
-        Warn({
-          msg: t("notification_permission_denied"),
-        });
-        setIsSubscribing(false);
-        return;
-      } else if (permission === "default") {
-        Warn({
-          msg: t("notification_cancelled"),
-        });
-        setIsSubscribing(false);
-        return;
-      }
-      Error({
-        msg: t("subscription_failed"),
-      });
+      const messages = {
+        denied: t("notification_permission_denied"),
+        default: t("notification_cancelled"),
+      };
+      
+      if (permission in messages) {
+        Warn({ msg: messages[permission as keyof typeof messages] });
+      } else {
+        Error({ msg: t("subscription_failed") });
+      }
    } finally {
      setIsSubscribing(false);
    }
  }
📝 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
try {
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_key,
});
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};
const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
Success({
msg: t("subscribed_successfully"),
});
setIsSubscribing(false);
} else {
Error({
msg: t("subscription_failed"),
});
setIsSubscribing(false);
}
} catch (error) {
const permission = Notification.permission;
if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
if (permission === "denied") {
Warn({
msg: t("notification_permission_denied"),
});
setIsSubscribing(false);
return;
} else if (permission === "default") {
Warn({
msg: t("notification_cancelled"),
});
setIsSubscribing(false);
return;
}
Error({
msg: t("subscription_failed"),
});
} finally {
setIsSubscribing(false);
try {
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_key,
});
const p256dh = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
);
const auth = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
);
const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
Success({
msg: t("subscribed_successfully"),
});
} else {
Error({
msg: t("subscription_failed"),
});
}
} catch (error) {
const permission = Notification.permission;
const messages = {
denied: t("notification_permission_denied"),
default: t("notification_cancelled"),
};
if (permission in messages) {
Warn({ msg: messages[permission as keyof typeof messages] });
} else {
Error({ msg: t("subscription_failed") });
}
} finally {
setIsSubscribing(false);
}

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.

Notification Subscription Error Handling and Unsubscribe Message Mismatch
2 participants