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

Add BitPageVisibility utility class (#10231) #10241

Merged

Conversation

msynk
Copy link
Member

@msynk msynk commented Mar 14, 2025

closes #10231

Summary by CodeRabbit

  • New Features
    • Enhanced Carousel Behavior: The carousel now automatically pauses autoplay when the page is hidden and resumes once visible, ensuring a smoother viewing experience.
    • Improved Demo Controls: The demonstration now includes controls to manually pause and resume autoplay, offering users more interactive control over carousel behavior.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
Copy link

coderabbitai bot commented Mar 14, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes add functionality for managing carousel autoplay based on page visibility. The BitCarousel component now injects a new BitPageVisibility service and implements methods to pause and resume autoplay when the page visibility changes. A corresponding JavaScript module sets up a one-time event listener for visibility changes, and dependency injection is updated to register the new service. Additionally, an unused import is removed in the SnackBar component, and demo code is updated with new public carousel control members.

Changes

File(s) Summary
src/.../Components/Lists/Carousel/BitCarousel.razor.cs
src/.../Pages/Components/Lists/Carousel/BitCarouselDemo.razor.cs
Updated carousel component and demo: added Pause, Resume, and PageVisibilityChange methods; updated lifecycle methods to subscribe/unsubscribe to page visibility events for controlling autoplay.
src/.../Extensions/IServiceCollectionExtensions.cs
src/.../Utils/BitPageVisibility.cs
src/.../Scripts/PageVisibility.ts
Introduced page visibility infrastructure: registered the BitPageVisibility service via DI, added a new utility class for visibility tracking with an OnChange event and JS interop, and implemented a TypeScript helper that registers a one-time visibilitychange event listener.
src/.../Components/Notifications/SnackBar/BitSnackBar.razor.cs Removed the unused using System.Text; import.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant B as Browser
    participant JS as PageVisibility (TS)
    participant VP as BitPageVisibility
    participant BC as BitCarousel

    B->>JS: visibilitychange event
    JS->>VP: invokeMethodAsync("VisibilityChanged", hidden)
    VP->>BC: trigger OnChange event (hidden state)
    alt Page hidden
        BC->>BC: Pause autoplay
    else Page visible
        BC->>BC: Resume autoplay
    end

Poem

I'm a rabbit in the codefield, swift and keen,
Hopping through changes with sights unseen.
Page hidden? I hit pause, then resume in a flash,
Watching the visibility as moments dash.
With each gentle hop, I celebrate the code stash! 🐇🌟


🪧 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.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
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/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Lists/Carousel/BitCarouselDemo.razor.cs (1)

213-224: Adding Pause and Resume members documentation is appropriate.

These new public members match the functionality added to the BitCarousel component for controlling autoplay based on page visibility.

However, consider adding example code that demonstrates the usage of these new methods, similar to how GoNext, GoPrev, and GoTo are implemented and demonstrated.

src/BlazorUI/Bit.BlazorUI/Scripts/PageVisibility.ts (1)

1-13: Implementation of page visibility tracking looks good.

The code correctly sets up a one-time event listener for document visibility changes and invokes the .NET method appropriately.

Consider refactoring this to use standalone functions instead of a static class, as suggested by the static analysis:

-namespace BitBlazorUI {
-    export class PageVisibility {
-        private static _isInitialized = false;
-
-        public static init(dotnetObj: DotNetObject) {
-            if (PageVisibility._isInitialized) return;
-
-            PageVisibility._isInitialized = true;
-
-            document.addEventListener('visibilitychange', () => dotnetObj.invokeMethodAsync('VisibilityChanged', document.hidden));
-        }
-    }
-}
+namespace BitBlazorUI {
+    let _isInitialized = false;
+    
+    export function initPageVisibility(dotnetObj: DotNetObject) {
+        if (_isInitialized) return;
+        
+        _isInitialized = true;
+        
+        document.addEventListener('visibilitychange', () => dotnetObj.invokeMethodAsync('VisibilityChanged', document.hidden));
+    }
+}

This approach is generally more aligned with TypeScript best practices for utility functions.

🧰 Tools
🪛 Biome (1.9.4)

[error] 2-12: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)

src/BlazorUI/Bit.BlazorUI/Utils/BitPageVisibility.cs (2)

1-12: Implementation looks good, but consider implementing IAsyncDisposable.

The class is well-structured with clear documentation linking to the MDN docs for the Page Visibility API. The primary constructor pattern for injecting IJSRuntime follows modern C# conventions.

However, since you're creating a DotNetObjectReference<BitPageVisibility> which needs to be disposed, this class should implement IAsyncDisposable to properly clean up resources.

-public class BitPageVisibility(IJSRuntime js)
+public class BitPageVisibility(IJSRuntime js) : IAsyncDisposable
 {
     private bool _isInitialized;
     private DotNetObjectReference<BitPageVisibility>? _dotnetObj;
+
+    public async ValueTask DisposeAsync()
+    {
+        _dotnetObj?.Dispose();
+        _dotnetObj = null;
+    }

22-31: Good implementation, but add exception handling.

The initialization method prevents multiple initializations and correctly sets up the JavaScript interop. However, there's no exception handling for JavaScript interop failures.

 public async Task Init()
 {
     if (_isInitialized) return;
-
-    _isInitialized = true;
-
-    _dotnetObj = DotNetObjectReference.Create(this);
-
-    await js.InvokeVoid("BitBlazorUI.PageVisibility.init", _dotnetObj);
+    
+    try
+    {
+        _dotnetObj = DotNetObjectReference.Create(this);
+        await js.InvokeVoid("BitBlazorUI.PageVisibility.init", _dotnetObj);
+        _isInitialized = true;
+    }
+    catch (Exception ex)
+    {
+        // Set flag back to false if initialization fails
+        _dotnetObj?.Dispose();
+        _dotnetObj = null;
+        // Consider logging the exception
+        throw; // Re-throw to let caller handle it
+    }
 }
src/BlazorUI/Bit.BlazorUI/Components/Lists/Carousel/BitCarousel.razor.cs (1)

224-234: Add exception handling for Page Visibility initialization.

The initialization of the BitPageVisibility service could fail if JavaScript interop encounters an issue. This would disrupt the component's lifecycle since it occurs during rendering.

 if (firstRender is false) return;

-await _pageVisibility.Init();
+try
+{
+    await _pageVisibility.Init();
+}
+catch (Exception ex)
+{
+    // Log the exception or handle it appropriately
+    // Consider how to recover or degrade gracefully
+}

 await _js.BitObserversRegisterResize(UniqueId, RootElement, _dotnetObj);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b3d3baf and 813de7d.

📒 Files selected for processing (6)
  • src/BlazorUI/Bit.BlazorUI/Components/Lists/Carousel/BitCarousel.razor.cs (5 hunks)
  • src/BlazorUI/Bit.BlazorUI/Components/Notifications/SnackBar/BitSnackBar.razor.cs (1 hunks)
  • src/BlazorUI/Bit.BlazorUI/Extensions/IServiceCollectionExtensions.cs (1 hunks)
  • src/BlazorUI/Bit.BlazorUI/Scripts/PageVisibility.ts (1 hunks)
  • src/BlazorUI/Bit.BlazorUI/Utils/BitPageVisibility.cs (1 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Lists/Carousel/BitCarouselDemo.razor.cs (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/BlazorUI/Bit.BlazorUI/Scripts/PageVisibility.ts

[error] 2-12: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (6)
src/BlazorUI/Bit.BlazorUI/Components/Notifications/SnackBar/BitSnackBar.razor.cs (1)

1-1: Cleanup of unused import looks good.

Removing the unused System.Text import helps maintain clean code.

src/BlazorUI/Bit.BlazorUI/Extensions/IServiceCollectionExtensions.cs (1)

12-12: LGTM! Good registration of the new BitPageVisibility service.

The service is correctly registered as scoped, consistent with the registration pattern used for BitThemeManager.

src/BlazorUI/Bit.BlazorUI/Utils/BitPageVisibility.cs (1)

15-18: LGTM: Event declaration is appropriate.

The event is properly declared with a nullable Func returning Task, which aligns with async event pattern.

src/BlazorUI/Bit.BlazorUI/Components/Lists/Carousel/BitCarousel.razor.cs (3)

26-26: LGTM: Service injection is correctly implemented.

The BitPageVisibility service is properly injected following the component's existing patterns.


199-200: LGTM: Event subscription properly implemented.

The event subscription is correctly set up in OnInitialized and properly unsubscribed in DisposeAsync.


470-471: LGTM: Proper event cleanup in DisposeAsync.

Correctly unsubscribes from the event handler to prevent memory leaks.

msynk added 2 commits March 14, 2025 11:33

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
@msynk msynk merged commit 396d7be into bitfoundation:develop Mar 14, 2025
3 checks passed
@msynk msynk deleted the 10231-blazorui-add-visibilitychange branch March 14, 2025 08:43
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.

The components that utilize a Timer can use Page Visibility API to reduce unwanted interactions
1 participant