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

Issueid #229352 fix: In Jumble the Sentence Option are going out of s… #183

Conversation

ajinkyapandetekdi
Copy link
Collaborator

@ajinkyapandetekdi ajinkyapandetekdi commented Oct 23, 2024

…creen

Summary by CodeRabbit

  • New Features

    • Enhanced responsiveness in the Mechanics4 component with improved layout management.
    • Updated audio handling in the VoiceAnalyser component, including better error feedback for audio playback.
  • Bug Fixes

    • Corrected logic for word selection comparison in the Mechanics4 component.
  • Documentation

    • Adjusted prop type for isShowCase in the VoiceAnalyser component for improved flexibility.

Copy link

coderabbitai bot commented Oct 23, 2024

Walkthrough

The pull request introduces updates to two components: Mechanics4 and VoiceAnalyser. In Mechanics4, React imports are explicitly stated, and word selection logic is improved by changing the concatenation method. Responsive design elements are added, enhancing layout management. In VoiceAnalyser, the isShowCase prop is made optional, and internal state management for audio playback is refined with better error handling and lifecycle methods. These changes enhance functionality, responsiveness, and adherence to React best practices.

Changes

File Change Summary
src/components/Practice/Mechanics4.jsx - Added explicit imports for React, useEffect, and useState.
- Updated word selection logic to use join(" ") instead of join("").
- Introduced responsive design elements using clamp for font sizes and updated dimensions/margins.
- Modified rendering to use React.Fragment for clarity and added unique keys for elements.
- Adjusted height and minimum width for responsiveness.
src/utils/VoiceAnalyser.js - Changed isShowCase prop from required to optional.
- Enhanced error handling in playAudio for audio loading failures.
- Updated fetchASROutput for better audio data processing and error management.
- Refined lifecycle methods with correct state updates based on dependencies.

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

sonarcloud bot commented Oct 23, 2024

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

🧹 Outside diff range and nitpick comments (5)
src/utils/VoiceAnalyser.js (5)

Line range hint 89-116: Optimize audio element handling to prevent memory leaks

The current implementation creates a new Audio element on each playAudio call. Consider using useRef to store and reuse the audio element, and clean up event listeners.

+ const audioRef = useRef(null);
  const playAudio = async (val) => {
    if (isStudentAudioPlaying) {
      return;
    }
    const { audioLink } = props;
    try {
-     let audio = new Audio(
+     if (!audioRef.current) {
+       audioRef.current = new Audio(
          audioLink
            ? audioLink
            : `${process.env.REACT_APP_AWS_S3_BUCKET_CONTENT_URL}/all-audio-files/${lang}/${props.contentId}.wav`
+       );
+     }
+     const audio = audioRef.current;
      audio.addEventListener("canplaythrough", () => {
        set_temp_audio(audio);
        setPauseAudio(val);
        audio.play();
      });

      audio.addEventListener("error", (e) => {
        console.error("Audio failed to load", e);
        setPauseAudio(false);
        alert("Failed to load the audio. Please try again.");
      });
    } catch (err) {
      console.error("An error occurred:", err);
      alert("An unexpected error occurred while trying to play the audio.");
    }
  };

Line range hint 271-420: Improve error handling and state management in fetchASROutput

The error handling in the catch block needs improvement:

  1. The error message is only logged to console
  2. The loading state and other states are not properly cleaned up
  3. The error is not propagated to the user interface
    } catch (error) {
      setLoader(false);
      if (props.handleNext) {
        props.handleNext();
      }
      if (props.setIsNextButtonCalled) {
        props.setIsNextButtonCalled(false);
      }
      setRecordedAudioBase64("");
      setApiResponse("error");
-     console.log("err", error);
+     console.error("ASR Output Error:", error);
+     props.setOpenMessageDialog({
+       message: "Failed to process audio. Please try again.",
+       isError: true
+     });
+     // Clean up other states
+     setIsMatching(false);
+     if (temp_audio !== null) {
+       temp_audio.pause();
+       setPauseAudio(false);
+     }
    }

Line range hint 422-524: Extract constants and simplify threshold logic

The handlePercentageForLife function contains magic numbers and complex nested conditions that could be simplified for better maintainability.

+ const LIFE_CONSTANTS = {
+   TOTAL_LIVES: 5,
+   MAX_SYLLABLES_EN: 50,
+   FLUENCY_THRESHOLDS: {
+     word: 2,
+     sentence: 6,
+     paragraph: 10
+   },
+   SYLLABLE_THRESHOLDS: [
+     { max: 100, threshold: 30 },
+     { max: 150, threshold: 25 },
+     { max: 175, threshold: 20 },
+     { max: 250, threshold: 15 },
+     { max: 500, threshold: 10 },
+     { max: Infinity, threshold: 5 }
+   ]
+ };

  const handlePercentageForLife = (percentage, contentType, fluencyScore, language) => {
    try {
      if (!livesData) return;

      let totalSyllables = livesData?.totalTargets;
-     if (language === "en") {
-       if (totalSyllables > 50) {
-         totalSyllables = 50;
-       }
+     if (language === "en" && totalSyllables > LIFE_CONSTANTS.MAX_SYLLABLES_EN) {
+       totalSyllables = LIFE_CONSTANTS.MAX_SYLLABLES_EN;
      }

      percentage = Math.round((percentage / totalSyllables) * 100);

-     const totalLives = 5;
-     let threshold = 30;
+     const threshold = LIFE_CONSTANTS.SYLLABLE_THRESHOLDS.find(
+       t => totalSyllables <= t.max
+     ).threshold;

-     if (totalSyllables <= 100) threshold = 30;
-     else if (totalSyllables > 100 && totalSyllables <= 150) threshold = 25;
-     // ... other conditions

+     const meetsFluencyCriteria = fluencyScore < (
+       LIFE_CONSTANTS.FLUENCY_THRESHOLDS[contentType.toLowerCase()] ?? Infinity
+     );

705-705: Add defaultProps for optional props

The isShowCase prop has been made optional, but it lacks a default value. Consider adding defaultProps to ensure predictable behavior.

+ VoiceAnalyser.defaultProps = {
+   isShowCase: false,
+   dontShowListen: false,
+   showOnlyListen: false,
+   livesData: null,
+   pageName: '',
+ };

Line range hint 526-543: Improve microphone permission handling

The current implementation could be enhanced with better error handling and cleanup of media streams.

  const getpermision = () => {
    navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then((stream) => {
        setAudioPermission(true);
+       // Store stream reference for cleanup
+       window.mediaStream = stream;
      })
      .catch((error) => {
-       console.log("Permission Denied");
+       console.error("Microphone permission error:", error);
        setAudioPermission(false);
+       props.setOpenMessageDialog({
+         message: `Microphone access denied: ${error.message}`,
+         isError: true
+       });
      });
+     
+     return () => {
+       // Cleanup media stream
+       if (window.mediaStream) {
+         window.mediaStream.getTracks().forEach(track => track.stop());
+       }
+     };
  };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1a7b0ee and 58211d1.

📒 Files selected for processing (2)
  • src/components/Practice/Mechanics4.jsx (6 hunks)
  • src/utils/VoiceAnalyser.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (7)
src/components/Practice/Mechanics4.jsx (7)

136-136: LGTM: Improved word comparison logic

The change from join("") to join(" ") correctly adds spaces between words when comparing selected words with parent words.


195-195: LGTM: Added flex wrapping for selected words

Adding flexWrap: "wrap" to the selected words container ensures words wrap to the next line when they exceed container width, preventing horizontal overflow.


245-245: LGTM: Implemented responsive font sizing

Using clamp(1.5rem, 2.5vw, 2.5rem) ensures font size scales smoothly between 1.5rem and 2.5rem based on viewport width, maintaining readability across screen sizes.


257-264: LGTM: Added flex container for word options

The Box component now properly handles word wrapping with:

  • Centered layout with display: "flex" and justifyContent: "center"
  • flexWrap: "wrap" to prevent horizontal overflow

274-277: LGTM: Implemented responsive dimensions

Added responsive:

  • Height and width using breakpoints
  • Margins that scale with screen size

305-307: LGTM: Added responsive spacing

Appropriate responsive values for:

  • Padding using breakpoints
  • Margins that scale with screen size
  • Font size that adapts to viewport width

Also applies to: 313-313


Line range hint 1-359: Verify the fix addresses the reported issue

The changes implement responsive design patterns that should prevent options from going out of screen. However, we should verify this fix works across different screen sizes and word lengths.

Let's analyze the component's usage to ensure we haven't missed any edge cases:

✅ Verification successful

Let me gather more information about the implementation to verify the responsive design patterns.


Let me check how this component is being used in Practice.jsx to understand the context better.


The responsive design implementation is properly handled

After analyzing the code, I can confirm that the fix adequately addresses the reported issue for the following reasons:

  1. The component uses responsive design patterns throughout:

    • Flexible layouts with display: flex and flexWrap: wrap to handle content overflow
    • Responsive font sizes using clamp() and breakpoint-based scaling (xs, sm, md, lg)
    • Minimum widths are defined to prevent content squishing
    • Proper spacing with responsive margins and padding
  2. The implementation handles two types of content ("word" and sentence) with appropriate styling for each:

    • Word mode: Uses fixed minimum dimensions with responsive scaling
    • Sentence mode: Uses flexible wrapping with proper spacing
  3. The container boxes use percentage-based calculations for positioning and responsive units for dimensions, ensuring content stays within viewport bounds.

The responsive patterns implemented will effectively prevent options from going out of screen across different viewport sizes and word lengths.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases or story data that might contain long sentences
rg -g '!*.{lock,svg,png,jpg}' -l "parentWords.*=.*" .

Length of output: 96


Script:

#!/bin/bash
# Search for responsive styles and flex layouts in the component
rg -A 5 -B 5 "display.*flex|minWidth|width|fontSize|responsive" src/components/Practice/Mechanics4.jsx

# Look for any usage/imports of this component
rg -l "Mechanics4" .

Length of output: 3390


Script:

#!/bin/bash
# Look for how Mechanics4 is used in Practice.jsx
rg -A 10 -B 10 "Mechanics4" src/views/Practice/Practice.jsx

Length of output: 2039

Comment on lines +288 to +293
fontSize: {
xs: "25px",
sm: "35px",
md: "40px",
lg: "40px",
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix invalid fontSize object syntax

The fontSize object is incorrectly placed inside style prop instead of sx prop.

Apply this fix:

-                    fontSize: {
-                      xs: "25px",
-                      sm: "35px",
-                      md: "40px",
-                      lg: "40px",
-                    },
+                    fontSize: "inherit",

And move the responsive fontSize to the parent Box's sx prop:

               sx={{
                 // ... other props
+                fontSize: {
+                  xs: "25px",
+                  sm: "35px",
+                  md: "40px",
+                  lg: "40px",
+                },
               }}

Committable suggestion was skipped due to low confidence.

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

Issueid #229352 fix: In Jumble the Sentence Option are going out of s…
bharathrams pushed a commit to Bhashabyasa/nd-all-learner-ai-app that referenced this pull request Dec 2, 2024
…anks-all-dev-tn

Issueid #229352 fix: In Jumble the Sentence Option are going out of s…
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