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

Added centralized function to handle camera permission error #10989

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

Conversation

Harsh-D-2004
Copy link

@Harsh-D-2004 Harsh-D-2004 commented Mar 3, 2025

Proposed Changes

@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
    • Enhanced camera permission handling: Users now receive a clear, single notification if camera access is denied.
    • Improved error management in the avatar editing interface for a smoother experience when camera access issues occur.
    • Camera access permission is now checked before attempting to capture video in the Camera Capture Dialog, improving user experience and error handling.

@Harsh-D-2004 Harsh-D-2004 requested a review from a team as a code owner March 3, 2025 19:29
Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Walkthrough

This pull request introduces a new asynchronous function handleCameraPermission in the utility file, which requests camera access using getUserMedia with a specified facing mode. It handles errors by showing a warning toast (ensuring the toast is shown only once) and invokes a callback on permission denial. The AvatarEditModal.tsx and CameraCaptureDialog.tsx components have been updated to import and utilize this function, enhancing error handling and permission management for camera access.

Changes

File(s) Change Summary
src/Utils/cameraPermissionHandler.ts Added new function handleCameraPermission and its method requestPermission(device: "camera", cameraFacingMode: string). Introduced state management for warning toast and media constraints.
src/components/Common/AvatarEditModal.tsx Modified onUserMediaError to call requestPermission asynchronously for improved camera permission handling.
src/components/Files/CameraCaptureDialog.tsx Integrated handleCameraPermission to check for camera access before capturing video, replacing direct calls to getUserMedia. Improved error handling and state management for the camera stream.

Possibly related PRs

Suggested labels

tested, needs review

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

I'm a little rabbit in a code garden so bright,
Hopping 'round functions in the morning light.
I added a feature with a breezy, soft hop,
Where camera permissions now smoothly don't stop.
With a tap of toast and a callback cheer,
I celebrate the changes—coding magic is here!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51a437d and 10e3214.

📒 Files selected for processing (1)
  • src/Utils/cameraPermissionHandler.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Utils/cameraPermissionHandler.ts

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.
  • @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 Mar 3, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 10e3214
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67c7598d864a740008bee134
😎 Deploy Preview https://deploy-preview-10989.preview.ohc.network
📱 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.

import { useTranslation } from "react-i18next";
import { toast } from "sonner";

const { t } = useTranslation();
Copy link
Member

Choose a reason for hiding this comment

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

hooks are supposed to be used only inside react components


const { t } = useTranslation();

let toastShown = false;
Copy link
Member

Choose a reason for hiding this comment

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

keeping it global will cause undesired behaviours

Comment on lines 8 to 22
export const handleCameraPermission = async (
cameraFacingMode: string,
onPermissionDenied: () => void,
) => {
toastShown = false;
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: cameraFacingMode },
});
} catch (_error) {
if (!toastShown) {
toastShown = true;
toast.warning(t("camera_permission_denied"));
}
onPermissionDenied();
Copy link
Member

Choose a reason for hiding this comment

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

I'd say make a hook instead called useMediaDevicePermissions instead

@rithviknishad
Copy link
Member

let's use it on other places as well where camera is used

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

♻️ Duplicate comments (2)
src/Utils/cameraPermissionHandler.ts (2)

1-4: ⚠️ Potential issue

Critical issue: Hook usage outside of a React component

React hooks like useTranslation() can only be used inside React function components or custom hooks. Using them at the module level will cause runtime errors.

Refactor this to properly handle translations without using hooks at the module level:

-import { useTranslation } from "react-i18next";
+import i18next from "i18next";
 import { toast } from "sonner";

-const { t } = useTranslation();
+const t = (key: string) => i18next.t(key);

6-6: ⚠️ Potential issue

Avoid using global state variables

Using a global toastShown variable can cause unexpected behavior when multiple components use this utility simultaneously.

This should be encapsulated within the function or potentially use a more sophisticated approach like a debounce mechanism.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d04d47a and ba36501.

📒 Files selected for processing (2)
  • src/Utils/cameraPermissionHandler.ts (1 hunks)
  • src/components/Common/AvatarEditModal.tsx (2 hunks)
🔇 Additional comments (3)
src/components/Common/AvatarEditModal.tsx (2)

26-26: Import looks good.

Clean addition of the import for the centralized camera permission handler.


396-399: Great refactoring of camera error handling.

The previously implicit error handling has been improved by delegating to a centralized function. This approach will make it easier to maintain consistent camera permission handling across the application.

src/Utils/cameraPermissionHandler.ts (1)

8-24: Consider creating a React hook instead

As suggested in previous comments, this utility might be better implemented as a React hook for more idiomatic React code.

A hook would allow proper use of the useTranslation hook and manage state properly within React's lifecycle. Consider refactoring to a hook like:

import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

export function useMediaDevicePermissions() {
  const { t } = useTranslation();
  
  const requestCameraPermission = useCallback(async (
    cameraFacingMode: string,
    onPermissionDenied: () => void,
  ) => {
    try {
      await navigator.mediaDevices.getUserMedia({
        video: { facingMode: cameraFacingMode },
      });
      // Permission granted
      return true;
    } catch (error) {
      if (error instanceof DOMException && 
          (error.name === "NotAllowedError" || error.name === "PermissionDeniedError")) {
        toast.warning(t("camera_permission_denied"));
      } else {
        toast.error(t("camera_error_occurred"));
      }
      
      onPermissionDenied();
      return false;
    }
  }, [t]);
  
  return { requestCameraPermission };
}

This would be used in components like:

const { requestCameraPermission } = useMediaDevicePermissions();

// Then in your component:
onUserMediaError={async () => {
  await requestCameraPermission("user", () => setIsCameraOpen(false));
}}

cameraFacingMode: string,
onPermissionDenied: () => void,
) => {
toastShown = false;
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

Reset state inside the function creates race conditions

Resetting toastShown at the beginning of each function call can create race conditions if the function is called multiple times in quick succession.

This line should be removed in favor of the timestamp-based approach suggested in the earlier comment.

Comment on lines 8 to 24
export const handleCameraPermission = async (
cameraFacingMode: string,
onPermissionDenied: () => void,
) => {
toastShown = false;
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: cameraFacingMode },
});
} catch (_error) {
if (!toastShown) {
toastShown = true;
toast.warning(t("camera_permission_denied"));
}
onPermissionDenied();
}
};
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

Implement more specific error handling and fix global state issues

The current implementation has several issues:

  1. It uses a global variable for tracking toast state
  2. It doesn't distinguish between different types of errors (permission denied vs. device not found)
  3. It resets the global state at the beginning of each call

Here's a more robust implementation:

-export const handleCameraPermission = async (
-  cameraFacingMode: string,
-  onPermissionDenied: () => void,
-) => {
-  toastShown = false;
-  try {
-    await navigator.mediaDevices.getUserMedia({
-      video: { facingMode: cameraFacingMode },
-    });
-  } catch (_error) {
-    if (!toastShown) {
-      toastShown = true;
-      toast.warning(t("camera_permission_denied"));
-    }
-    onPermissionDenied();
-  }
-};
+// Track toast display with a timestamp-based approach instead of a boolean
+let lastToastTime = 0;
+const TOAST_COOLDOWN_MS = 3000; // Only show toast once every 3 seconds
+
+export const handleCameraPermission = async (
+  cameraFacingMode: string,
+  onPermissionDenied: () => void,
+) => {
+  try {
+    await navigator.mediaDevices.getUserMedia({
+      video: { facingMode: cameraFacingMode },
+    });
+    // Permission granted, do nothing
+  } catch (error) {
+    // Show toast only if we haven't shown one recently
+    const now = Date.now();
+    if (now - lastToastTime > TOAST_COOLDOWN_MS) {
+      lastToastTime = now;
+      
+      // Different message based on error type
+      if (error instanceof DOMException && 
+          (error.name === "NotAllowedError" || error.name === "PermissionDeniedError")) {
+        toast.warning(t("camera_permission_denied"));
+      } else {
+        toast.error(t("camera_error_occurred"));
+      }
+    }
+    
+    // Always call the callback
+    onPermissionDenied();
+  }
+};

Note: You'll need to add the camera_error_occurred translation key to your i18n resources.

📝 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
export const handleCameraPermission = async (
cameraFacingMode: string,
onPermissionDenied: () => void,
) => {
toastShown = false;
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: cameraFacingMode },
});
} catch (_error) {
if (!toastShown) {
toastShown = true;
toast.warning(t("camera_permission_denied"));
}
onPermissionDenied();
}
};
// Track toast display with a timestamp-based approach instead of a boolean
let lastToastTime = 0;
const TOAST_COOLDOWN_MS = 3000; // Only show toast once every 3 seconds
export const handleCameraPermission = async (
cameraFacingMode: string,
onPermissionDenied: () => void,
) => {
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: cameraFacingMode },
});
// Permission granted, do nothing
} catch (error) {
// Show toast only if we haven't shown one recently
const now = Date.now();
if (now - lastToastTime > TOAST_COOLDOWN_MS) {
lastToastTime = now;
// Different message based on error type
if (
error instanceof DOMException &&
(error.name === "NotAllowedError" || error.name === "PermissionDeniedError")
) {
toast.warning(t("camera_permission_denied"));
} else {
toast.error(t("camera_error_occurred"));
}
}
// Always call the callback
onPermissionDenied();
}
};

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

♻️ Duplicate comments (2)
src/Utils/cameraPermissionHandler.ts (2)

7-27: 🛠️ Refactor suggestion

Fix potential race conditions and improve error handling.

The current implementation has several issues:

  1. Resetting toastShown at the beginning of each call can create race conditions
  2. The error handling doesn't distinguish between different types of errors
  3. The dependency array includes toastShown which could cause unnecessary recreation
  const requestPermission = useCallback(
    async (device: "camera", cameraFacingMode: string = "user") => {
      try {
-        setToastShown(false); 
        const constraints =
          device === "camera"
            ? { video: { facingMode: cameraFacingMode } }
            : { audio: true };

        await navigator.mediaDevices.getUserMedia(constraints);
        return true;
      } catch (_error) {
        if (!toastShown) {
          setToastShown(true);
-          toast.warning(`${device} permission denied`);
+          // Different message based on error type
+          if (_error instanceof DOMException && 
+              (_error.name === "NotAllowedError" || _error.name === "PermissionDeniedError")) {
+            toast.warning(`${device} permission denied`);
+          } else {
+            toast.error(`Error accessing ${device}`);
+          }
        }
        return false; // Permission denied
      }
    },
-    [toastShown],
+    [],
  );
🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)


4-6: 🛠️ Refactor suggestion

Convert to proper React custom hook.

React hooks should be named with the 'use' prefix according to React conventions. This was also mentioned in previous review comments.

-export const handleCameraPermission = () => {
+export const useMediaDevicePermissions = () => {
  const [toastShown, setToastShown] = useState(false);
🧹 Nitpick comments (3)
src/Utils/cameraPermissionHandler.ts (3)

10-10: Remove trailing whitespace.

There's an extra space at the end of this line.

-        setToastShown(false); 
+        setToastShown(false);
🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)


1-30: Enhance internationalization support for error messages.

The current implementation uses string interpolation for error messages, which might not work well with translation systems. Consider using translation keys instead.

import { useCallback, useState } from "react";
import { toast } from "sonner";
+import { t } from "i18next";

// [...rest of the code...]

-          toast.warning(`${device} permission denied`);
+          toast.warning(device === "camera" ? t("camera_permission_denied") : t("audio_permission_denied"));
🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)


8-25: Expand device type support with proper TypeScript typing.

The current implementation accepts only "camera" but has logic for audio devices too. Consider improving the type definition.

-    async (device: "camera", cameraFacingMode: string = "user") => {
+    async (device: "camera" | "audio" | "microphone", cameraFacingMode: string = "user") => {
      try {
        setToastShown(false);
        const constraints =
-          device === "camera"
+          device === "camera"
            ? { video: { facingMode: cameraFacingMode } }
-            : { audio: true };
+            : { audio: true };
🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba36501 and 51a437d.

📒 Files selected for processing (3)
  • src/Utils/cameraPermissionHandler.ts (1 hunks)
  • src/components/Common/AvatarEditModal.tsx (3 hunks)
  • src/components/Files/CameraCaptureDialog.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Common/AvatarEditModal.tsx
🧰 Additional context used
🪛 ESLint
src/Utils/cameraPermissionHandler.ts

[error] 10-10: Delete ·

(prettier/prettier)

🔇 Additional comments (7)
src/components/Files/CameraCaptureDialog.tsx (4)

18-18: Good addition: Importing centralized camera permission handler.

This is a good step toward centralizing camera permission handling across the application.


31-32: Good implementation: Using centralized permission handler and stream state management.

Converting the local variable to state and using the centralized permission handler improves code maintainability and error handling.


49-67: Robust implementation for camera permissions and stream acquisition.

The new implementation correctly:

  1. Checks for camera permission first
  2. Handles permission denial gracefully by closing the dialog
  3. Only attempts to access the camera if permission is granted
  4. Properly sets the media stream state
  5. Includes appropriate error handling

This is a significant improvement over direct media access.


68-75: Clean stream cleanup in the useEffect.

The cleanup function properly stops all tracks in the stream when the component unmounts or the dialog closes.

src/Utils/cameraPermissionHandler.ts (3)

1-3: Import React hooks and toast library for notification handling.

The imports look good and are necessary for the implemented functionality.


29-30: Return object with the permission request function.

The return statement correctly makes the requestPermission function available to consumers of this hook.


1-30: Consider implementing a timestamp-based approach for toast throttling.

The current boolean-based approach to prevent multiple toasts isn't ideal for handling multiple calls in a short time period. A timestamp-based approach would be more robust.

-export const handleCameraPermission = () => {
-  const [toastShown, setToastShown] = useState(false);
+export const useMediaDevicePermissions = () => {
+  const [lastToastTime, setLastToastTime] = useState(0);
+  const TOAST_COOLDOWN_MS = 3000; // Only show toast once every 3 seconds

  const requestPermission = useCallback(
    async (device: "camera", cameraFacingMode: string = "user") => {
      try {
-        setToastShown(false);
        const constraints =
          device === "camera"
            ? { video: { facingMode: cameraFacingMode } }
            : { audio: true };

        await navigator.mediaDevices.getUserMedia(constraints);
        return true;
      } catch (_error) {
-        if (!toastShown) {
-          setToastShown(true);
+        const now = Date.now();
+        if (now - lastToastTime > TOAST_COOLDOWN_MS) {
+          setLastToastTime(now);
          toast.warning(`${device} permission denied`);
        }
        return false; // Permission denied
      }
    },
-    [toastShown],
+    [lastToastTime],
  );

  return { requestPermission };
};
🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)

Comment on lines 1 to 30
import { useCallback, useState } from "react";
import { toast } from "sonner";

export const handleCameraPermission = () => {
const [toastShown, setToastShown] = useState(false);

const requestPermission = useCallback(
async (device: "camera", cameraFacingMode: string = "user") => {
try {
setToastShown(false);
const constraints =
device === "camera"
? { video: { facingMode: cameraFacingMode } }
: { audio: true };

await navigator.mediaDevices.getUserMedia(constraints);
return true;
} catch (_error) {
if (!toastShown) {
setToastShown(true);
toast.warning(`${device} permission denied`);
}
return false; // Permission denied
}
},
[toastShown],
);

return { requestPermission };
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify this utility is used consistently across the codebase.

Based on PR objectives, this centralized function should be applied in other areas of the codebase where camera functionality is utilized.


🏁 Script executed:

#!/bin/bash
# Search for any direct calls to navigator.mediaDevices.getUserMedia in the codebase
# that could be replaced with this centralized handler

echo "Finding potential locations for applying centralized camera permission handling:"
rg -A 3 -B 3 "navigator\.mediaDevices\.getUserMedia" --type tsx --type ts | grep -v "cameraPermissionHandler"

echo -e "\nPlaces where the camera permission handler is already used:"
rg -A 1 "handleCameraPermission" --type tsx --type ts

Length of output: 525


Action: Re-run the Search for Camera Permission Usages

It appears the previous search command failed due to the unrecognized file type “tsx.” To verify if the centralized camera permission utility is applied consistently across the codebase, please re-run the updated search using a glob pattern for both .ts and .tsx files.

Once you have the output from this script, please verify that:

  • There are no remaining direct calls to navigator.mediaDevices.getUserMedia that bypass the centralized handler.
  • The handleCameraPermission function is being used wherever camera functionality is expected.

🏁 Script executed:

#!/bin/bash
echo "Finding potential locations for applying centralized camera permission handling in .ts and .tsx files:"
rg -g "*.{ts,tsx}" -A 3 -B 3 "navigator\.mediaDevices\.getUserMedia" | grep -v "cameraPermissionHandler"

echo -e "\nFinding usage of handleCameraPermission in .ts and .tsx files:"
rg -g "*.{ts,tsx}" -A 1 "handleCameraPermission"

Length of output: 2322


Action Required: Ensure Consistent Usage of Centralized Camera Permission Handler

It has been detected that while the centralized handler is correctly used in parts of the codebase (e.g., in AvatarEditModal.tsx), there are still direct calls to navigator.mediaDevices.getUserMedia in at least one location. For example, in src/components/Files/CameraCaptureDialog.tsx, a direct call is made instead of utilizing the centralized handleCameraPermission utility. Please update the camera access logic in this file (and any other similar cases) so that all camera-related getUserMedia calls are funneled through the centralized handler.

  • src/components/Files/CameraCaptureDialog.tsx
    • Replace the direct call to navigator.mediaDevices.getUserMedia({ video: { facingMode: cameraFacingMode } }) with an invocation of the handler’s requestPermission function.

Review and apply this refactoring consistently across the codebase wherever camera functionality is implemented.

🧰 Tools
🪛 ESLint

[error] 10-10: Delete ·

(prettier/prettier)

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.

Bug : Camera Permission Error
2 participants