Skip to content

feat(TreeView): add OnBeforeTreeItemClick parameter#7375

Merged
ArgoZhang merged 6 commits intomainfrom
refactor-tree
Dec 19, 2025
Merged

feat(TreeView): add OnBeforeTreeItemClick parameter#7375
ArgoZhang merged 6 commits intomainfrom
refactor-tree

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Dec 19, 2025

Link issues

fixes #7374

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 a pre-click callback to TreeView items and update samples and tests to support the new behavior.

New Features:

  • Introduce OnBeforeTreeItemClick callback on TreeView items to allow async confirmation or veto before processing a node click.

Enhancements:

  • Update TreeView sample attribute metadata to use generic TreeViewItem signatures and document the new pre-click callback.
  • Extend TreeView tips in the sample page to mention the new pre-click callback behavior.

Tests:

  • Add a unit test verifying that returning false from OnBeforeTreeItemClick prevents the regular click callback from running.

Copilot AI review requested due to automatic review settings December 19, 2025 08:59
@bb-auto bb-auto Bot added the enhancement New feature or request label Dec 19, 2025
@bb-auto bb-auto Bot added this to the v10.1.0 milestone Dec 19, 2025
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Dec 19, 2025

Reviewer's Guide

Adds a new OnBeforeTreeItemClick callback to TreeView that can asynchronously veto item click handling, wires it into the click pipeline, updates samples/docs metadata to use generic TreeViewItem types, and adds a unit test and tip entry to cover and document the new behavior.

Class diagram for TreeView with OnBeforeTreeItemClick

classDiagram
    class TreeView_TItem {
        +Func~TreeViewItem_TItem, Task~?~~ OnTreeItemClick
        +Func~TreeViewItem_TItem, Task_bool~~ OnBeforeTreeItemClick
        +Func~TreeViewItem_TItem, Task~?~~ OnTreeItemChecked
        +Func~TreeViewItem_TItem, Task~?~~ OnExpandNodeAsync
        -TreeViewItem_TItem _activeItem
        -bool ClickToggleNode
        -bool ShowCheckbox
        -bool ClickToggleCheck
        -bool IsDisabled
        -bool CanExpandWhenDisabled
        +Task OnClick(TreeViewItem_TItem item)
        +Task OnToggleNodeAsync(TreeViewItem_TItem item)
        +Task OnCheckStateChanged(TreeViewItem_TItem item, CheckedState state)
        +CheckedState ToggleCheckState(CheckedState current)
        +void StateHasChanged()
    }

    class TreeViewItem_TItem {
        +CheckedState CheckedState
        +bool CanTriggerClickNode(bool isDisabled, bool canExpandWhenDisabled)
    }

    TreeView_TItem --> TreeViewItem_TItem : contains

    class AttributeItem {
        +string Name
        +string Description
        +string Type
        +string ValueList
        +string DefaultValue
    }

    class TreeViews_Sample {
        +static AttributeItem[] GetAttributes()
    }

    TreeViews_Sample --> AttributeItem : uses

    %% AttributeItem entries updated to use generic TreeViewItem_TItem types
    class TreeView_string {
        +Func~TreeViewItem_TItem, Task~?~~ OnTreeItemClick
        +Func~TreeViewItem_TItem, Task_bool~~ OnBeforeTreeItemClick
        +Func~TreeViewItem_TItem, Task~?~~ OnTreeItemChecked
        +Func~TreeViewItem_TItem, Task~?~~ OnExpandNodeAsync
    }

    TreeView_string --|> TreeView_TItem
Loading

File-Level Changes

Change Details Files
Introduce OnBeforeTreeItemClick parameter on TreeView and integrate it into the item click workflow so that click handling can be conditionally prevented.
  • Add nullable Func<TreeViewItem, Task> OnBeforeTreeItemClick component parameter with XML documentation.
  • Update OnClick handler to invoke OnBeforeTreeItemClick when present and short‑circuit subsequent click logic if it returns false.
  • Ensure that active item setting, node toggling, checkbox toggling, and OnTreeItemClick invocation only run when the pre‑click callback confirms (returns true).
  • Minor formatting fix for the AllowDrag condition spacing in OnAfterRenderAsync.
src/BootstrapBlazor/Components/TreeView/TreeView.razor.cs
Add unit test to verify that OnBeforeTreeItemClick can cancel the click callback execution.
  • Create OnBeforeTreeItemClick_Ok fact that sets OnBeforeTreeItemClick to return false and asserts OnTreeItemClick is not invoked when a node is clicked.
test/UnitTest/Components/TreeViewTest.cs
Update TreeView sample metadata and tips to document the new callback and correct generic type signatures.
  • Change TreeView attribute descriptions to use TreeViewItem in Type and DefaultValue fields for several callbacks and Items property.
  • Add a new AttributeItem entry describing OnBeforeTreeItemClick as a Func<TreeViewItem, Task> with a Chinese description.
  • Add an extra tip list item in the TreeViews sample view for the OnBeforeTreeItemClick behavior.
  • Normalize file headers and page directive BOM/spacing in sample files.
src/BootstrapBlazor.Server/Components/Samples/TreeViews.razor.cs
src/BootstrapBlazor.Server/Components/Samples/TreeViews.razor
src/BootstrapBlazor.Server/Locales/en-US.json
src/BootstrapBlazor.Server/Locales/zh-CN.json

Assessment against linked issues

Issue Objective Addressed Explanation
#7374 Add a new OnBeforeTreeItemClick parameter to the TreeView component that allows consumers to run async logic and return a bool indicating whether the tree item click should proceed.
#7374 Integrate the OnBeforeTreeItemClick parameter into the TreeView click handling logic so that when it returns false, the normal click behavior (active item change, expand/toggle, checkbox toggle, and OnTreeItemClick callback) is skipped.
#7374 Document and demonstrate the new OnBeforeTreeItemClick parameter (including sample usage/tests and attribute metadata).

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

Copy link
Copy Markdown
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 there - I've reviewed your changes - here's some feedback:

  • You added a new TreeViewsTipsOnBeforeTreeItemClick usage in TreeViews.razor, but there are no corresponding entries shown in en-US.json or zh-CN.json; make sure the new localization keys are added so the tip renders correctly in both languages.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- You added a new `TreeViewsTipsOnBeforeTreeItemClick` usage in `TreeViews.razor`, but there are no corresponding entries shown in `en-US.json` or `zh-CN.json`; make sure the new localization keys are added so the tip renders correctly in both languages.

## Individual Comments

### Comment 1
<location> `test/UnitTest/Components/TreeViewTest.cs:829-838` </location>
<code_context>
+    public async Task OnBeforeTreeItemClick_Ok()
+    {
+        var clicked = false;
+        var cut = Context.Render<TreeView<TreeFoo>>(pb =>
+        {
+            pb.Add(a => a.ClickToggleNode, true);
+            pb.Add(a => a.Items, TreeFoo.GetTreeItems());
+            pb.Add(a => a.OnTreeItemClick, node =>
+            {
+                clicked = true;
+                return Task.CompletedTask;
+            });
+            pb.Add(a => a.OnBeforeTreeItemClick, node =>
+            {
+                return Task.FromResult(false);
+            });
+        });
+        var node = cut.FindAll(".tree-node").Skip(1).First();
+        await cut.InvokeAsync(() => node.Click());
+        Assert.False(clicked);
+    }
+
</code_context>

<issue_to_address>
**suggestion (testing):** Extend the test to verify that `OnBeforeTreeItemClick` also blocks other click side effects (not just `OnTreeItemClick`).

The test currently only asserts that `OnTreeItemClick` is not invoked when `OnBeforeTreeItemClick` returns `false`. Since the implementation also blocks `_activeItem` updates, node toggling (`OnToggleNodeAsync`), and checkbox toggling (`OnCheckStateChanged`) when `confirm` is false, please extend this test (or add separate tests) to also verify that:
- The clicked node is not expanded/collapsed when `ClickToggleNode` is `true`.
- Checkbox state is unchanged when `ShowCheckbox` and `ClickToggleCheck` are enabled.
- The selected/active node does not change.

Suggested implementation:

```csharp
        Assert.True(clicked);
    }

    [Fact]
    public async Task OnBeforeTreeItemClick_Ok()
    {
        // arrange
        var clicked = false;

        var cut = Context.Render<TreeView<TreeFoo>>(pb =>
        {
            pb.Add(a => a.ClickToggleNode, true);
            pb.Add(a => a.ShowCheckbox, true);
            pb.Add(a => a.ClickToggleCheck, true);
            pb.Add(a => a.Items, TreeFoo.GetTreeItems());
            pb.Add(a => a.OnTreeItemClick, node =>
            {
                clicked = true;
                return Task.CompletedTask;
            });
            pb.Add(a => a.OnBeforeTreeItemClick, node =>
            {
                // Block the click side-effects.
                return Task.FromResult(false);
            });
        });

        // capture initial state before click
        var nodes = cut.FindAll(".tree-node");
        var node = nodes.Skip(1).First();

        var initialClasses = node.ClassList.ToArray();

        var checkbox = node.QuerySelector("input[type=checkbox]") as AngleSharp.Dom.IElement;
        var initialChecked = checkbox?.HasAttribute("checked") ?? false;

        AngleSharp.Dom.IElement? activeNodeBefore = null;
        string? activeNodeIdBefore = null;
        try
        {
            activeNodeBefore = cut.Find(".tree-node.active");
            activeNodeIdBefore = activeNodeBefore.GetAttribute("data-id");
        }
        catch
        {
            // No active node before click – keep both "before" and "after"
            // values null so the assertion still verifies they are equal.
        }

        // act
        await cut.InvokeAsync(() => node.Click());

        // assert

        // 1. OnTreeItemClick is not invoked
        Assert.False(clicked);

        // 2. Node expand/collapse state is unchanged
        nodes = cut.FindAll(".tree-node");
        node = nodes.Skip(1).First();
        Assert.Equal(initialClasses, node.ClassList);

        // 3. Checkbox state is unchanged
        checkbox = node.QuerySelector("input[type=checkbox]") as AngleSharp.Dom.IElement;
        var afterChecked = checkbox?.HasAttribute("checked") ?? false;
        Assert.Equal(initialChecked, afterChecked);

        // 4. Active/selected node is unchanged
        AngleSharp.Dom.IElement? activeNodeAfter = null;
        string? activeNodeIdAfter = null;
        try
        {
            activeNodeAfter = cut.Find(".tree-node.active");
            activeNodeIdAfter = activeNodeAfter.GetAttribute("data-id");
        }
        catch
        {
            // Still no active node after click
        }

        Assert.Equal(activeNodeIdBefore, activeNodeIdAfter);
    }

```

1. Ensure `using AngleSharp.Dom;` is present at the top of `TreeViewTest.cs` so that `AngleSharp.Dom.IElement` and `ClassList` compile.
2. If your DOM structure or CSS classes differ (for example, if the active/selected node uses a different class than `.tree-node.active`, or the checkbox uses a different selector than `input[type=checkbox]`), adjust:
   - The selector used to locate the checkbox.
   - The selector used to locate the active node.
   - The way expansion/collapse state is asserted (you may prefer to assert on specific classes like `"is-expanded"` / `"is-collapsed"` instead of comparing the full `ClassList` arrays).
3. If the TreeView component exposes a more direct way to inspect the active or expanded node (e.g., via attributes like `data-expanded` / `data-active-id`), consider replacing the `ClassList` and `data-id` checks with those more explicit indicators to make the test more robust.
</issue_to_address>

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.

Comment thread test/UnitTest/Components/TreeViewTest.cs
@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 19, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@1f1ac65). Learn more about missing BASE report.
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff            @@
##             main     #7375   +/-   ##
========================================
  Coverage        ?   100.00%           
========================================
  Files           ?       748           
  Lines           ?     32766           
  Branches        ?      4545           
========================================
  Hits            ?     32766           
  Misses          ?         0           
  Partials        ?         0           
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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ArgoZhang ArgoZhang merged commit 6ecb251 into main Dec 19, 2025
9 of 10 checks passed
@ArgoZhang ArgoZhang deleted the refactor-tree branch December 19, 2025 09:03
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds a new OnBeforeTreeItemClick parameter to the TreeView component that allows consumers to intercept and potentially prevent node click actions. When this callback returns false, the click action and all subsequent operations (expand/collapse, OnTreeItemClick, checkbox toggle) are cancelled.

Key Changes:

  • Added OnBeforeTreeItemClick callback parameter that returns a boolean to control whether the click proceeds
  • Modified the OnClick method to check the callback result before executing node click logic
  • Added comprehensive test coverage and documentation in both English and Chinese

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/BootstrapBlazor/Components/TreeView/TreeView.razor.cs Added OnBeforeTreeItemClick parameter and integrated callback check into OnClick method logic; includes minor formatting fix for spacing
test/UnitTest/Components/TreeViewTest.cs Added unit test to verify OnBeforeTreeItemClick prevents node click when returning false
src/BootstrapBlazor.Server/Components/Samples/TreeViews.razor.cs Updated attribute documentation to include OnBeforeTreeItemClick and corrected generic type parameters for consistency
src/BootstrapBlazor.Server/Locales/zh-CN.json Added Chinese documentation explaining the new OnBeforeTreeItemClick callback functionality
src/BootstrapBlazor.Server/Locales/en-US.json Added English documentation explaining the new OnBeforeTreeItemClick callback functionality
src/BootstrapBlazor.Server/Components/Samples/TreeViews.razor Added display of the new OnBeforeTreeItemClick documentation in the tips section

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

new()
{
Name = nameof(TreeView<string>.OnBeforeTreeItemClick),
Description = "点击节点前回调方法",
Copy link

Copilot AI Dec 19, 2025

Choose a reason for hiding this comment

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

The Description field contains Chinese text while other attributes in this file use English descriptions. This is inconsistent with the rest of the file where descriptions are in English. The Description should be translated to English to maintain consistency.

Suggested change
Description = "点击节点前回调方法",
Description = "Callback delegate before tree control node is clicked",

Copilot uses AI. Check for mistakes.
{
_activeItem = item;
if (ClickToggleNode && item.CanTriggerClickNode(IsDisabled, CanExpandWhenDisabled))
var confirm = true;
Copy link

Copilot AI Dec 19, 2025

Choose a reason for hiding this comment

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

The variable name 'confirm' is misleading in this context. Since the callback is named 'OnBeforeTreeItemClick' and returns a boolean to indicate whether the click should proceed, a more descriptive name would be 'shouldProceed' or 'canProceed' to better convey the intent that this controls whether the click action continues.

Copilot uses AI. Check for mistakes.
"TreeViewsTips6": "Set whether the node is <b>expanded</b> state through <code>TreeViewItem&lt;TItem&gt;.IsExpand</code>",
"TreeViewsTips7": "Set whether the node is <b>selected</b> state through <code>TreeViewItem&lt;TItem&gt;.IsActive</code>",
"TreeViewsTips8": "Through <code>TreeViewItem&lt;TItem&gt;.Checked</code>, set whether the node is in <b>checked/single selection</b> state",
"TreeViewsTipsOnBeforeTreeItemClick": "You can prevent a node click by setting the <code>OnBeforeTreeItemClick</code> callback method, and cancel the click action when it returns <code>false</code>.",
Copy link

Copilot AI Dec 19, 2025

Choose a reason for hiding this comment

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

The English translation is somewhat redundant with "prevent" and "cancel" conveying the same meaning. The sentence can be simplified to be more concise and clear.

Suggested change
"TreeViewsTipsOnBeforeTreeItemClick": "You can prevent a node click by setting the <code>OnBeforeTreeItemClick</code> callback method, and cancel the click action when it returns <code>false</code>.",
"TreeViewsTipsOnBeforeTreeItemClick": "Use the <code>OnBeforeTreeItemClick</code> callback to cancel a node click by returning <code>false</code>.",

Copilot uses AI. Check for mistakes.
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(TreeView): add OnBeforeTreeItemClick parameter

2 participants