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

Confirm Dialog For Navigation on Edited Questionnaire Form #9838

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Jan 8, 2025

Proposed Changes

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 navigation prevention mechanism to protect unsaved changes in questionnaire forms
    • Implemented a custom hook to warn users before navigating away from forms with pending edits
  • Improvements

    • Enhanced form interaction by preventing accidental data loss
    • Added user-friendly navigation protection with customizable warning messages

@Jacobjeevan Jacobjeevan requested a review from a team as a code owner January 8, 2025 06:48
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

The pull request introduces a new custom hook usePreventNavigation to prevent users from accidentally navigating away from a questionnaire form with unsaved changes. The implementation adds a isDirty state to track form modifications in the QuestionnaireForm component. When the form contains any edited responses, the hook triggers browser and in-app navigation prevention mechanisms, displaying confirmation dialogs to protect users from unintentionally losing their work.

Changes

File Change Summary
src/components/Questionnaire/QuestionnaireForm.tsx - Added isDirty state variable
- Implemented useEffect to track form modifications
- Integrated usePreventNavigation hook
src/hooks/usePreventNavigation.ts - Created new custom hook usePreventNavigation
- Added event listeners for beforeunload and link navigation
- Implemented confirmation dialog logic

Assessment against linked issues

Objective Addressed Explanation
Ask confirmation before navigating away
Provide options to stay or leave the page
Prevent unintentional data loss

Possibly related PRs

Suggested labels

needs review, needs testing, P1

Suggested reviewers

  • rithviknishad

Poem

🐰 A rabbit's tale of form protection,
Where changes dance with navigation's reflection
No data lost, no work undone
A hook that saves, a battle won!
Hop away, but first beware -
Your unsaved work, we'll keep with care! 🚦


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

netlify bot commented Jan 8, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 22da20d
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677e1fc77f2ff4000800d2e5
😎 Deploy Preview https://deploy-preview-9838--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.

@Jacobjeevan Jacobjeevan changed the title Confirm Dialog For Navigation on Edited Encounter Form Confirm Dialog For Navigation on Edited Questionnaire Form Jan 8, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/components/Questionnaire/QuestionnaireForm.tsx (1)

Line range hint 251-259: Reset isDirty state after successful form submission.

The isDirty state should be reset to false after successful form submission to prevent showing the navigation warning unnecessarily.

  toast.success("Questionnaire submitted successfully");
+ setIsDirty(false);
  onSubmit?.();
🧹 Nitpick comments (3)
src/hooks/usePreventNavigation.ts (1)

8-13: Consider memoizing the options object.

To prevent unnecessary re-renders, consider memoizing the options object passed to the hook using useMemo.

+ const options = useMemo(() => ({
+   isDirty,
+   message: message ?? "You have unsaved changes. Are you sure you want to leave?"
+ }), [isDirty, message]);

- export function usePreventNavigation({
-   isDirty,
-   message = "You have unsaved changes. Are you sure you want to leave?",
- }: UsePreventNavigationOptions) {
+ export function usePreventNavigation(options: UsePreventNavigationOptions) {
+   const { isDirty, message = "You have unsaved changes. Are you sure you want to leave?" } = options;
src/components/Questionnaire/QuestionnaireForm.tsx (2)

14-14: Add i18n support for the navigation warning message.

Since the project uses i18next (imported as t), consider translating the navigation warning message.

- usePreventNavigation({ isDirty });
+ usePreventNavigation({ 
+   isDirty,
+   message: t("unsaved_changes_warning")
+ });

Also applies to: 66-66, 88-88


108-119: Optimize form modification detection.

The current implementation:

  1. Runs on every questionnaireForms change
  2. Could cause unnecessary re-renders
  3. Performs deep array traversal on each update

Consider using a reducer pattern or memoization:

+ const hasEdits = useMemo(() => 
+   questionnaireForms.some((form) =>
+     form.responses.some(
+       (response) =>
+         response.values.length > 0 ||
+         response.note ||
+         response.body_site ||
+         response.method,
+     ),
+   ),
+   [questionnaireForms]
+ );

- useEffect(() => {
-   const hasEdits = questionnaireForms.some((form) =>
-     form.responses.some(
-       (response) =>
-         response.values.length > 0 ||
-         response.note ||
-         response.body_site ||
-         response.method,
-     ),
-   );
-   setIsDirty(hasEdits);
- }, [questionnaireForms]);
+ useEffect(() => {
+   setIsDirty(hasEdits);
+ }, [hasEdits]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between adac786 and 22da20d.

📒 Files selected for processing (2)
  • src/components/Questionnaire/QuestionnaireForm.tsx (4 hunks)
  • src/hooks/usePreventNavigation.ts (1 hunks)
🔇 Additional comments (2)
src/hooks/usePreventNavigation.ts (2)

3-6: LGTM! Well-defined interface.

The interface clearly defines the required options with appropriate types.


37-53: LGTM! Proper event listener management.

The implementation:

  • Correctly uses the capture phase for early interception
  • Properly cleans up listeners to prevent memory leaks
  • Has appropriate dependency tracking

Comment on lines +21 to +35
const preventNavigation = (e: Event) => {
const confirmLeave = window.confirm(message);

if (!confirmLeave) {
e.preventDefault();
e.stopPropagation();
window.history.replaceState(null, "", window.location.pathname);
return false;
}
};

const handleLinkClick = (e: MouseEvent) => {
const link = (e.target as HTMLElement).closest("a");
if (link) preventNavigation(e);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Integrate with the project's routing system for complete navigation prevention

The codebase uses a custom routing system (see src/Routers/). The current implementation only handles browser-native navigation events but misses router-based navigation. To fully prevent unwanted navigation:

  • Integrate with router events in src/Routers/AppRouter.tsx or relevant route definition files
  • Consider implementing a higher-level navigation guard that works with both browser and router events
  • Keep the current browser event handlers for external navigation
🔗 Analysis chain

Consider using a custom dialog component instead of window.confirm.

The native window.confirm dialog:

  • Is not customizable for consistent UI/UX
  • May be blocked by some browsers
  • Cannot be styled to match the application theme

Consider using your application's dialog component system instead.

Enhance link detection for routing libraries.

The current link detection might miss navigation attempts through routing libraries (e.g., React Router). Consider adding support for router events.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for router usage in the project
rg -l "react-router|next/router|@reach/router" --type ts --type tsx

Length of output: 97


Script:

#!/bin/bash
# Search for router-related imports and usage without file type restrictions
rg -l "from ['\"]react-router|from ['\"]next/router|from ['\"]@reach/router"

# Search for common routing patterns and components
rg -l "useNavigate|useRouter|Link |Router|BrowserRouter|Routes|Route "

# Look for route definitions
rg -l "path=['\"]|route=['\"]|path: ['\"]"

Length of output: 3294

@nihal467
Copy link
Member

nihal467 commented Jan 9, 2025

image

@Jacobjeevan When we click the cancel button in the pop-up, we are still being exited from the questionnaire. The ideal behavior should be that when the user hits cancel, they should stay on the same page and be allowed to continue editing.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 10, 2025
Copy link

👋 Hi, @Jacobjeevan,
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
merge conflict pull requests with merge conflict test failed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Ask Confirmation Before Navigating Away from Questions Page When State is Dirty
2 participants