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

Issue #229206 feat: For fill in the blanks mechanic,answer option sho… #187

Conversation

ajinkyapandetekdi
Copy link
Collaborator

@ajinkyapandetekdi ajinkyapandetekdi commented Oct 24, 2024

…uld be placed at blank space. PFA

Summary by CodeRabbit

  • New Features

    • Enhanced audio playback controls, allowing for better management of student recordings.
    • Improved user interaction with a new cursor style for the audio playback button.
  • Bug Fixes

    • Refined error handling for audio loading failures, ensuring smoother playback experience.
  • Improvements

    • Streamlined logic for word selection and rendering in the Mechanics component.
    • Adjusted layout responsiveness for better display across various screen sizes.

Copy link

sonarcloud bot commented Oct 24, 2024

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes in this pull request involve significant modifications to the Mechanics3 component, including the removal of useEffect hooks related to word selection and audio initialization. The getSimilarWords function was streamlined, and the getEnableButton function was removed in favor of using the enableNext prop directly. Additionally, layout adjustments were made for the Grid component, and the handling of the answer display was updated for better flexibility. The AudioCompare and VoiceAnalyser components also received updates focused on user interaction and improved audio playback management.

Changes

File Change Summary
src/components/Practice/Mechanics3.jsx - Removed two useEffect hooks for word selection and audio initialization.
- Streamlined getSimilarWords function.
- Removed getEnableButton function, using enableNext prop directly.
- Adjusted Grid layout positioning.
- Updated answer display handling using regex.
src/utils/AudioCompare.js - Added cursor style to the audio playback button.
- No changes to core logic or functionality.
src/utils/VoiceAnalyser.js - Introduced temp_Student_audio state variable.
- Updated playAudio function for conditional playback.
- Refined playRecordedAudio function with improved error handling.
- Added useEffect hooks for audio playback management.

Possibly related PRs


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.

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

@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: 5

🧹 Outside diff range and nitpick comments (4)
src/utils/AudioCompare.js (3)

152-152: LGTM! The cursor style improves user interaction feedback.

The addition of cursor: "pointer" enhances the user experience by providing visual feedback for clickable elements.

Consider also adding appropriate ARIA attributes to improve accessibility:

 <Box
   sx={{
     marginLeft: props.isShowCase ? "" : "35px",
     cursor: "pointer",
   }}
+  role="button"
+  aria-label="Play recorded audio"
 >

Line range hint 154-170: Consider enhancing error handling for audio playback.

The audio playback implementation could benefit from proper error handling to manage scenarios where audio playback fails.

Consider wrapping the playback logic with error handling:

const handlePlayback = async (shouldPlay) => {
  try {
    await props.playRecordedAudio(shouldPlay);
  } catch (error) {
    console.error('Audio playback failed:', error);
    // Handle playback error (e.g., show user feedback)
  }
};

Line range hint 11-227: Consider breaking down the complex conditional rendering.

The component has complex nested conditional rendering that could be simplified for better maintainability.

Consider extracting the recording and playback controls into separate components:

  • RecordingControls - for handling the recording state UI
  • PlaybackControls - for managing the playback UI
  • AudioVisualizer - for the visualization component

This would make the code more maintainable and easier to test.

src/components/Practice/Mechanics3.jsx (1)

246-247: LGTM: Improved responsive layout

Switching to relative positioning improves layout stability across different screen sizes. Consider using CSS Grid or Flexbox for even better responsiveness.

  position: {
-   lg: "relative", // Change as needed for large screens
-   xl: "relative", // Change as needed for extra-large screens
+   lg: "relative",
+   xl: "relative",
  },
  left: {
-   lg: "0px",
-   xl: "0px",
+   lg: 0,
+   xl: 0,
  },

Also applies to: 253-254

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 19df211 and 072b332.

📒 Files selected for processing (3)
  • src/components/Practice/Mechanics3.jsx (8 hunks)
  • src/utils/AudioCompare.js (1 hunks)
  • src/utils/VoiceAnalyser.js (4 hunks)
🔇 Additional comments (4)
src/components/Practice/Mechanics3.jsx (3)

129-129: LGTM: Simplified enableNext handling

Direct prop passing improves code clarity by removing unnecessary abstraction.


264-264: LGTM: Responsive image sizing

Using clamp for image height provides smooth scaling while maintaining boundaries. Good choice of min/max values.


398-398: Verify VoiceAnalyser behavior with enableNext

Please verify that the VoiceAnalyser component correctly handles the enableNext state transitions.

✅ Verification successful

Let me try a different approach to verify the VoiceAnalyser component implementation and usage.

This will help us understand:

  1. How VoiceAnalyser is defined
  2. Where and how enableNext prop is used
  3. Location of the VoiceAnalyser component file

Let me check the actual implementation of VoiceAnalyser to understand how it handles props.


Based on the code analysis, I can now provide a final response:

VoiceAnalyser correctly handles enableNext prop

The VoiceAnalyser component properly implements the enableNext prop with the following behaviors:

  • Clears recorded audio when enableNext becomes false (useEffect on line 47)
  • Controls the visibility of the next button based on enableNext prop (line 398)
  • Properly declares enableNext as a required boolean prop in PropTypes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for VoiceAnalyser usage and prop handling
ast-grep --pattern 'const VoiceAnalyser = ({ enableNext, $$$, showOnlyListen }) => {
  $$$
}'

Length of output: 95


Script:

#!/bin/bash
# Search for VoiceAnalyser component definition
ast-grep --pattern 'const VoiceAnalyser = $_'

# Search for VoiceAnalyser usage with enableNext prop
rg "VoiceAnalyser.*enableNext" -A 2

# Search for files containing VoiceAnalyser
fd VoiceAnalyser

Length of output: 131


Script:

#!/bin/bash
# Check the content of VoiceAnalyser component
cat src/utils/VoiceAnalyser.js

# Search for any references to enableNext within VoiceAnalyser.js
rg "enableNext" src/utils/VoiceAnalyser.js -A 2

# Look for VoiceAnalyser imports and usage
rg "import.*VoiceAnalyser" -A 2

Length of output: 25860

src/utils/VoiceAnalyser.js (1)

71-71: LGTM: New state variable for student audio management.

The addition of temp_Student_audio state improves the separation of concerns between teacher and student audio playback.

@@ -402,7 +290,7 @@ const Mechanics2 = ({
>
{answer?.text !== "" ? (
<>
{parentWords?.split("_____")[0]} {/* Before the blank */}
{parentWords?.split(/_+/)[0]}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling multiple blanks

The current split implementation assumes a single blank. Consider enhancing it to support multiple blanks in the future.

- {parentWords?.split(/_+/)[0]}
- {parentWords?.split(/_+/)[1]}
+ {parentWords?.split(/(_+)/).map((part, index) => {
+   if (part.match(/^_+$/)) {
+     return answer?.text || part;
+   }
+   return part;
+ })}

Also applies to: 313-313

Comment on lines +709 to +732
{!loader && (
<Box sx={{ display: "flex", justifyContent: "center", mt: 4 }}>
{props.enableNext && (
<Box
sx={{ cursor: "pointer" }}
onClick={() => {
if (
props.pageName === "wordsorimage" ||
props.pageName === "m5"
) {
props.updateStoredData(recordedAudio, isMatching);
}
if (props.setIsNextButtonCalled) {
props.setIsNextButtonCalled(true);
} else {
props.handleNext();
}
}}
>
<NextButtonRound />
</Box>
)}
</Box>
)}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider extracting Next button logic to a separate component.

The Next button rendering logic contains complex conditions and could benefit from being extracted into a dedicated component for better maintainability.

Create a new component:

// NextButton.js
const NextButton = ({ 
  loader,
  enableNext,
  pageName,
  updateStoredData,
  recordedAudio,
  isMatching,
  setIsNextButtonCalled,
  handleNext 
}) => {
  if (loader) return null;
  
  const handleClick = () => {
    if (pageName === "wordsorimage" || pageName === "m5") {
      updateStoredData(recordedAudio, isMatching);
    }
    if (setIsNextButtonCalled) {
      setIsNextButtonCalled(true);
    } else {
      handleNext();
    }
  };

  return enableNext ? (
    <Box sx={{ display: "flex", justifyContent: "center", mt: 4 }}>
      <Box sx={{ cursor: "pointer" }} onClick={handleClick}>
        <NextButtonRound />
      </Box>
    </Box>
  ) : null;
};

Then simplify the render:

-{!loader && (
-  <Box sx={{ display: "flex", justifyContent: "center", mt: 4 }}>
-    {props.enableNext && (
-      <Box
-        sx={{ cursor: "pointer" }}
-        onClick={() => {
-          if (
-            props.pageName === "wordsorimage" ||
-            props.pageName === "m5"
-          ) {
-            props.updateStoredData(recordedAudio, isMatching);
-          }
-          if (props.setIsNextButtonCalled) {
-            props.setIsNextButtonCalled(true);
-          } else {
-            props.handleNext();
-          }
-        }}
-      >
-        <NextButtonRound />
-      </Box>
-    )}
-  </Box>
-)}
+<NextButton
+  loader={loader}
+  enableNext={props.enableNext}
+  pageName={props.pageName}
+  updateStoredData={props.updateStoredData}
+  recordedAudio={recordedAudio}
+  isMatching={isMatching}
+  setIsNextButtonCalled={props.setIsNextButtonCalled}
+  handleNext={props.handleNext}
+/>

Comment on lines +111 to +115
if (val) {
audio.play();
} else {
audio.pause();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider adding error handling for audio play/pause operations.

While the code handles loading errors, it should also handle play/pause operation failures.

Apply this diff to add error handling:

 if (val) {
-  audio.play();
+  audio.play().catch(error => {
+    console.error("Failed to play audio:", error);
+    setPauseAudio(false);
+    alert("Failed to play the audio. Please try again.");
+  });
 } else {
-  audio.pause();
+  try {
+    audio.pause();
+  } catch (error) {
+    console.error("Failed to pause audio:", error);
+  }
 }
📝 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 (val) {
audio.play();
} else {
audio.pause();
}
if (val) {
audio.play().catch(error => {
console.error("Failed to play audio:", error);
setPauseAudio(false);
alert("Failed to play the audio. Please try again.");
});
} else {
try {
audio.pause();
} catch (error) {
console.error("Failed to pause audio:", error);
}
}

Comment on lines +155 to +177
useEffect(() => {
if (temp_Student_audio !== null) {
if (!isStudentAudioPlaying) {
temp_Student_audio.pause();
props.setVoiceAnimate(false);
} else {
temp_Student_audio.play();
props.setVoiceAnimate(true);
}
temp_Student_audio.onended = function () {
setPauseAudio(false);
props.setVoiceAnimate(false);
};
temp_Student_audio.addEventListener("ended", () =>
setIsStudentAudioPlaying(false)
);
}
return () => {
if (temp_Student_audio !== null) {
temp_Student_audio.pause();
}
};
}, [temp_Student_audio]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve event listener cleanup in useEffect.

The current implementation might lead to memory leaks if the component unmounts while audio is playing.

Apply this diff to improve cleanup:

 useEffect(() => {
   if (temp_Student_audio !== null) {
+    const handleEnded = () => {
+      setPauseAudio(false);
+      props.setVoiceAnimate(false);
+      setIsStudentAudioPlaying(false);
+    };
+
     if (!isStudentAudioPlaying) {
       temp_Student_audio.pause();
       props.setVoiceAnimate(false);
     } else {
       temp_Student_audio.play();
       props.setVoiceAnimate(true);
     }
-    temp_Student_audio.onended = function () {
-      setPauseAudio(false);
-      props.setVoiceAnimate(false);
-    };
-    temp_Student_audio.addEventListener("ended", () =>
-      setIsStudentAudioPlaying(false)
-    );
+    temp_Student_audio.addEventListener("ended", handleEnded);
+
+    return () => {
+      temp_Student_audio.removeEventListener("ended", handleEnded);
+      temp_Student_audio.pause();
+    };
   }
-  return () => {
-    if (temp_Student_audio !== null) {
-      temp_Student_audio.pause();
-    }
-  };
 }, [temp_Student_audio]);
📝 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
useEffect(() => {
if (temp_Student_audio !== null) {
if (!isStudentAudioPlaying) {
temp_Student_audio.pause();
props.setVoiceAnimate(false);
} else {
temp_Student_audio.play();
props.setVoiceAnimate(true);
}
temp_Student_audio.onended = function () {
setPauseAudio(false);
props.setVoiceAnimate(false);
};
temp_Student_audio.addEventListener("ended", () =>
setIsStudentAudioPlaying(false)
);
}
return () => {
if (temp_Student_audio !== null) {
temp_Student_audio.pause();
}
};
}, [temp_Student_audio]);
useEffect(() => {
if (temp_Student_audio !== null) {
const handleEnded = () => {
setPauseAudio(false);
props.setVoiceAnimate(false);
setIsStudentAudioPlaying(false);
};
if (!isStudentAudioPlaying) {
temp_Student_audio.pause();
props.setVoiceAnimate(false);
} else {
temp_Student_audio.play();
props.setVoiceAnimate(true);
}
temp_Student_audio.addEventListener("ended", handleEnded);
return () => {
temp_Student_audio.removeEventListener("ended", handleEnded);
temp_Student_audio.pause();
};
}
}, [temp_Student_audio]);

Comment on lines +135 to +149
audio.addEventListener("canplaythrough", () => {
setIsStudentAudioPlaying(val);
set_temp_Student_audio(audio);
if (val) {
audio.play();
audio.onended = () => setIsStudentAudioPlaying(false);
} else {
audio.pause();
}
});
audio.addEventListener("error", (e) => {
console.error("Audio failed to load", e);
setIsStudentAudioPlaying(false);
}
alert("Failed to load the audio. Please try again.");
});
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 cleanup for audio resources.

The audio element should be properly cleaned up to prevent memory leaks.

Apply this diff to add cleanup:

 const audio = new Audio(recordedAudio);
+let isCleanedUp = false;
+
+const cleanup = () => {
+  if (!isCleanedUp) {
+    audio.removeEventListener("canplaythrough", handler);
+    audio.removeEventListener("error", errorHandler);
+    audio.pause();
+    isCleanedUp = true;
+  }
+};
+
+const handler = () => {
  setIsStudentAudioPlaying(val);
  set_temp_Student_audio(audio);
  if (val) {
    audio.play();
    audio.onended = () => setIsStudentAudioPlaying(false);
  } else {
    audio.pause();
  }
+};
+
+const errorHandler = (e) => {
  console.error("Audio failed to load", e);
  setIsStudentAudioPlaying(false);
  alert("Failed to load the audio. Please try again.");
+  cleanup();
};

-audio.addEventListener("canplaythrough", () => {
-  setIsStudentAudioPlaying(val);
-  set_temp_Student_audio(audio);
-  if (val) {
-    audio.play();
-    audio.onended = () => setIsStudentAudioPlaying(false);
-  } else {
-    audio.pause();
-  }
-});
+audio.addEventListener("canplaythrough", handler);
-audio.addEventListener("error", (e) => {
-  console.error("Audio failed to load", e);
-  setIsStudentAudioPlaying(false);
-  alert("Failed to load the audio. Please try again.");
-});
+audio.addEventListener("error", errorHandler);
+
+return cleanup;
📝 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
audio.addEventListener("canplaythrough", () => {
setIsStudentAudioPlaying(val);
set_temp_Student_audio(audio);
if (val) {
audio.play();
audio.onended = () => setIsStudentAudioPlaying(false);
} else {
audio.pause();
}
});
audio.addEventListener("error", (e) => {
console.error("Audio failed to load", e);
setIsStudentAudioPlaying(false);
}
alert("Failed to load the audio. Please try again.");
});
let isCleanedUp = false;
const cleanup = () => {
if (!isCleanedUp) {
audio.removeEventListener("canplaythrough", handler);
audio.removeEventListener("error", errorHandler);
audio.pause();
isCleanedUp = true;
}
};
const handler = () => {
setIsStudentAudioPlaying(val);
set_temp_Student_audio(audio);
if (val) {
audio.play();
audio.onended = () => setIsStudentAudioPlaying(false);
} else {
audio.pause();
}
};
const errorHandler = (e) => {
console.error("Audio failed to load", e);
setIsStudentAudioPlaying(false);
alert("Failed to load the audio. Please try again.");
cleanup();
};
audio.addEventListener("canplaythrough", handler);
audio.addEventListener("error", errorHandler);
return cleanup;

@gouravmore gouravmore merged commit 7b2d0cb into Sunbird-ALL:all-1.2-tn-dev Oct 25, 2024
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 14, 2024
bharathrams pushed a commit to Bhashabyasa/nd-all-learner-ai-app that referenced this pull request Nov 25, 2024
…anks-all-dev-tn

Issue #229206 feat: For fill in the blanks mechanic,answer option sho…
bharathrams pushed a commit to Bhashabyasa/nd-all-learner-ai-app that referenced this pull request Dec 2, 2024
…anks-all-dev-tn

Issue #229206 feat: For fill in the blanks mechanic,answer option sho…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants