Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jul 13, 2025

Link issues

fixes #6404

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add network monitoring support by creating NetworkMonitor and NetworkMonitorIndicator components with accompanying JS interop module, integrate them into the layout with styling, and include unit tests

New Features:

  • Introduce NetworkMonitor component enabling JS interop-based tracking of network state changes
  • Introduce NetworkMonitorIndicator component providing a UI indicator with popover details for network type, downlink, and RTT

Enhancements:

  • Integrate the network indicator into HomeLayout and import its SCSS stylesheet
  • Add net.js JavaScript module to listen for connection and online/offline events
  • Add NetworkMonitorState model class to encapsulate network information

Tests:

  • Add unit tests for NetworkMonitor and NetworkMonitorIndicator components
  • Update existing DisplayTest delays from 50ms to 100ms to stabilize lookup service assertions

@bb-auto bb-auto bot added the enhancement New feature or request label Jul 13, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jul 13, 2025

Reviewer's Guide

Introduces a network‐monitoring UI and service component using JS interop to track online/offline and connection metrics, integrates it into the main layout with new styles and localization, and covers functionality with unit tests.

Sequence diagram for network state change handling

sequenceDiagram
    participant Browser
    participant JSModule as net.js
    participant NetworkMonitor
    participant NetworkMonitorIndicator

    Browser->>JSModule: Network state changes (online/offline or connection info)
    JSModule->>NetworkMonitor: invokeMethodAsync(TriggerOnlineStateChanged/TriggerNetworkStateChanged)
    NetworkMonitor->>NetworkMonitorIndicator: OnNetworkStateChanged callback
    NetworkMonitorIndicator->>NetworkMonitorIndicator: Update UI state
Loading

Class diagram for new NetworkMonitor components

classDiagram
    class NetworkMonitorState {
        +bool IsOnline
        +string? NetworkType
        +double? Downlink
        +int RTT
    }
    class NetworkMonitor {
        +Func<NetworkMonitorState, Task>? OnNetworkStateChanged
        +List<string>? Indicators
        -NetworkMonitorState _state
        +Task TriggerOnlineStateChanged(bool online)
        +Task TriggerNetworkStateChanged(NetworkMonitorState state)
    }
    class NetworkMonitorIndicator {
        +string? Title
        +Placement PopoverPlacement
        +string? Trigger
        -NetworkMonitorState _state
        -List<string> _indicators
        -string _networkTypeString
        -string _downlinkString
        -string _rttString
        +Task OnNetworkStateChanged(NetworkMonitorState state)
    }
    NetworkMonitorIndicator --> NetworkMonitor : uses
    NetworkMonitorIndicator --> NetworkMonitorState : has
    NetworkMonitor --> NetworkMonitorState : has
Loading

File-Level Changes

Change Details Files
Extended test wait times
  • Increased Task.Delay from 50ms to 100ms in two assertions
test/UnitTest/Components/DisplayTest.cs
Added NetworkMonitorIndicator UI component
  • Created .razor view with Popover wrapper and metric display
  • Implemented code‐behind class to initialize, localize and render state
  • Authored SCSS for indicator variants and popover behavior
src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorIndicator.razor
src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorIndicator.razor.cs
src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorIndicator.razor.scss
Implemented NetworkMonitor service component with JS interop
  • Built NetworkMonitor class subclassing BootstrapModuleComponentBase
  • Defined NetworkMonitorState model for connection data
  • Wrote net.js module to capture navigator.connection changes and online/offline events
src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitor.cs
src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorState.cs
src/BootstrapBlazor/wwwroot/modules/net.js
Integrated component into layout and styles
  • Inserted NetworkMonitorIndicator into HomeLayout markup
  • Imported new SCSS into global components.scss
src/BootstrapBlazor.Server/Components/Layout/HomeLayout.razor
src/BootstrapBlazor/wwwroot/scss/components.scss
Updated localization resources
  • Added network monitor labels (Title, NetworkType, Downlink, RTT) to en.json and zh.json
src/BootstrapBlazor/Locales/en.json
src/BootstrapBlazor/Locales/zh.json
Added unit tests for network monitor
  • Tested indicator’s offline/online rendering behavior
  • Validated NetworkMonitor.OnNetworkStateChanged callback
test/UnitTest/Components/NetworkMonitorIndicatorTest.cs
test/UnitTest/Components/NetworkMonitorIndicatorTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6404 Add a NetworkMonitor component to the BootstrapBlazor library.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added this to the 9.8.0 milestone Jul 13, 2025
sourcery-ai[bot]
sourcery-ai bot previously approved these changes Jul 13, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @ArgoZhang - I've reviewed your changes - here's some feedback:

  • Implement a Dispose/OnAfterRender cleanup in the NetworkMonitor component to call the JS ‘dispose’ method and remove event listeners when the component is destroyed.
  • Add a feature‐detection guard or fallback path for browsers that don’t support navigator.connection to prevent runtime errors in unsupported environments.
  • Replace the hardcoded Task.Delay in tests with a more deterministic synchronization mechanism (e.g. awaiting state changes or using event callbacks) to avoid flaky timing issues.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Implement a Dispose/OnAfterRender cleanup in the NetworkMonitor component to call the JS ‘dispose’ method and remove event listeners when the component is destroyed.
- Add a feature‐detection guard or fallback path for browsers that don’t support navigator.connection to prevent runtime errors in unsupported environments.
- Replace the hardcoded Task.Delay in tests with a more deterministic synchronization mechanism (e.g. awaiting state changes or using event callbacks) to avoid flaky timing issues.

## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/wwwroot/modules/net.js:12` </location>
<code_context>
+            downlink, networkType: effectiveType, rTT: rtt
+        });
+    }
+    navigator.connection.onchange = e => {
+        updateState(e.target);
+    }
</code_context>

<issue_to_address>
Potential lack of feature detection for navigator.connection.

Add a check to ensure navigator.connection and its onchange property exist before using them to prevent errors in unsupported browsers.
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/wwwroot/modules/net.js:7` </location>
<code_context>
+export function init(id, options) {
+    const { invoke, onlineStateChangedCallback, onNetworkStateChangedCallback, indicators } = options;
+    const updateState = nt => {
+        const { downlink, effectiveType, rtt } = nt;
+        invoke.invokeMethodAsync(onNetworkStateChangedCallback, {
+            downlink, networkType: effectiveType, rTT: rtt
+        });
+    }
</code_context>

<issue_to_address>
Inconsistent property casing for 'rTT' in the object sent to .NET.

The property name should be 'RTT' to match the C# class and avoid deserialization problems.
</issue_to_address>

### Comment 3
<location> `src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorIndicator.razor:15` </location>
<code_context>
+                <div>@_state.NetworkType</div>
+            </div>
+            <div class="bb-nt-item">
+                <span>Downlink:</span>
+                <div>@_state.Downlink M/s</div>
+            </div>
+            <div class="bb-nt-item">
</code_context>

<issue_to_address>
Unit for downlink speed may be misleading.

Update the label to 'Mbps' to accurately reflect the standard unit for downlink speed.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                <span>Downlink:</span>
                <div>@_state.Downlink M/s</div>
=======
                <span>Downlink:</span>
                <div>@_state.Downlink Mbps</div>
>>>>>>> REPLACE

</suggested_fix>

### Comment 4
<location> `src/BootstrapBlazor/Components/NetworkMonitor/NetworkMonitorIndicator.razor:11` </location>
<code_context>
+    <Template>
+        <div class="bb-nt-main">
+            <div class="bb-nt-item">
+                <span>NetworkType:</span>
+                <div>@_state.NetworkType</div>
+            </div>
+            <div class="bb-nt-item">
</code_context>

<issue_to_address>
Hardcoded labels may not be localized.

Consider replacing the hardcoded labels with the existing localized strings from the code-behind to support localization.

Suggested implementation:

```
                <span>@NetworkTypeText:</span>

```

```
                <span>@DownlinkText:</span>

```

```
                <span>@RTTText:</span>

```

Make sure that `NetworkTypeText`, `DownlinkText`, and `RTTText` are defined as localized string properties in the code-behind file (NetworkMonitorIndicator.razor.cs or @code block), and that they retrieve the appropriate localized values.
</issue_to_address>

### Comment 5
<location> `test/UnitTest/Components/NetworkMonitorIndicatorTest.cs:19` </location>
<code_context>
+        });
+
+        var com = cut.FindComponent<NetworkMonitor>();
+        await cut.InvokeAsync(() => com.Instance.TriggerNetworkStateChanged(new NetworkMonitorState
+        {
+            IsOnline = false,
+            NetworkType = "4g",
+            Downlink = 10.0,
+            RTT = 50
+        }));
+        Assert.DoesNotContain("offline", cut.Markup);
+
+        await cut.InvokeAsync(() => com.Instance.TriggerOnlineStateChanged(true));
</code_context>

<issue_to_address>
Missing test for the 'offline' class when the network is offline.

Please add a test to check that the 'offline' class appears in the markup when the network is offline, to ensure the UI updates correctly.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        await cut.InvokeAsync(() => com.Instance.TriggerNetworkStateChanged(new NetworkMonitorState
        {
            IsOnline = false,
            NetworkType = "4g",
            Downlink = 10.0,
            RTT = 50
        }));
        Assert.DoesNotContain("offline", cut.Markup);

        await cut.InvokeAsync(() => com.Instance.TriggerOnlineStateChanged(true));
        Assert.DoesNotContain("offline", cut.Markup);
=======
        await cut.InvokeAsync(() => com.Instance.TriggerNetworkStateChanged(new NetworkMonitorState
        {
            IsOnline = false,
            NetworkType = "4g",
            Downlink = 10.0,
            RTT = 50
        }));
        Assert.Contains("offline", cut.Markup);

        await cut.InvokeAsync(() => com.Instance.TriggerOnlineStateChanged(true));
        Assert.DoesNotContain("offline", cut.Markup);
>>>>>>> REPLACE

</suggested_fix>

### Comment 6
<location> `test/UnitTest/Components/NetworkMonitorIndicatorTest.cs:45` </location>
<code_context>
+            });
+        });
+
+        await cut.InvokeAsync(() => cut.Instance.TriggerOnlineStateChanged(false));
+        Assert.NotNull(state);
+        Assert.False(state.IsOnline);
+    }
+}
</code_context>

<issue_to_address>
Missing test for TriggerNetworkStateChanged with various NetworkMonitorState values.

Please add tests covering different NetworkMonitorState property combinations to verify correct callback and state updates across all scenarios.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    }
+}
=======
    }

    [Theory]
    [InlineData(true, true)]
    [InlineData(true, false)]
    [InlineData(false, true)]
    [InlineData(false, false)]
    public async Task NetworkMonitor_TriggerNetworkStateChanged_UpdatesStateCorrectly(bool isOnline, bool isConnectionExpensive)
    {
        NetworkMonitorState? callbackState = null;
        var cut = Context.RenderComponent<NetworkMonitor>(pb =>
        {
            pb.Add(a => a.OnNetworkStateChanged, v =>
            {
                callbackState = v;
                return Task.CompletedTask;
            });
        });

        var testState = new NetworkMonitorState
        {
            IsOnline = isOnline,
            IsConnectionExpensive = isConnectionExpensive
        };

        await cut.InvokeAsync(() => cut.Instance.TriggerNetworkStateChanged(testState));

        Assert.NotNull(callbackState);
        Assert.Equal(isOnline, callbackState!.IsOnline);
        Assert.Equal(isConnectionExpensive, callbackState.IsConnectionExpensive);
    }
}
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@codecov
Copy link

codecov bot commented Jul 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (7441314) to head (127de2b).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6405   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          718       722    +4     
  Lines        31726     31790   +64     
  Branches      4478      4482    +4     
=========================================
+ Hits         31726     31790   +64     
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ArgoZhang ArgoZhang enabled auto-merge (squash) July 13, 2025 01:34
@ArgoZhang ArgoZhang disabled auto-merge July 13, 2025 01:34
@ArgoZhang ArgoZhang merged commit 61ef8f7 into main Jul 13, 2025
6 checks passed
@ArgoZhang ArgoZhang deleted the feat-network branch July 13, 2025 01:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(NetworkMonitor): add NetworkMonitor component

2 participants