Skip to content

Conversation

@saseungmin
Copy link
Member

@saseungmin saseungmin commented Jun 18, 2025

  • add TSDoc documentation
  • add defensive logic for cases without videoId
  • fix issue where seekTo doesn't work properly when paused without interval

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue where playback progress updates were not triggered after seeking, especially when the video was paused.
    • Improved handling of missing or invalid video IDs to prevent potential errors.
  • New Features

    • Playback progress is now accurately reported after seeking, including when the video is paused.
  • Documentation

    • Enhanced documentation and comments for player properties and callback behaviors to improve clarity.
  • Refactor

    • Improved code robustness and progress reporting logic for a more reliable playback experience.

- add TSDoc documentation
- add defensive logic for cases without videoId
- fix issue where seekTo doesn't work properly when paused without interval
@changeset-bot
Copy link

changeset-bot bot commented Jun 18, 2025

🦋 Changeset detected

Latest commit: 2904ac5

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
react-native-youtube-bridge Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Jun 18, 2025

Walkthrough

This update improves the YouTube player integration by ensuring the onProgress callback is triggered after seeking, even when the video is paused. It adds defensive checks for missing video IDs, enhances progress reporting accuracy, and updates documentation for clarity. Type definitions and utility functions are also refined for robustness and maintainability.

Changes

Files/Group Change Summary
.changeset/gentle-houses-attack.md Documents the patch, summarizing fixes for onProgress, defensive programming, and documentation improvements.
src/YoutubePlayer.web.tsx Integrates video ID validation, adds sendProgress callback, and enhances player state handling for progress.
src/hooks/useCreateLocalPlayerHtml.ts Injects sendProgress into HTML, updates seekTo to trigger progress after seeking.
src/hooks/youtubeIframeScripts.ts Adds and exports sendProgress function, updates state change handler for accurate progress reporting.
src/types/youtube.ts Improves TSDoc comments for player variables and props; no type signature changes.
src/utils/validate.ts Updates validateVideoId to accept optional parameter and handle undefined/null safely.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant YoutubePlayer
    participant Iframe
    participant youtubeIframeScripts

    App->>YoutubePlayer: Calls seekTo(newTime)
    YoutubePlayer->>Iframe: Sends seekTo command
    Iframe->>youtubeIframeScripts: Executes seekTo
    youtubeIframeScripts->>Iframe: Seeks to new time
    Note over youtubeIframeScripts: Waits 200ms
    youtubeIframeScripts->>Iframe: Calls sendProgress
    Iframe->>YoutubePlayer: Sends progress update
    YoutubePlayer->>App: Invokes onProgress callback
Loading

Possibly related PRs

Poem

In the warren of code, a hop and a leap,
Progress now reports, no secrets to keep.
Seek while paused? No longer a fright—
The callback will trigger, all data in sight.
With checks and docs, the patch is complete,
A bunny’s delight, this update is sweet!
🐇✨


📜 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 7020e35 and 2904ac5.

📒 Files selected for processing (1)
  • src/YoutubePlayer.web.tsx (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/YoutubePlayer.web.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jun 18, 2025

Deploying react-native-youtube-bridge with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2904ac5
Status: ✅  Deploy successful!
Preview URL: https://1b7afef3.react-native-youtube-bridge.pages.dev
Branch Preview URL: https://fix-call-seek-to-progress.react-native-youtube-bridge.pages.dev

View logs

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

🧹 Nitpick comments (5)
src/utils/validate.ts (1)

1-4: Accepts undefined but not null – consider widening the type for completeness
videoId can now be omitted, which is great. However, callers that might pass null (e.g. values coming straight from JSON) will still be rejected at the TS level even though the runtime implementation gracefully coalesces null to an empty string.

-export const validateVideoId = (videoId?: string): boolean => {
+export const validateVideoId = (videoId?: string | null): boolean => {

Purely a nicety; feel free to skip if you are certain null will never propagate.

.changeset/gentle-houses-attack.md (1)

5-8: Minor wording / punctuation polish for the release note

-fix: where onProgress is not called when seekTo is invoked
+fix: onProgress not emitted when seekTo is invoked
- - add defensive logic for cases without videoId
+ - add defensive logic for missing `videoId`
- - fix issue where seekTo doesn't work properly when paused without interval
+ - fix seekTo when video is paused and no interval is active

Totally optional, but reads a bit smoother.

src/hooks/useCreateLocalPlayerHtml.ts (1)

137-147: Magic 200 ms delay – expose as a constant for easier tuning

A hard-coded timeout is fine today, but if experimentation shows 200 ms is too short/long you’ll need to reopen this template string. Consider declaring a file-level constant so the value can be tweaked in one spot:

-                setTimeout(() => {
-                  sendProgress();
-                }, 200);
+                const SEEK_PROGRESS_DELAY = 200; // ms
+                setTimeout(sendProgress, SEEK_PROGRESS_DELAY);

Very minor, yet improves maintainability.

src/hooks/youtubeIframeScripts.ts (1)

47-68: sendProgress duplicates the serialization logic – DRY up with a shared helper

Both startProgressTracking’s interval body and sendProgress build an identical payload. Extract the common code to a single postProgress() helper and call it from both places:

+  function postProgress() {
+    const currentTime = player.getCurrentTime();
+    const duration    = player.getDuration();
+    const percentage  = duration > 0 ? (currentTime / duration) * 100 : 0;
+    const loadedFraction = player.getVideoLoadedFraction();
+
+    window.ReactNativeWebView.postMessage(JSON.stringify({
+      type: 'progress',
+      currentTime,
+      duration,
+      percentage,
+      loadedFraction,
+    }));
+  }
+
   function sendProgress() {
     if (player && player.getCurrentTime) {
       try {
-        const currentTime = player.getCurrentTime();
-        const duration = player.getDuration();
-        const percentage = duration > 0 ? (currentTime / duration) * 100 : 0;
-        const loadedFraction = player.getVideoLoadedFraction();
-        
-        window.ReactNativeWebView.postMessage(JSON.stringify({
-          type: 'progress',
-          currentTime,
-          duration,
-          percentage,
-          loadedFraction,
-        }));
+        postProgress();
       } catch (error) {
         console.error('Final progress error:', error);
       }
     }
   }

Reduces duplication and keeps any future payload tweaks consistent.

src/YoutubePlayer.web.tsx (1)

194-221: Streamline onStateChange with a switch to avoid repetitive branches

The current cascade of if statements repeats common actions (stopProgressTracking, sendProgress, startProgressTracking), making it harder to see what each state actually does.

-            if (state === PlayerState.ENDED) {
-              stopProgressTracking();
-              sendProgress();
-              return;
-            }
-            ...
-            if (state === PlayerState.CUED) {
-              stopProgressTracking();
-              sendProgress();
-              return;
-            }
-
-            stopProgressTracking();
+            switch (state) {
+              case PlayerState.ENDED:
+              case PlayerState.PAUSED:
+              case PlayerState.CUED:
+                stopProgressTracking();
+                sendProgress();
+                break;
+              case PlayerState.PLAYING:
+              case PlayerState.BUFFERING:
+                startProgressTracking();
+                break;
+              default:
+                stopProgressTracking();
+            }

This reduces cognitive load and prevents future divergence when additional states are introduced.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between df8960e and 7020e35.

📒 Files selected for processing (6)
  • .changeset/gentle-houses-attack.md (1 hunks)
  • src/YoutubePlayer.web.tsx (6 hunks)
  • src/hooks/useCreateLocalPlayerHtml.ts (2 hunks)
  • src/hooks/youtubeIframeScripts.ts (4 hunks)
  • src/types/youtube.ts (2 hunks)
  • src/utils/validate.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/hooks/useCreateLocalPlayerHtml.ts (1)
src/hooks/youtubeIframeScripts.ts (1)
  • youtubeIframeScripts (275-286)
src/YoutubePlayer.web.tsx (2)
src/utils/validate.ts (1)
  • validateVideoId (1-5)
src/index.tsx (1)
  • PlayerState (3-3)
🪛 LanguageTool
.changeset/gentle-houses-attack.md

[style] ~8-~8: Consider using a different verb for a more formal wording.
Context: ...nsive logic for cases without videoId - fix issue where seekTo doesn't work properl...

(FIX_RESOLVE)


[uncategorized] ~8-~8: You might be missing the article “an” here.
Context: ...esn't work properly when paused without interval

(AI_EN_LECTOR_MISSING_DETERMINER_AN)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (3)
src/hooks/useCreateLocalPlayerHtml.ts (1)

75-77: 👍 Injecting sendProgress early keeps it hoisted and callable
Placing the helper just after receiveMessage means it is defined before any consumer (e.g. seekTo) executes – good ordering.

src/hooks/youtubeIframeScripts.ts (1)

100-129: Early returns clean the flow – but the final stopProgressTracking() is now unreachable

Because every handled state path now returns, the unconditional stopProgressTracking(); at line 128 can never run. Either remove it or keep one “catch-all” branch instead of multiple returns to avoid dead code.

src/types/youtube.ts (1)

60-71: Docs perfectly mirror the new behaviour – thanks
The clarifications around onProgress and seekTo remove previous ambiguity. No further action needed.

@saseungmin saseungmin merged commit b4cdf79 into main Jun 18, 2025
6 checks passed
@saseungmin saseungmin deleted the fix/call-seek-to-progress branch June 18, 2025 12:06
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