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 Camera Capture on Retake and Close #9180

Merged

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 22, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers


Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation to reflect the changes.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to the issue.
  • Request for Peer Reviews.
  • Completion of QA.

Summary by CodeRabbit

  • New Features
    • Introduced a reset functionality in the Camera Capture dialog, allowing users to clear their captured images and uploaded files.
    • Enhanced audio recording management in the Audio Capture dialog with improved microphone access and resource handling.
  • Bug Fixes
    • Improved handling of the reset action after capturing an image through updated button interactions.
  • Refactor
    • Enhanced clarity and reusability of the file clearing process in the file upload functionality.

@JavidSumra JavidSumra requested a review from a team as a code owner November 22, 2024 06:38
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

Walkthrough

The pull request introduces modifications to the CameraCaptureDialog component and the useFileUpload hook. A new prop, onResetCapture, is added to the CameraCaptureDialogProps interface, enabling the component to reset its capture state. The clearFiles method is introduced in the useFileUpload hook to clear uploaded files, and it is integrated with the onResetCapture prop. This ensures that when users click "retake" or "close," the previous capture state is reset, preventing unnecessary file saves.

Changes

File Change Summary
src/components/Files/CameraCaptureDialog.tsx Added onResetCapture prop to CameraCaptureDialogProps and updated button handlers to include reset logic.
src/hooks/useFileUpload.tsx Introduced clearFiles method to reset files and uploadFileNames, and updated its reference in the hook.
src/components/Files/AudioCaptureDialog.tsx Added mediaStreamRef for better media management and introduced cleanup logic for resource management.

Assessment against linked issues

Objective Addressed Explanation
The image should not be saved when the user clicks "Retake." (9179)

Possibly related PRs

  • Update Camera Capture Component #9159: This PR updates the CameraCaptureDialog component, which is directly related to the main PR as both involve modifications to the same component, enhancing its functionality and user experience.

Suggested labels

needs review

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

In the dialog where captures play,
A reset now brightens the day.
Click "retake," let files be clear,
No more saves to cause you fear!
With a hop and a skip, we cheer,
For a cleaner capture, oh so dear! 🐇✨

Warning

Rate limit exceeded

@JavidSumra has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 33 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 4b9925d and 7bad523.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b9925d and 7bad523.

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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 7bad523
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6746e36ad8fde10008c23f3d
😎 Deploy Preview https://deploy-preview-9180--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
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 (3)
src/components/Files/CameraCaptureDialog.tsx (2)

174-176: Consider reordering operations in close handler

The current order of operations is:

  1. Reset preview
  2. Hide dialog
  3. Reset capture

Consider calling onResetCapture before hiding the dialog to ensure cleanup happens before the component potentially unmounts:

 onClick={() => {
   setPreviewImage(null);
+  onResetCapture();
   onHide();
-  onResetCapture();
 }}

235-237: Consider reordering operations in laptop close handler

Similar to the mobile close handler, consider reordering operations:

 onClick={() => {
   setPreviewImage(null);
+  onResetCapture();
   onHide();
-  onResetCapture();
 }}
src/hooks/useFileUpload.tsx (1)

264-264: Consider adding reset capability to AudioCaptureDialog for consistency.

While the camera capture reset is now handled properly, the audio capture dialog lacks similar reset functionality. This could lead to inconsistent behavior between the two capture methods.

Consider adding the onResetCapture prop to AudioCaptureDialog:

 <AudioCaptureDialog
   show={audioModalOpen}
   onHide={() => setAudioModalOpen(false)}
   onCapture={(file) => {
     setFiles((prev) => [...prev, file]);
   }}
+  onResetCapture={clearFiles}
   autoRecord
 />

Also applies to: 265-265, 266-266, 267-267, 268-268, 269-269, 270-270, 271-271, 272-272

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 10369c5 and 5c21667.

📒 Files selected for processing (2)
  • src/components/Files/CameraCaptureDialog.tsx (5 hunks)
  • src/hooks/useFileUpload.tsx (3 hunks)
🔇 Additional comments (6)
src/components/Files/CameraCaptureDialog.tsx (4)

18-18: LGTM: Appropriate prop addition for reset functionality

The new onResetCapture prop is correctly typed and mandatory, which aligns with its essential role in fixing the unnecessary file saving issue.


22-22: LGTM: Clean props destructuring

The onResetCapture prop is correctly destructured alongside other props.


149-151: LGTM: Correct implementation of reset on retake

The reset functionality is properly implemented in the retake button handler.


212-214: LGTM: Consistent implementation with mobile retake

The reset functionality is properly implemented and consistent with the mobile version.

src/hooks/useFileUpload.tsx (2)

252-255: LGTM! Implementation addresses the core issue.

The clearFiles function correctly resets both the files and file names states, effectively preventing unnecessary file saves when retaking photos.


317-317: Verify usage of clearFiles across the codebase.

The clearFiles function is now properly exposed in the hook's return object. Let's verify its usage across the codebase to ensure it's being used appropriately in all necessary places.

✅ Verification successful

The clearFiles function is properly implemented and exposed

The verification shows that:

  • The clearFiles function is correctly implemented in useFileUpload hook, resetting both files and upload file names
  • It's properly exposed in the hook's return interface
  • It's being used appropriately in the hook's implementation for resetting files (e.g., with onResetCapture)
  • The hook is imported and used in two components: PatientConsentRecords and FileUpload
  • No other manual file reset patterns were found that should be replaced with clearFiles
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of useFileUpload hook and verify clearFiles implementation

# Find files that import useFileUpload
echo "Files importing useFileUpload:"
rg -l "useFileUpload"

# Find potential usage of clearFiles from the hook
echo "\nPotential clearFiles usage:"
rg "clearFiles" --type tsx --type ts

# Find other potential file reset patterns that might need to use clearFiles
echo "\nOther potential reset patterns:"
rg -A 2 "setFiles\(\[\]\)" --type tsx --type ts

Length of output: 494


Script:

#!/bin/bash
# Let's try without file type flags since they're not recognized
# First, let's check the implementation and interface of clearFiles
echo "Implementation and interface of clearFiles:"
rg -A 5 "clearFiles" src/hooks/useFileUpload.tsx

# Find all usages of useFileUpload and surrounding context
echo "\nUseFileUpload hook usages:"
rg -B 2 -A 5 "useFileUpload" src/components/Patient/PatientConsentRecords.tsx src/components/Files/FileUpload.tsx

# Check for file reset patterns without type flags
echo "\nFile reset patterns:"
rg -A 2 "setFiles\(\[\]\)"

Length of output: 3299

src/components/Files/CameraCaptureDialog.tsx 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 (2)
src/components/Files/AudioCaptureDialog.tsx (2)

62-65: Consider releasing microphone resources regardless of status

While the implementation works, consider moving the releaseMic() call outside the status check to ensure microphone resources are always released, even in edge cases.

  const handleStopRecording = () => {
+   releaseMic();
    if (status !== "RECORDING") return;
-   releaseMic();
    setStatus("RECORDED");
    stopRecording();
    timer.stop();
  };

107-115: Optimize the microphone release implementation

The implementation can be simplified while maintaining the same cleanup effectiveness.

  const releaseMic = () => {
    if (mediaStreamRef.current) {
-     mediaStreamRef.current.getTracks().forEach((track) => {
-       track.stop();
-       mediaStreamRef.current?.removeTrack(track);
-     });
+     mediaStreamRef.current.getTracks().forEach(track => track.stop());
      mediaStreamRef.current = null;
    }
  };

The removeTrack call is unnecessary since we're stopping the tracks and nullifying the reference. This change makes the code more concise while maintaining the same cleanup effectiveness.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5c21667 and 0c0f143.

📒 Files selected for processing (3)
  • src/components/Files/AudioCaptureDialog.tsx (5 hunks)
  • src/components/Files/CameraCaptureDialog.tsx (5 hunks)
  • src/hooks/useFileUpload.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Files/CameraCaptureDialog.tsx
  • src/hooks/useFileUpload.tsx
🔇 Additional comments (2)
src/components/Files/AudioCaptureDialog.tsx (2)

29-29: LGTM: Good practice for managing MediaStream lifecycle

The addition of mediaStreamRef using useRef is a proper way to maintain the MediaStream reference across component renders.


46-47: LGTM: Proper stream management implementation

Storing the MediaStream in the ref immediately after obtaining it ensures proper resource management.

src/components/Files/AudioCaptureDialog.tsx Outdated Show resolved Hide resolved
@nihal467
Copy link
Member

LGTM

Copy link
Contributor

@Jacobjeevan Jacobjeevan left a comment

Choose a reason for hiding this comment

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

LGTM

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

🧹 Outside diff range and nitpick comments (2)
src/components/Files/AudioCaptureDialog.tsx (2)

111-116: Consider separating cleanup into its own effect.

While the cleanup logic is correct, it might be better to separate it into a dedicated useEffect for better separation of concerns. The current effect handles both autoRecord initialization and cleanup.

Consider this refactor:

  useEffect(() => {
    if (autoRecord && show && status === "RECORDING") {
      handleStartRecording();
    }
-
-    return () => {
-      if (mediaStreamRef.current) {
-        mediaStreamRef.current.getTracks().forEach((track) => track.stop());
-        mediaStreamRef.current = null;
-      }
-    };
  }, [autoRecord, status, show]);
+
+ useEffect(() => {
+   return () => {
+     if (mediaStreamRef.current) {
+       mediaStreamRef.current.getTracks().forEach((track) => track.stop());
+       mediaStreamRef.current = null;
+     }
+   };
+ }, []);

Line range hint 134-134: Address the TODO comment about browser support.

The comment indicates a need to find a better link that supports all browsers. This should be addressed to ensure proper cross-browser compatibility.

Would you like me to help research and suggest a more universal browser settings URL pattern?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e81f9a1 and 4b9925d.

📒 Files selected for processing (1)
  • src/components/Files/AudioCaptureDialog.tsx (4 hunks)
🔇 Additional comments (2)
src/components/Files/AudioCaptureDialog.tsx (2)

29-29: LGTM: Good practice for managing media stream resources.

The addition of mediaStreamRef using useRef is a proper way to maintain a reference to the MediaStream across renders.


46-47: LGTM: Proper stream management implementation.

The media stream is correctly stored in the ref before starting the recording, enabling proper cleanup later.

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

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

@rithviknishad rithviknishad removed changes required merge conflict pull requests with merge conflict labels Nov 27, 2024
@rithviknishad rithviknishad merged commit f8c78fd into ohcnetwork:develop Nov 27, 2024
18 of 19 checks passed
Copy link

@JavidSumra Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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