Skip to content

feat(TreeView): support Darg and Drop function #6121

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

syminomega
Copy link
Contributor

@syminomega syminomega commented May 30, 2025

Issues

#6216

New Feature

Add Draggable TreeView

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

Implement drag-and-drop support for TreeView nodes with customizable drop behaviors and visual previews.

New Features:

  • Add ItemDraggable, Draggable, and PreviewDrop parameters to enable node dragging and drop preview.
  • Introduce OnItemDragStart, OnItemDragEnd, OnItemDrop callbacks and an OnDrop handler for drop event customization.
  • Define TreeDropEventArgs class and TreeDropType enum to represent drop operations.

Enhancements:

  • Add SCSS styling and CSS classes for drop zones and preview indicators on tree nodes.

Documentation:

  • Update sample TreeViews component to demonstrate draggable TreeView usage and OnDrop event logging.

Copy link

bb-auto bot commented May 30, 2025

Thanks for your PR, @syminomega. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

Copy link
Contributor

sourcery-ai bot commented May 30, 2025

Reviewer's Guide

This PR adds full drag-and-drop reordering support to the TreeView component by introducing draggable parameters and callbacks, rendering drop zones with preview indicators, and updating the component logic to handle item reordering on drop.

Sequence Diagram for TreeView Item Drag-and-Drop

sequenceDiagram
    actor User
    participant SourceRow as TreeViewRow (Source)
    participant TargetRow as TreeViewRow (Target)
    participant TreeViewComp as TreeView

    User->>SourceRow: Initiates drag (ondragstart)
    SourceRow->>SourceRow: DragStart(eventArgs)
    SourceRow->>TreeViewComp: OnItemDragStart(SourceItem)
    TreeViewComp->>TreeViewComp: OnItemDragStart(item): sets _draggingItem, _previewDrop, StateHasChanged()

    User->>TargetRow: Drags over drop zone (ondragenter)
    TargetRow->>TargetRow: DragEnterChildInside() / DragEnterChildBelow()
    TargetRow->>TargetRow: Sets preview flags (e.g., _previewChildLast), Renders drop preview

    User->>TargetRow: Drops item (ondrop)
    TargetRow->>TargetRow: DropChildInside() / DropChildBelow()
    TargetRow->>TreeViewComp: OnItemDrop(TreeDropEventArgs)
    TreeViewComp->>TreeViewComp: OnItemDrop(args): sets args.Source
    TreeViewComp->>TreeViewComp: Invokes user OnDrop(args) callback
    alt User OnDrop returns true
        TreeViewComp->>TreeViewComp: Reorders items (updates TreeViewItem parents/collections)
        TreeViewComp->>TreeViewComp: Resets _draggingItem, _previewDrop, StateHasChanged()
    end

    User->>SourceRow: Drag operation ends (ondragend)
    SourceRow->>SourceRow: DragEnd(eventArgs)
    SourceRow->>TreeViewComp: OnItemDragEnd()
    TreeViewComp->>TreeViewComp: OnItemDragEnd(): resets _previewDrop, _draggingItem, StateHasChanged()
Loading

File-Level Changes

Change Details Files
Implement draggable behavior in TreeViewRow
  • Add Draggable and PreviewDrop parameters
  • Define OnItemDragStart, OnItemDragEnd and OnItemDrop callbacks
  • Implement drag event handlers (DragStart, DragEnd, DragEnter/Leave, DropChildInside, DropChildBelow)
  • Update markup to render draggable attribute and drop zones with preview elements
  • Add CSS class for drop-pass state
Components/TreeView/TreeViewRow.razor.cs
Components/TreeView/TreeViewRow.razor
Add drop preview and styling
  • Define CSS variable for preview color
  • Add drop-zone layout and preview classes (.tree-drop-zone, .tree-preview-*)
  • Disable user-select and pointer events during drag
  • Add .tree-drop-pass class to suppress pointer events
Components/TreeView/TreeView.razor.scss
Extend TreeView component to handle drag-and-drop
  • Introduce ItemDraggable and OnDrop parameters
  • Maintain preview state and current dragging item
  • Implement OnItemDragStart, OnItemDragEnd, OnItemDrop to reorder items based on drop type
  • Pass draggable settings and callbacks into each TreeViewRow
Components/TreeView/TreeView.razor.cs
Components/TreeView/TreeView.razor
Define drop event arguments and types
  • Add TreeDropEventArgs with Source, Target, DropType and ExpandAfterDrop
  • Introduce TreeDropType enum (AsFirstChild, AsLastChild, AsSiblingBelow)
Components/TreeView/TreeView.razor.cs
Enums/TreeDropType.cs
Update demo to showcase draggable TreeView
  • Enable ItemDraggable and bind OnDrop in sample markup
  • Implement OnDrop handler in sample code to log moves
Server/Components/Samples/TreeViews.razor
Server/Components/Samples/TreeViews.razor.cs

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 requested a review from ArgoZhang May 30, 2025 09:20
Copy link

codecov bot commented May 30, 2025

Codecov Report

Attention: Patch coverage is 64.41718% with 58 lines in your changes missing coverage. Please review.

Project coverage is 99.81%. Comparing base (c0e8878) to head (b24e2d8).

Files with missing lines Patch % Lines
...rapBlazor/Components/TreeView/TreeViewRow.razor.cs 64.70% 23 Missing and 7 partials ⚠️
...tstrapBlazor/Components/TreeView/TreeView.razor.cs 62.12% 20 Missing and 5 partials ⚠️
...tstrapBlazor/Components/TreeView/TreeViewRow.razor 75.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main    #6121      +/-   ##
===========================================
- Coverage   100.00%   99.81%   -0.19%     
===========================================
  Files          704      704              
  Lines        31093    31256     +163     
  Branches      4395     4414      +19     
===========================================
+ Hits         31093    31198     +105     
- Misses           0       45      +45     
- Partials         0       13      +13     
Flag Coverage Δ
BB 99.81% <64.41%> (?)

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.

sourcery-ai[bot]
sourcery-ai bot previously approved these changes May 30, 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 @syminomega - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 2 issues found
  • 🟢 Documentation: all looks good

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.

/// Drop action can be cancelled by returning false.
/// </summary>
[Parameter]
public Func<TreeDropEventArgs<TItem>, Task<bool>> OnDrop { get; set; } = _ => Task.FromResult(true);
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Default value for OnDrop may mask missing handler.

Consider making OnDrop a required parameter or log a warning when the default is used to help identify missing handlers.

Suggested implementation:

    [Parameter]
    public Func<TreeDropEventArgs<TItem>, Task<bool>> OnDrop { get; set; }

    private bool _previewDrop;
    private async Task<bool> InvokeOnDropAsync(TreeDropEventArgs<TItem> args)
    {
        if (OnDrop != null)
        {
            return await OnDrop.Invoke(args);
        }
        else
        {
            Console.WriteLine("Warning: OnDrop handler is not set. Drop action will be ignored.");
            return false;
        }
    }

    private void OnItemDragEnd()

You will need to replace any direct calls to OnDrop.Invoke(...) elsewhere in this file with await InvokeOnDropAsync(...) to ensure the warning and fallback behavior are applied consistently.


_draggingItem = null;
_previewDrop = false;
_rows = GetTreeItems().ToFlat();
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (performance): Potential performance issue with full tree flattening after each drop.

Consider updating only the modified tree sections instead of flattening the entire tree after each drop to enhance performance, especially for large trees.

Suggested implementation:

            _draggingItem = null;
            _previewDrop = false;
            UpdateRowsAfterDrop();

            StateHasChanged();
    /// <summary>
    /// Updates only the affected rows in the _rows collection after a drop operation,
    /// instead of flattening the entire tree for performance.
    /// </summary>
    private void UpdateRowsAfterDrop()
    {
        // TODO: Implement logic to update only the modified sections of _rows
        // based on the drag-and-drop operation.
        // This should update, insert, or remove only the affected items in _rows.
        // For now, this is a placeholder to be implemented according to your tree structure.
    }

    #region Draggable

You will need to implement the logic inside UpdateRowsAfterDrop() to update only the relevant parts of _rows based on your tree structure and the specifics of your drag-and-drop operation. This may involve:

  • Identifying which nodes were moved or changed.
  • Updating, inserting, or removing only those nodes in _rows.
  • Ensuring the UI reflects only the necessary changes for optimal performance.

If you have helper methods or data structures that track the affected nodes, use them here.

Comment on lines +338 to +339
await ToggleNodeAsync();
StateHasChanged();
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (performance): Calling StateHasChanged inside DragStart may cause unnecessary re-renders.

Consider removing or batching this StateHasChanged call if the UI is already updated by the drag operation to avoid redundant renders.

Suggested change
await ToggleNodeAsync();
StateHasChanged();
await ToggleNodeAsync();

OnItemDragEnd?.Invoke();
}

private bool _previewChildLast;
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider replacing multiple boolean preview flags with a single enum and centralizing drop logic to simplify state management.

// 1. Introduce a single enum to represent all preview states:
private enum PreviewState
{
    None,
    InsideLast,
    InsideFirst,
    Below
}

private PreviewState _previewState;

// 2. Helper methods to set/clear the preview state:
private void SetPreview(PreviewState state) => _previewState = state;
private void ClearPreview() => _previewState = PreviewState.None;

// 3. Simplify DragEnter/Leave:
private void DragEnterChildInside(DragEventArgs e) => SetPreview(PreviewState.InsideLast);
private void DragLeaveChildInside(DragEventArgs e) => ClearPreview();

private void DragEnterChildBelow(DragEventArgs e)
{
    var canBecomeFirst = (Item.HasChildren || Item.Items.Any()) && Item.IsExpand;
    SetPreview(canBecomeFirst ? PreviewState.InsideFirst : PreviewState.Below);
}
private void DragLeaveChildBelow(DragEventArgs e) => ClearPreview();

// 4. Simplify Drop handlers into one method:
private async Task HandleDrop(DragEventArgs e)
{
    if (OnItemDrop == null) return;
    var args = new TreeDropEventArgs<TItem>
    {
        Target = Item,
        ExpandAfterDrop = _expandAfterDrop,
        DropType = _previewState switch
        {
            PreviewState.InsideLast  => TreeDropType.AsLastChild,
            PreviewState.InsideFirst => TreeDropType.AsFirstChild,
            PreviewState.Below       => TreeDropType.AsSiblingBelow,
            _                        => throw new InvalidOperationException()
        }
    };
    ClearPreview();
    await OnItemDrop.Invoke(args);
}

// 5. Wire up DropChildInside/DropChildBelow to the unified handler:
private Task DropChildInside(DragEventArgs e) => HandleDrop(e);
private Task DropChildBelow(DragEventArgs e) => HandleDrop(e);

This replaces the three booleans with a single _previewState enum, centralizes preview‐state toggling in SetPreview/ClearPreview, and merges the drop logic into one HandleDrop method. All existing functionality is preserved.

StateHasChanged();
}

private async Task OnItemDrop(TreeDropEventArgs<TItem> e)
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider extracting the container/index computation and item insertion into helper methods to reduce nesting and duplication in OnItemDrop.

private async Task OnItemDrop(TreeDropEventArgs<TItem> e)
{
    if (_draggingItem is null)
        throw new InvalidOperationException("拖拽的项为空");

    // … pre–checks, remove from old parent, set expand …
    _draggingItem.Parent?.Items.Remove(_draggingItem);
    _draggingItem.IsExpand = e.ExpandAfterDrop;

    // compute target container, parent & insert index in one place
    (TreeViewItem<TItem>? newParent, IList<TreeViewItem<TItem>> container, int idx) = e.DropType switch
    {
        TreeDropType.AsFirstChild  => ( e.Target,   e.Target.Items,                    0 ),
        TreeDropType.AsLastChild   => ( e.Target,   e.Target.Items,      e.Target.Items.Count ),
        TreeDropType.AsSiblingBelow => GetSiblingBelowInfo(e.Target),
        _ => throw new ArgumentOutOfRangeException()
    };

    InsertDraggedItem(_draggingItem, newParent, container, idx);

    _draggingItem = null;
    _previewDrop = false;
    _rows = GetTreeItems().ToFlat();
    StateHasChanged();
}

private static (TreeViewItem<TItem>? parent, IList<TreeViewItem<TItem>> items, int index)
    GetSiblingBelowInfo(TreeViewItem<TItem> target)
{
    if (target.Parent is { } p)
    {
        var idx = p.Items.IndexOf(target) + 1;
        return (p, p.Items, idx);
    }
    else
    {
        var idx = Items.IndexOf(target) + 1;
        return (null, Items, idx);
    }
}

private void InsertDraggedItem(
    TreeViewItem<TItem> dragged,
    TreeViewItem<TItem>? parent,
    IList<TreeViewItem<TItem>> list,
    int index)
{
    if (index < 0 || index > list.Count)
        list.Add(dragged);
    else
        list.Insert(index, dragged);

    dragged.Parent = parent;
}

Extracting the “compute container/index” logic and a single InsertDraggedItem helper:

  • Removes the deep nesting and code‐duplication in each case.
  • Consolidates index bounds checks.
  • Centralizes parent assignment.

@ArgoZhang ArgoZhang changed the title feat:DraggableTree feat(TreeView): support Darg and Drop function Jun 12, 2025
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