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

Fixing NotificationsList on Service Worker #8686

Conversation

vishwansh01
Copy link
Contributor

@vishwansh01 vishwansh01 commented Oct 1, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers
Screenshot (35)

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

  • Bug Fixes

    • Improved error handling during the unsubscription process to prevent runtime errors.
  • New Features

    • Enhanced subscription management logic, ensuring better handling of service worker availability.
  • Improvements

    • Streamlined state management for subscription status, enhancing clarity and robustness.
    • Maintained existing functionality for marking notifications as read or unread while improving underlying logic.

@vishwansh01 vishwansh01 requested a review from a team as a code owner October 1, 2024 14:29
Copy link

netlify bot commented Oct 1, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit d02281d
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/671e5c17bf9e9f0008f7783d
😎 Deploy Preview https://deploy-preview-8686--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.

@nihal467
Copy link
Member

nihal467 commented Oct 8, 2024

LGTM

Copy link
Member

@khavinshankar khavinshankar left a comment

Choose a reason for hiding this comment

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

@vishwansh01 the logic looks, just some suggestions on readability

src/Components/Notifications/NotificationsList.tsx Outdated Show resolved Hide resolved
src/Components/Notifications/NotificationsList.tsx Outdated Show resolved Hide resolved
src/Components/Notifications/NotificationsList.tsx Outdated Show resolved Hide resolved
@bodhish
Copy link
Member

bodhish commented Oct 18, 2024

@vishwansh01 can you update the status here?

@AdityaJ2305
Copy link
Contributor

Hey @bodhish, Since @vishwansh01 hasn’t responded to the requested changes on the PR, can I create a new PR for this issue if he remains inactive?

@bodhish
Copy link
Member

bodhish commented Oct 21, 2024

@vishwansh01 will you be working on this issue?

@vishwansh01
Copy link
Contributor Author

@bodhish yes I am working

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Oct 21, 2024
@khavinshankar
Copy link
Member

@vishwansh01 fix the linting errors

Copy link

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


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

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Oct 23, 2024
@vishwansh01 vishwansh01 force-pushed the issues/8006/Fixing-TypeError-ServiceWorker branch from 857248e to 7e15e3c Compare October 23, 2024 13:17
@vishwansh01 vishwansh01 reopened this Oct 23, 2024
@vishwansh01 vishwansh01 reopened this Oct 23, 2024
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Oct 23, 2024
Copy link

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


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

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Oct 24, 2024
@bodhish
Copy link
Member

bodhish commented Oct 27, 2024

@vishwansh01 let me know when its up for review.

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Oct 27, 2024
@bodhish
Copy link
Member

bodhish commented Nov 5, 2024

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

✅ Actions performed

Full review triggered.

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes in the NotificationsList.tsx component focus on improving subscription management and notification state handling. Key updates include enhanced subscription logic that checks for the availability of the service worker, refined error handling during unsubscription, and streamlined state management for subscription status. While the core functionality for marking notifications as read or unread remains unchanged, the overall structure has been adjusted to ensure robustness and prevent runtime errors.

Changes

File Path Change Summary
src/components/Notifications/NotificationsList.tsx Updated subscription logic to check for navigator.serviceWorker, refined error handling in unsubscription, streamlined state management for isSubscribing, and maintained notification handling logic.

Assessment against linked issues

Objective Addressed Explanation
Safely check for service worker availability and handle undefined subscription object (8006)

🐇 In the meadow, notifications bloom,
With checks for service workers, no more gloom!
Errors are tamed, and states align,
A robust solution, oh how it shines!
Click and read, with joy we cheer,
For every update, we hold so dear! 🌼


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

🧹 Outside diff range and nitpick comments (2)
src/components/Notifications/NotificationsList.tsx (2)

264-266: Add user feedback for service worker unavailability.

The early return when service worker is unavailable is good, but users should be informed why the subscription functionality isn't working.

 if (!navigator.serviceWorker) {
+  Warn({
+    msg: t("push_notifications_not_supported"),
+  });
   return;
 }

Line range hint 441-458: Enhance error handling in initialSubscriptionState.

The current try-catch block could provide more specific error handling and user feedback.

 const intialSubscriptionState = async () => {
   try {
     const res = await request(routes.getUserPnconfig, {
       pathParams: { username: username },
     });
+    if (!navigator.serviceWorker) {
+      setIsSubscribed("NotSupported");
+      return;
+    }
     const reg = await navigator.serviceWorker.ready;
+    if (!reg.pushManager) {
+      setIsSubscribed("NotSupported");
+      return;
+    }
     const subscription = await reg.pushManager.getSubscription();
     if (!subscription && !res.data?.pf_endpoint) {
       setIsSubscribed("NotSubscribed");
     } else if (subscription?.endpoint === res.data?.pf_endpoint) {
       setIsSubscribed("SubscribedOnThisDevice");
     } else {
       setIsSubscribed("SubscribedOnAnotherDevice");
     }
   } catch (error) {
+    console.error('Failed to initialize subscription state:', error);
     Sentry.captureException(error);
+    setIsSubscribed("Error");
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 60f02ee and d02281d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)

Comment on lines +264 to +266
if (!navigator.serviceWorker) {
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add specific handling for iOS Chrome browser.

Since the PR aims to fix issues with Chrome Mobile iOS, we should add specific detection and handling for this browser where service workers are not supported.

+const isIOSChrome = /CriOS/i.test(navigator.userAgent);
+
+if (isIOSChrome) {
+  Warn({
+    msg: t("push_notifications_not_supported_ios_chrome"),
+  });
+  return;
+}
 if (!navigator.serviceWorker) {
   return;
 }

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

Comment on lines +305 to +334
if (reg.pushManager !== null && reg.pushManager !== undefined) {
setIsSubscribing(true);
reg.pushManager
.getSubscription()
.then(function (subscription) {
subscription
?.unsubscribe()
.then(async function (_successful) {
const data = {
pf_endpoint: "",
pf_p256dh: "",
pf_auth: "",
};
await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
setIsSubscribed("NotSubscribed");
setIsSubscribing(false);
})
.catch(function (_e) {
Error({
msg: t("unsubscribe_failed"),
});
});
});
})
.catch(function (_e) {
Error({ msg: t("subscription_error") });
});
})
.catch(function (_e) {
Error({ msg: t("subscription_error") });
});
}
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

Improve error handling in unsubscribe function.

While the null checks for pushManager are good, the error handling can be improved:

  1. The deeply nested promise chain makes error handling complex
  2. Error details are not logged
  3. Null subscription case isn't handled explicitly

Consider refactoring to async/await for better error handling:

-  navigator.serviceWorker.ready
-    .then(function (reg) {
-      if (reg.pushManager !== null && reg.pushManager !== undefined) {
-        setIsSubscribing(true);
-        reg.pushManager
-          .getSubscription()
-          .then(function (subscription) {
-            subscription
-              ?.unsubscribe()
-              .then(async function (_successful) {
-                const data = {
-                  pf_endpoint: "",
-                  pf_p256dh: "",
-                  pf_auth: "",
-                };
-                await request(routes.updateUserPnconfig, {
-                  pathParams: { username: username },
-                  body: data,
-                });
-                setIsSubscribed("NotSubscribed");
-                setIsSubscribing(false);
-              })
-              .catch(function (_e) {
-                Error({
-                  msg: t("unsubscribe_failed"),
-                });
-              });
-          })
-          .catch(function (_e) {
-            Error({ msg: t("subscription_error") });
-          });
-      }
-    })
-    .catch(function (_e) {
-      Sentry.captureException(_e);
-    });
+  try {
+    const reg = await navigator.serviceWorker.ready;
+    if (!reg.pushManager) {
+      throw new Error('Push manager not available');
+    }
+    
+    setIsSubscribing(true);
+    const subscription = await reg.pushManager.getSubscription();
+    
+    if (!subscription) {
+      setIsSubscribed("NotSubscribed");
+      return;
+    }
+    
+    await subscription.unsubscribe();
+    
+    const data = {
+      pf_endpoint: "",
+      pf_p256dh: "",
+      pf_auth: "",
+    };
+    
+    await request(routes.updateUserPnconfig, {
+      pathParams: { username: username },
+      body: data,
+    });
+    
+    setIsSubscribed("NotSubscribed");
+  } catch (error) {
+    Sentry.captureException(error);
+    Error({
+      msg: t(error.message === 'Push manager not available' 
+        ? "push_notifications_not_supported"
+        : "unsubscribe_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
if (reg.pushManager !== null && reg.pushManager !== undefined) {
setIsSubscribing(true);
reg.pushManager
.getSubscription()
.then(function (subscription) {
subscription
?.unsubscribe()
.then(async function (_successful) {
const data = {
pf_endpoint: "",
pf_p256dh: "",
pf_auth: "",
};
await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
setIsSubscribed("NotSubscribed");
setIsSubscribing(false);
})
.catch(function (_e) {
Error({
msg: t("unsubscribe_failed"),
});
});
});
})
.catch(function (_e) {
Error({ msg: t("subscription_error") });
});
})
.catch(function (_e) {
Error({ msg: t("subscription_error") });
});
}
try {
const reg = await navigator.serviceWorker.ready;
if (!reg.pushManager) {
throw new Error('Push manager not available');
}
setIsSubscribing(true);
const subscription = await reg.pushManager.getSubscription();
if (!subscription) {
setIsSubscribed("NotSubscribed");
return;
}
await subscription.unsubscribe();
const data = {
pf_endpoint: "",
pf_p256dh: "",
pf_auth: "",
};
await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
setIsSubscribed("NotSubscribed");
} catch (error) {
Sentry.captureException(error);
Error({
msg: t(error.message === 'Push manager not available'
? "push_notifications_not_supported"
: "unsubscribe_failed"
),
});
} finally {
setIsSubscribing(false);
}

@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
Copy link

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


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

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Nov 12, 2024
@sainak
Copy link
Member

sainak commented Nov 15, 2024

closing in favor of #8935

@sainak sainak closed this Nov 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required merge conflict pull requests with merge conflict tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

TypeError in NotificationsList Component on Service Worker Subscription Fetch
7 participants