Skip to content

fix: Tree Dnd updates #8229

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

Merged
merged 10 commits into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 57 additions & 10 deletions packages/@react-aria/dnd/src/DragManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {DragEndEvent, DragItem, DropActivateEvent, DropEnterEvent, DropEvent, Dr
import {getDragModality, getTypes} from './utils';
import {isVirtualClick, isVirtualPointerEvent} from '@react-aria/utils';
import type {LocalizedStringFormatter} from '@internationalized/string';
import {useEffect, useState} from 'react';
import {RefObject, useEffect, useState} from 'react';

let dropTargets = new Map<Element, DropTarget>();
let dropItems = new Map<Element, DroppableItem>();
Expand All @@ -32,7 +32,8 @@ interface DropTarget {
onDropTargetEnter?: (target: DroppableCollectionTarget | null) => void,
onDropActivate?: (e: DropActivateEvent, target: DroppableCollectionTarget | null) => void,
onDrop?: (e: DropEvent, target: DroppableCollectionTarget | null) => void,
onKeyDown?: (e: KeyboardEvent, dragTarget: DragTarget) => void
onKeyDown?: (e: KeyboardEvent, dragTarget: DragTarget) => void,
activateButtonRef?: RefObject<FocusableElement | null>
}

export function registerDropTarget(target: DropTarget) {
Expand All @@ -47,7 +48,8 @@ export function registerDropTarget(target: DropTarget) {
interface DroppableItem {
element: FocusableElement,
target: DroppableCollectionTarget,
getDropOperation?: (types: Set<string>, allowedOperations: DropOperation[]) => DropOperation
getDropOperation?: (types: Set<string>, allowedOperations: DropOperation[]) => DropOperation,
activateButtonRef?: RefObject<FocusableElement | null>
}

export function registerDropItem(item: DroppableItem) {
Expand Down Expand Up @@ -241,15 +243,26 @@ class DragSession {
this.cancelEvent(e);

if (e.key === 'Enter') {
if (e.altKey) {
if (e.altKey || e.target === this.getCurrentActivateButton()) {
this.activate();
} else {
this.drop();
}
}
}

getCurrentActivateButton(): FocusableElement | null {
return this.currentDropItem?.activateButtonRef?.current ?? this.currentDropTarget?.activateButtonRef?.current ?? null;
}

onFocus(e: FocusEvent) {
let activateButton = this.getCurrentActivateButton();
if (e.target === activateButton) {
// TODO: canceling this breaks the focus ring. Revisit when we support tabbing.
this.cancelEvent(e);
return;
}

// Prevent focus events, except to the original drag target.
if (e.target !== this.dragTarget.element) {
this.cancelEvent(e);
Expand All @@ -265,6 +278,9 @@ class DragSession {
this.validDropTargets.find(target => target.element.contains(e.target as HTMLElement));

if (!dropTarget) {
// if (e.target === activateButton) {
// activateButton.focus();
// }
if (this.currentDropTarget) {
this.currentDropTarget.element.focus();
} else {
Expand All @@ -274,10 +290,18 @@ class DragSession {
}

let item = dropItems.get(e.target as HTMLElement);
this.setCurrentDropTarget(dropTarget, item);
if (dropTarget) {
this.setCurrentDropTarget(dropTarget, item);
}
}

onBlur(e: FocusEvent) {
let activateButton = this.getCurrentActivateButton();
if (e.relatedTarget === activateButton) {
this.cancelEvent(e);
return;
}

if (e.target !== this.dragTarget.element) {
this.cancelEvent(e);
}
Expand All @@ -296,6 +320,11 @@ class DragSession {
onClick(e: MouseEvent) {
this.cancelEvent(e);
if (isVirtualClick(e) || this.isVirtualClick) {
if (e.target === this.getCurrentActivateButton()) {
this.activate();
return;
}

if (e.target === this.dragTarget.element) {
this.cancel();
return;
Expand All @@ -319,7 +348,7 @@ class DragSession {

cancelEvent(e: Event) {
// Allow focusin and focusout on the drag target so focus ring works properly.
if ((e.type === 'focusin' || e.type === 'focusout') && e.target === this.dragTarget?.element) {
if ((e.type === 'focusin' || e.type === 'focusout') && (e.target === this.dragTarget?.element || e.target === this.getCurrentActivateButton())) {
return;
}

Expand Down Expand Up @@ -375,14 +404,23 @@ class DragSession {

this.restoreAriaHidden = ariaHideOutside([
this.dragTarget.element,
...validDropItems.map(item => item.element),
...visibleDropTargets.map(target => target.element)
...validDropItems.flatMap(item => item.activateButtonRef?.current ? [item.element, item.activateButtonRef?.current] : [item.element]),
...visibleDropTargets.flatMap(target => target.activateButtonRef?.current ? [target.element, target.activateButtonRef?.current] : [target.element])
]);

this.mutationObserver.observe(document.body, {subtree: true, attributes: true, attributeFilter: ['aria-hidden']});
}

next() {
// TODO: Allow tabbing to the activate button. Revisit once we fix the focus ring.
// For now, the activate button is reachable by screen readers and ArrowLeft/ArrowRight
// is usable specifically by Tree. Will need tabbing for other components.
// let activateButton = this.getCurrentActivateButton();
// if (activateButton && document.activeElement !== activateButton) {
// activateButton.focus();
// return;
// }

if (!this.currentDropTarget) {
this.setCurrentDropTarget(this.validDropTargets[0]);
return;
Expand All @@ -409,6 +447,15 @@ class DragSession {
}

previous() {
// let activateButton = this.getCurrentActivateButton();
// if (activateButton && document.activeElement === activateButton) {
// let target = this.currentDropItem ?? this.currentDropTarget;
// if (target) {
// target.element.focus();
// return;
// }
// }

if (!this.currentDropTarget) {
this.setCurrentDropTarget(this.validDropTargets[this.validDropTargets.length - 1]);
return;
Expand Down Expand Up @@ -487,7 +534,6 @@ class DragSession {
if (this.currentDropTarget && typeof this.currentDropTarget.onDropTargetEnter === 'function') {
this.currentDropTarget.onDropTargetEnter(item.target);
}

item.element.focus();
this.currentDropItem = item;

Expand Down Expand Up @@ -578,12 +624,13 @@ class DragSession {

activate() {
if (this.currentDropTarget && typeof this.currentDropTarget.onDropActivate === 'function') {
let target = this.currentDropItem?.target ?? null;
let rect = this.currentDropTarget.element.getBoundingClientRect();
this.currentDropTarget.onDropActivate({
type: 'dropactivate',
x: rect.left + (rect.width / 2),
y: rect.top + (rect.height / 2)
}, null);
}, target);
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions packages/@react-aria/dnd/src/useDropIndicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import * as DragManager from './DragManager';
import {DroppableCollectionState} from '@react-stately/dnd';
import {DropTarget, Key, RefObject} from '@react-types/shared';
import {DropTarget, FocusableElement, Key, RefObject} from '@react-types/shared';
import {getDroppableCollectionId} from './utils';
import {HTMLAttributes} from 'react';
// @ts-ignore
Expand All @@ -23,7 +23,9 @@ import {useLocalizedStringFormatter} from '@react-aria/i18n';

export interface DropIndicatorProps {
/** The drop target that the drop indicator represents. */
target: DropTarget
target: DropTarget,
/** The ref to the activate button. */
activateButtonRef?: RefObject<FocusableElement | null>
}

export interface DropIndicatorAria {
Expand Down
13 changes: 9 additions & 4 deletions packages/@react-aria/dnd/src/useDroppableCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
DropTargetDelegate,
Key,
KeyboardDelegate,
KeyboardEvents,
Node,
RefObject
} from '@react-types/shared';
Expand All @@ -48,7 +47,8 @@ export interface DroppableCollectionOptions extends DroppableCollectionProps {
keyboardDelegate: KeyboardDelegate,
/** A delegate object that provides drop targets for pointer coordinates within the collection. */
dropTargetDelegate: DropTargetDelegate,
onKeyDown?: KeyboardEvents['onKeyDown']
/** A custom keyboard event handler for drop targets. */
onKeyDown?: (e: KeyboardEvent) => void
}

export interface DroppableCollectionResult {
Expand Down Expand Up @@ -94,6 +94,7 @@ export function useDroppableCollection(props: DroppableCollectionOptions, state:
onRootDrop,
onItemDrop,
onReorder,
onMove,
acceptedDragTypes = 'all',
shouldAcceptItemDrop
} = localState.props;
Expand Down Expand Up @@ -134,11 +135,15 @@ export function useDroppableCollection(props: DroppableCollectionOptions, state:
await onRootDrop({items: filteredItems, dropOperation});
}

if (target.type === 'item') {
if (target.type === 'item') {
if (target.dropPosition === 'on' && onItemDrop) {
await onItemDrop({items: filteredItems, dropOperation, isInternal, target});
}

if (onMove && isInternal) {
await onMove({keys: draggingKeys, dropOperation, target});
}

if (target.dropPosition !== 'on') {
if (!isInternal && onInsert) {
await onInsert({items: filteredItems, dropOperation, target});
Expand Down Expand Up @@ -750,7 +755,7 @@ export function useDroppableCollection(props: DroppableCollectionOptions, state:
break;
}
}
localState.props.onKeyDown?.(e as any);
localState.props.onKeyDown?.(e);
}
});
}, [localState, ref, onDrop, direction]);
Expand Down
11 changes: 7 additions & 4 deletions packages/@react-aria/dnd/src/useDroppableItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@

import * as DragManager from './DragManager';
import {DroppableCollectionState} from '@react-stately/dnd';
import {DropTarget, RefObject} from '@react-types/shared';
import {DropTarget, FocusableElement, RefObject} from '@react-types/shared';
import {getDroppableCollectionRef, getTypes, globalDndState, isInternalDropOperation} from './utils';
import {HTMLAttributes, useEffect} from 'react';
import {useVirtualDrop} from './useVirtualDrop';

export interface DroppableItemOptions {
/** The drop target represented by the item. */
target: DropTarget
target: DropTarget,
/** The ref to the activate button. */
activateButtonRef?: RefObject<FocusableElement | null>
}

export interface DroppableItemResult {
Expand Down Expand Up @@ -50,10 +52,11 @@ export function useDroppableItem(options: DroppableItemOptions, state: Droppable
isInternal,
draggingKeys
});
}
},
activateButtonRef: options.activateButtonRef
});
}
}, [ref, options.target, state, droppableCollectionRef]);
}, [ref, options.target, state, droppableCollectionRef, options.activateButtonRef]);

let dragSession = DragManager.useDragSession();
let {draggingKeys} = globalDndState;
Expand Down
41 changes: 37 additions & 4 deletions packages/@react-stately/dnd/src/useDroppableCollectionState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export function useDroppableCollectionState(props: DroppableCollectionStateOptio
onRootDrop,
onItemDrop,
onReorder,
onMove,
shouldAcceptItemDrop,
collection,
selectionManager,
Expand Down Expand Up @@ -95,13 +96,32 @@ export function useDroppableCollectionState(props: DroppableCollectionStateOptio

if (acceptedDragTypes === 'all' || acceptedDragTypes.some(type => types.has(type))) {
let isValidInsert = onInsert && target.type === 'item' && !isInternal && (target.dropPosition === 'before' || target.dropPosition === 'after');
let isValidReorder = onReorder && target.type === 'item' && isInternal && (target.dropPosition === 'before' || target.dropPosition === 'after');
let isValidReorder = onReorder
&& target.type === 'item'
&& isInternal
&& (target.dropPosition === 'before' || target.dropPosition === 'after')
&& isDraggingWithinParent(collection, target, draggingKeys);

let isItemDropAllowed = target.type !== 'item'
|| target.dropPosition !== 'on'
|| (!shouldAcceptItemDrop || shouldAcceptItemDrop(target, types));

let isValidMove = onMove
&& target.type === 'item'
&& isInternal
&& isItemDropAllowed;

// Feedback was that internal root drop was weird so preventing that from happening
let isValidRootDrop = onRootDrop && target.type === 'root' && !isInternal;

// Automatically prevent items (i.e. folders) from being dropped on themselves.
let isValidOnItemDrop = onItemDrop && target.type === 'item' && target.dropPosition === 'on' && !(isInternal && target.key != null && draggingKeys.has(target.key)) && (!shouldAcceptItemDrop || shouldAcceptItemDrop(target, types));
let isValidOnItemDrop = onItemDrop
&& target.type === 'item'
&& target.dropPosition === 'on'
&& !(isInternal && target.key != null && draggingKeys.has(target.key))
&& isItemDropAllowed;

if (onDrop || isValidInsert || isValidReorder || isValidRootDrop || isValidOnItemDrop) {
if (onDrop || isValidInsert || isValidReorder || isValidMove || isValidRootDrop || isValidOnItemDrop) {
if (getDropOperation) {
return getDropOperation(target, types, allowedOperations);
} else {
Expand All @@ -111,7 +131,7 @@ export function useDroppableCollectionState(props: DroppableCollectionStateOptio
}

return 'cancel';
}, [isDisabled, acceptedDragTypes, getDropOperation, onInsert, onRootDrop, onItemDrop, shouldAcceptItemDrop, onReorder, onDrop]);
}, [isDisabled, collection, acceptedDragTypes, getDropOperation, onInsert, onRootDrop, onItemDrop, shouldAcceptItemDrop, onReorder, onMove, onDrop]);

return {
collection,
Expand Down Expand Up @@ -187,3 +207,16 @@ function isEqualDropTarget(a?: DropTarget | null, b?: DropTarget | null) {
return b?.type === 'item' && b?.key === a.key && b?.dropPosition === a.dropPosition;
}
}

function isDraggingWithinParent(collection: Collection<Node<unknown>>, target: ItemDropTarget, draggingKeys: Set<Key>) {
let targetNode = collection.getItem(target.key);

for (let key of draggingKeys) {
let node = collection.getItem(key);
if (node?.parentKey !== targetNode?.parentKey) {
return false;
}
}

return true;
}
11 changes: 9 additions & 2 deletions packages/@react-types/shared/src/dnd.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,17 @@ export interface DroppableCollectionUtilityOptions {
*/
onItemDrop?: (e: DroppableCollectionOnItemDropEvent) => void,
/**
* Handler that is called when items are reordered via drag in the source collection.
* Handler that is called when items are reordered within the collection.
* This handler only allows dropping between items, not on items.
* It does not allow moving items to a different parent item within a tree.
*/
onReorder?: (e: DroppableCollectionReorderEvent) => void,
/**
* Handler that is called when items are moved within the source collection.
* This handler allows dropping both on or between items, and items may be
* moved to a different parent item within a tree.
*/
onMove?: (e: DroppableCollectionReorderEvent) => void,
/**
* A function returning whether a given target in the droppable collection is a valid "on" drop target for the current drag types.
*/
Expand All @@ -232,7 +240,6 @@ export interface DroppableCollectionBaseProps {
onDropEnter?: (e: DroppableCollectionEnterEvent) => void,
/**
* Handler that is called after a valid drag is held over a drop target for a period of time.
* @private
*/
onDropActivate?: (e: DroppableCollectionActivateEvent) => void,
/** Handler that is called when a valid drag exits a drop target. */
Expand Down
Loading