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: region-clicked event and seek issue inside region (#3911, #3804) #3945

Merged

Conversation

Olejqua
Copy link
Contributor

@Olejqua Olejqua commented Nov 29, 2024

Short description

Added parentElement check in virtualAppend method to prevent redundant DOM operations that were breaking click event handling during zoomed playback.

Resolves #3911
Resolves #3804

This PR resolves two related issues with region-clicked events and seeking inside regions in WaveSurfer.js:

  1. Issue region-clicked Event Issue on Regions in WaveSurfer Zoomed State for Chrome and Safari #3911:
    The region-clicked event was not firing on Chrome and Safari when the zoom slider was used. This behavior was inconsistent across browsers, as Firefox worked as expected.

  2. Issue [Regions] Clicking inside region does not seek #3804:
    Since version 7.8.2, clicking inside a region no longer seeks the audio position correctly on Chrome and Edge. The expected behavior (as seen in Firefox) is that clicking inside a region seeks the audio to the clicked position.

Implementation details

Modified regions.ts virtualAppend method to check element's DOM state before append/remove operations:

if (isVisible && !element.parentElement) {
    container.appendChild(element)
} else if (!isVisible && element.parentElement) {
    element.remove()
}

Copy link

coderabbitai bot commented Nov 29, 2024

Walkthrough

The pull request modifies the virtualAppend method in the RegionsPlugin class to enhance the logic for appending and removing region elements based on their visibility and parent status. It also updates the onInit method to include error handling for uninitialized wavesurfer instances. These changes aim to improve the robustness of region management by preventing unnecessary DOM manipulations and ensuring proper initialization.

Changes

File Change Summary
src/plugins/regions.ts - Modified virtualAppend method to refine conditions for appending and removing region elements.
- Updated onInit method to throw an error if the wavesurfer instance is not initialized.
- Updated method signature and type alias for clarity, though no actual signature change was made.

Possibly related PRs

  • FIX: clearRegions #3909: The changes in the clearRegions method of the RegionsPlugin class are related to the overall management of regions, which is also a focus of the modifications in the virtualAppend method in the main PR. Both PRs involve refining how regions are handled within the same class.

Suggested reviewers

  • katspaugh

Poem

🐇 In the realm of regions, we hop and play,
With logic refined, we brighten the day.
No more redundance, just clean, tidy space,
Error checks added, we quicken the pace.
So here’s to the changes, let’s give them a cheer,
For a plugin that’s better, let’s all persevere! 🌟


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

@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/plugins/regions.ts (2)

530-532: Consider adding synchronization for rapid zoom/scroll operations.

The current implementation might be susceptible to race conditions during rapid zoom/scroll operations. Consider:

  1. Using a debounce mechanism for the visibility checks
  2. Adding a state flag to track pending DOM operations
  3. Using requestAnimationFrame instead of setTimeout for better synchronization with the browser's render cycle

Example implementation:

+private pendingDOMOperation = false;
+private debouncedRenderIfVisible = debounce((container, element) => {
   if (!this.wavesurfer) return
   const clientWidth = this.wavesurfer.getWidth()
   const scrollLeft = this.wavesurfer.getScroll()
   const scrollWidth = container.clientWidth
   const duration = this.wavesurfer.getDuration()
   const start = Math.round((region.start / duration) * scrollWidth)
   const width = Math.round(((region.end - region.start) / duration) * scrollWidth) || 1
   const isVisible = start + width > scrollLeft && start < scrollLeft + clientWidth

   if (this.pendingDOMOperation) return
   this.pendingDOMOperation = true
   
   requestAnimationFrame(() => {
     if (isVisible && !element.parentElement) {
       container.appendChild(element)
     } else if (!isVisible && element.parentElement) {
       element.remove()
     }
     this.pendingDOMOperation = false
   })
}, 16); // ~60fps

530-532: Enhance error handling for DOM operations.

While the core fix is solid, consider adding error handling to make the code more robust:

  1. Try-catch blocks around DOM operations
  2. Logging for debugging browser-specific issues
  3. Cleanup mechanism for error cases

Example implementation:

-if (isVisible && !element.parentElement) {
-  container.appendChild(element)
-} else if (!isVisible && element.parentElement) {
-  element.remove()
-}
+try {
+  if (isVisible && !element.parentElement) {
+    container.appendChild(element)
+    console.debug(`Region ${region.id} appended to DOM`)
+  } else if (!isVisible && element.parentElement) {
+    element.remove()
+    console.debug(`Region ${region.id} removed from DOM`)
+  }
+} catch (error) {
+  console.error(`Failed to update region ${region.id} DOM state:`, error)
+  // Attempt cleanup
+  if (element.parentElement === container) {
+    try {
+      element.remove()
+    } catch (cleanupError) {
+      console.error('Cleanup failed:', cleanupError)
+    }
+  }
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e7ceaf9 and c2ef4b9.

📒 Files selected for processing (1)
  • src/plugins/regions.ts (1 hunks)
🔇 Additional comments (1)
src/plugins/regions.ts (1)

530-532: Improved DOM manipulation logic addresses browser-specific issues.

The changes effectively prevent redundant DOM operations by:

  1. Only appending if the element is visible AND doesn't have a parent
  2. Only removing if the element is not visible AND has a parent

This should resolve the browser-specific issues with region-clicked events and seeking by ensuring consistent DOM state management.

Let's verify the DOM manipulation logic:

✅ Verification successful

DOM manipulation patterns are consistent across the codebase

The verification shows that while there are multiple instances of appendChild and remove operations throughout the codebase, the specific case in regions.ts is unique because it handles dynamic visibility-based DOM manipulation. Other instances are primarily one-time operations for initialization or cleanup.

The parent element check is specifically needed in regions.ts because:

  1. It's the only place where elements are repeatedly added/removed based on visibility
  2. Other DOM operations in the codebase are straightforward mount/unmount scenarios
  3. No other components use similar virtual append logic that could suffer from the same browser-specific issues
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar DOM manipulation patterns in the codebase
# that might need the same fix for consistency.

# Search for appendChild/remove calls that might need parent element checks
rg -A 2 "appendChild|remove\(\)" --type ts

# Search for element visibility checks that might need parent element checks
ast-grep --pattern 'if ($visible) {
  $element.$method($$$)
}'

Length of output: 4879

Copy link
Owner

@katspaugh katspaugh left a comment

Choose a reason for hiding this comment

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

Thanks!

@katspaugh katspaugh merged commit 24466fa into katspaugh:main Dec 2, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants