Skip to content

Migrate drag and drop from react-dnd to @dnd-kit - #391

Open
ccombe wants to merge 18 commits into
jameskerr:mainfrom
ccombe:migrate-to-dnd-kit
Open

ccombe wants to merge 18 commits into
jameskerr:mainfrom
ccombe:migrate-to-dnd-kit

Conversation

@ccombe

@ccombe ccombe commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Part 1 of the roadmap in #390.

Merge order

  1. Untangle the one circular import and the patterns that add more #400 first. Removes the cycle on main and adds the madge CI guard.
  2. Simplify keyboard handling and dedupe computeDrop branches #399 second. Small keyboard refactor that touches some of the same files.
  3. Migrate drag and drop from react-dnd to @dnd-kit #391 (this PR) last. Rebase onto the updated main once both land; the nine overlapping files resolve by keeping this PR's dnd-kit mechanics alongside Untangle the one circular import and the patterns that add more #400's type imports, factories, and per-store server snapshot.

Summary

Migrates react-arborist from react-dnd to @dnd-kit, and renders drag previews with @dnd-kit's <DragOverlay> instead of a hand-positioned fixed layer.

The preview change is in this PR rather than a follow-up because it is the same subject: what positions a drag. Kept separate, the follow-up was a 6-file diff on top of this one that deleted a test this PR adds, and it could not be reviewed on its own.

Motivation

In #371, @TrevorBurnham suggested swapping out react-dnd for @dnd-kit rather than maintaining compatibility with react-dnd forks. Moving off react-dnd removes the two peer dependencies and the global HTML5 backend singleton conflict (#319).

Review history

The PR went through six review rounds. Each round found a failure the unit suite did not cover, so the fixes and their regression tests are listed in the order they landed.

Round 1: correctness under real drags

Review: #391 review 5729791895. Six blocking items:

  1. A fast drag could drop in the wrong place. onDragStart seeded pointerRef with the activator coordinates, and the move listeners attached in an effect after the next commit. A flick released inside that window measured the target against the start. Approach: attach capture-phase pointer listeners synchronously in onDragStart, keep pointerRef null until a real move, and use activator + delta only for a release with no move. use-drag-handlers.test.ts runs start, move and end in one tick.

  2. A drop could commit to a stale target. updateHover left the previous hover in place when over or the pointer was missing, so onDragEnd dropped where the user had last been. Approach: updateHover returns false, cancels the pending frame, dispatches hovering(null, null) and hides the cursor. onDragEnd only drops when the same event produces a valid target. Tested by leaving droppable space and releasing over nothing.

  3. Possible Improved drag and drop performance #385 regression (row render counts). This was the item Round 1 left open. useDraggable and useDroppable read dnd-kit's InternalContext, whose value includes over, so every visible row re-rendered on a pointer move. Approach: the hooks now live in a thin RowContainer wrapper, and the memoised RowView renders the user's Row and Node and subscribes only to the node, data and destination state it paints. useFreshNode now keys on node data and state values instead of the previous clone, so unrelated renders keep the same node instance. dnd-provider.test.tsx drives a real mouse drag across rows and asserts that a row in another subtree does not render again.

  4. The scroll fix had no test. Added gmail-spec.cy.js: it shrinks the scroll container, starts a drag, holds the pointer in the bottom auto-scroll band, and asserts the drop lands beside the row under the pointer after scrollTop advances. use-drag-handlers.test.ts also verifies that computeDrop measures the pointer, not activator + delta, when dnd-kit's delta contains scroll adjustment.

  5. Touch was not supported. The claim now matches the implementation: the handle uses touch-action: manipulation, the default sensors are MouseSensor (5px distance) and TouchSensor (250ms hold, 5px tolerance), and tests cover a touch hold starting a drag and a swipe scrolling instead. Checked in Chromium touch emulation (390x720): a swipe scrolled the list, a hold followed by a move dragged, and a mouse drag was unaffected.

  6. dragType was dead. Removed dragType and dragTypeForNode from props, code, docs and the changeset.

Non-blocking items from Round 1:

  • Outer droppable registration: outer-drop-hook.ts checks tree.listEl.current after every commit and re-registers when the element changes, covering the fixed/variable list swap and late mounts.
  • Private dependency and docs: @dnd-kit/core is a peer dependency (^6.3.1), both README install lines include it, and the sensors note says the public API tracks the 6.x line.
  • Extra render per row mount: activator listeners attach and detach in the ref callback and dispatch through listenersRef, so there is no useState element and no re-bind per render.
  • Screen-reader announcements: dnd-kit defaults are replaced with pointer-only instructions and announcements using data.name (id fallback). An accessibility prop overrides or suppresses them. Tested in dnd-provider.test.tsx.
  • Redundant preview state: removed the nodes.drag.id fallback and isDragging condition from drag-preview-container.tsx.
  • Leftovers: renamed get-dnd-provider-props.ts to collision-detection.ts, deleted types/dnd.ts and DragItem, and corrected the stale multi-tree comment in tree-api.ts.
  • [Roadmap] Migrate drag-and-drop engine to @dnd-kit & modernize architecture #390: the body now says [Stacked on #391] Use dnd-kit's native DragOverlay for drag previews #392 is folded into Migrate drag and drop from react-dnd to @dnd-kit #391 and lists Support coordinating the tree with an external DndContext #396 as the shared-context follow-up.

Round 2: the fixes themselves

Review: #391 review 5736361132. Five inline threads:

  • Activator listeners only attached at mount. They now come from a fixed list and read listenersRef.current at event time, so a row that mounts disabled starts dragging when it is enabled without re-running the ref callback. Tested.
  • touch-action: none on every row would block scrolling. The handle now uses touch-action: manipulation, paired with the delayed TouchSensor.
  • Both README install lines now include @dnd-kit/core.
  • Peer range raised from ^6.0.0 to ^6.3.1, since only 6.3.1 was tested. Lockfile updated.

Round 3: behaviour bugs and the hand-off details

Review: #391 review 5912631411. Nine inline threads:

  • Drop position after auto-scroll. onDragEnd read the pointer after stopTracking() had already cleared it, so a release fell back to activator + scrollAdjustedTranslate. It reads the pointer first now. Test: the pointer sits on the bottom half of a row while delta points above it, so the two produce different targets.
  • Stale rowIndex in useFreshNode. The clone was memoised on node data and state but not the node's position, so a row kept its old rowIndex after a folder above it moved. original.id and original.rowIndex are in the deps; the regression test opens a folder above a row and asserts the clone's prev follows it.
  • Hover sticking after the pointer leaves. Added TreeApi.clearHover(), which cancels the pending frame and resets hovering, the destination and the cursor in one place. updateHover, onDragEnd and onDragCancel call it, and tree-api.test.ts asserts the three reset together.
  • Drops on rows the user can't see. A row collision is accepted only when the pointer is also inside the outer droppable's rect, so an overscan or partly visible row can't collect a drop outside the scroll container. Two collision tests cover a row that sticks out and the same row when the pointer is inside.
  • Screen-reader instructions not linked to the handle. aria-describedby, aria-roledescription and aria-disabled now go on the row, the element that actually takes focus; dnd-kit's role="button" / tabIndex stay off it so the treeitem keeps focus. Putting them on the handle moved focus on click and broke the Gmail e2e focus assertions, so the row is the deliberate target.
  • Drag preview re-renders. The preview element is memoised on the renderer, id and drag ids, and dragIds itself is memoised so the fallback [id] array keeps its identity. dnd-kit context updates no longer re-run the consumer's renderDragPreview.
  • Touch action. Set only while the row can drag and only when it has no inline touch-action of its own, and the previous value is restored on detach.
  • Custom sensor activators. The bound events are the union of the live listener keys and the built-in fallback, so a sensor that activates on contextmenu works. Tested with a minimal SensorInstance passed through the sensors prop.
  • Local Mouse type. Replaced with the shared XYCoord from types/renderers.ts.
  • Type-import cleanup folded in. c3ebede marks the remaining type-only imports from Untangle the one circular import and the patterns that add more #400's review as types (RootState, NodeApi, TreeProps, OpenMap, and the handlers / renderers namespaces) now that the react-dnd hooks are gone. It replaces a separate stacked PR, so the cleanup ships with the branch that rewrites those files.

Round 4: treeitem ARIA semantics, useFreshNode children refresh, and docs

Review: #391 review 6079134194. Five inline threads fixed in b66a1ee:

  • Treeitem ARIA semantics (row-container.tsx). Dropped aria-roledescription and aria-disabled from rowAttrs, and omitted aria-describedby when !canDragNode(node) (both disableDrag and while editing), so screen readers announce rows as active treeitems rather than "draggable" or disabled. Updated the assertions in dnd-provider.test.tsx.
  • Stale node.children in useFreshNode. Added original.children to useFreshNode's useMemo deps so folder rows refresh when a child updates in place (such as a useSimpleTree rename keeping the folder's data reference unchanged), with the regression test in row-container.test.tsx.
  • Migration notes & README accuracy. Updated .changes/drag-overlay-modernization.md and README.md to state that offset and mouse are no longer passed (undefined) rather than null, and that isDragging is still passed while the preview mounts only during an active drag and always receives true. Restored the Node >=22.12 / require(esm), TypeScript node16/node18 TS1479, and Jest customExportConditions / jsdom / pnpm / --experimental-vm-modules guidance in README.md.

Round 5: RowView derived state, useFreshNode parent, onDragOver, React stopPropagation, and outerRef

Review: #391 review 6098482648. Six inline threads fixed in d87d141:

  • Derived node/tree state in RowView (row-container.tsx). RowViewInner now subscribes to useNodesContext() (while RowContainer passes primitive describedBy and memoised dragListeners instead of the unmemoised dragAttributes object). Derived getters such as node.isOnlySelection, tree.selectedIds.size, tree.dragNodes, and node.parent.isSelected stay current on every node-state change, while RowView still skips re-renders for unrelated rows during dnd-kit InternalContext pointer moves (Improved drag and drop performance #385).
  • Stale node.parent in useFreshNode. Replaced original.parent?.id ?? null with original.parent in useFreshNode's useMemo deps so parent.children, nextSibling, and parent.data refresh after tree rebuilds.
  • One-event drop-indicator lag (use-drag-handlers.ts, provider.tsx). Added an onDragOver handler alongside onDragMove so updateHover runs with the updated event.over as soon as the pointer crosses a row boundary.
  • React stopPropagation() inside dragHandle (drag-hook.ts, row-container.tsx). Replaced native addEventListener attachment with React event props (dragListeners) spread onto rowAttrs, gated on handleElRef.current?.contains(event.target), so a child <button onMouseDown={e => e.stopPropagation()}> stops drags cleanly.
  • Callback ref for the outer droppable (outer-drop-hook.ts, outer-drop.ts, default-container.tsx). Replaced the dependency-less useEffect with an OuterDropRefContext callback ref wired to List's outerRef, so late-mounted containers register OUTER_DROP_ID immediately on mount and clear tree.listEl / droppable state on unmount.
  • TreeProps docs (README.md). Added sensors and accessibility to the TreeProps listing.

Round 6: SSR DndContext id, custom renderContainer outer drop fallback, focus preservation, and docs

Review: #391 review 6100477489. Five inline threads fixed in ca517ee:

  • Deterministic SSR aria-describedby (provider.tsx). Passed const dndId = useId() to <DndKitContext id={dndId}>, avoiding dnd-kit's module-level counter mismatch between server prerender and client hydration. Added a test in dnd-provider.test.tsx.
  • Custom renderContainer outer drop fallback (outer-drop-hook.ts). Kept the OuterDropRefContext callback ref for DefaultContainer's List and restored a fallback useEffect that registers tree.listEl.current when the callback ref was never used, so custom renderContainer components wiring ref={tree.listEl} still support dropping below the last row and list-bounds clipping. Added a test in dnd-provider.test.tsx.
  • Preserving focus when a row element swaps (row-container.tsx). innerRef now focuses the newly mounted element when n !== null && n !== el.current and !node.isEditing && node.isFocused, so custom renderRow components that switch element tags while focused do not drop focus to document.body. Added a test in row-container.test.tsx.
  • Custom renderRow attrs & pointer-only sensors docs (.changes/migrate-to-dnd-kit.md, README.md, types/tree-props.ts). Documented that attrs carries drag-activation listeners (so custom renderRow must spread {...attrs} in full and compose onMouseDown/onTouchStart/onPointerDown/custom sensor handlers), and clarified that sensors supports pointer-based sensors only (MouseSensor, TouchSensor, PointerSensor, or custom pointer/mouse/touch sensors), not KeyboardSensor.

Where the rest of the scope lives

  • #399: keyboard handler extraction, computeDrop dedupe, and Backspace multi-selection focus fallback (folded from Fix focus fallback on Backspace deletion of trailing nodes #402).
  • #400: circular imports, initial-state factories, per-store SSR snapshot, and the madge CI guard. The type-only imports are in this PR (c3ebede).
  • #396: shared or external DndContext. Not supported in this PR.

Version decision

@dnd-kit/core 6.3.1 (Dec 2024) is the target. @dnd-kit/react / @dnd-kit/dom 0.5.x is the maintained line, but it is pre-1.0: its API is still moving, and adopting it would trade one known-stable dependency for an unsettled one. @dnd-kit/core is what the ecosystem uses today and what this component's needs (sensors, droppables, overlay) are already covered by. Revisit at 1.0.

Consumer changes

Breaking

  • react-dnd and react-dnd-html5-backend are removed from peerDependencies; @dnd-kit/core (^6.3.1) joins peerDependencies, so it has to be installed alongside react-arborist.
  • dndBackend, dndManager, dndRootElement, and dragType are removed from TreeProps, not deprecated, so TypeScript flags existing uses.
  • DragPreviewProps loses offset and mouse, which are no longer passed (undefined). With <DragOverlay> positioning the preview, a custom renderDragPreview that positioned itself with offset should stop doing so. id and dragIds are unchanged; isDragging is still passed, though the preview now mounts only during an active drag and always receives true (so a preview that previously animated out on isDragging === false will not get that render).
  • The default sensors are a MouseSensor (5px distance) and a TouchSensor (250ms hold, 5px tolerance). @dnd-kit's KeyboardSensor is not included (since it starts a drag on Space or Enter and would swallow the tree's own keyboard commands, covered by a test on a nested button), and non-pointer sensors passed via sensors are not supported because hover targeting measures live pointer coordinates. The drag handle uses touch-action: manipulation, so a swipe still scrolls the list.
  • Custom renderRow components receive drag-activation event listeners on attrs and must spread {...attrs} in full (composing rather than overwriting attrs.onMouseDown, attrs.onTouchStart, attrs.onPointerDown, or custom sensor activator handlers). Node renderers that only attach ref={dragHandle} keep working unchanged when using the default row renderer or a custom renderRow that spreads attrs.

Capabilities v5 gives up

These depended on react-dnd or native HTML5 drag and drop, and are listed in the changeset as well:

  • Dragging rows onto the host app's react-dnd targets (the drag-out demo), and dropping the app's react-dnd items into the tree. The demo and its Cypress spec are removed with the capability.
  • OS file drops, dragging rows out to other apps or windows, and iframe setups via dndRootElement.
  • dragType: with each tree owning a private DndContext, no external target can read the drag data, so the prop had no observable effect. Removed entirely rather than kept as a dead label.
  • Sharing one <DndContext> across trees, or supplying your own. Every <Tree> owns its context. Tracked in Support coordinating the tree with an external DndContext #396.

Preserved and added

  • ref={dragHandle} keeps working in existing node renderers (when renderRow spreads attrs).
  • renderDragPreview keeps working; only its coordinate props are gone.
  • XYCoord is defined locally as { x: number, y: number } instead of re-exporting react-dnd's.
  • New sensors prop for customising the default pointer sensors (supports pointer-based sensors such as MouseSensor, TouchSensor, PointerSensor, or custom pointer/mouse/touch sensors; the typing tracks @dnd-kit/core 6.x SensorDescriptor<SensorOptions>[]).
  • New accessibility prop for dnd-kit's screen-reader instructions and announcements. The defaults are pointer-only and use node names, matching the fact that keyboard dragging is not part of this PR.

Technical details

  1. Context ownership. TreeProvider always wraps the tree in its own <DndContext>. The useHasParentDndContext probe, the shared-context mode, ExternalDndListener, the treeCollisionDetection export and the drag-out demo are gone; Support coordinating the tree with an external DndContext #396 tracks reintroducing a supported form.
  2. Sensor wiring. src/dnd/use-drag-handlers.ts owns the four dnd-kit callbacks and the pointer state, so TreeProvider stays a wiring component and Support coordinating the tree with an external DndContext #396 has one place to add to.
  3. Pointer tracking and listener timing. event.delta is dnd-kit's scrollAdjustedTranslate, so activator + delta is not the pointer once the list auto-scrolls mid-drag. Capture-phase pointer listeners attach synchronously in onDragStart rather than via a commit-delayed effect, leaving pointerRef null until the first move so flicks measure against activator + delta while real moves track the pointer.
  4. Stale hover cancellation. updateHover returns false and dispatches hovering(null, null) alongside cancelHover() when the pointer leaves droppable space or points to an unmounted row, ensuring onDragEnd drops only on targets valid in that event.
  5. Drop calculation. useDroppable puts the row's element ref on the droppable's data, and computeDrop takes a structural Measurable (any object with getBoundingClientRect) instead of an HTMLElement, so the hover maths runs against the live row with no casts or fabricated elements.
  6. Preview. <DragOverlay dropAnimation={null}> positions the preview; provider.tsx no longer keeps dragPreviewState, and DragPreviewContext is removed.
  7. Listener shim and touch action. drag-hook.ts returns memoised React-level dragListeners spread onto rowAttrs and gated on handleElRef.current?.contains(event.target), so a child's synthetic e.stopPropagation() cancels drags before reaching dnd-kit while keeping RowView memoised. The dragHandle ref callback sets touch-action: manipulation (and restores it on detach) without re-binding listeners on every render; with the delayed TouchSensor, swiping a row scrolls the list and holding still starts the drag.
  8. Droppable registration. outer-drop-hook.ts exposes a callback ref via OuterDropRefContext (read by List's outerRef) so OUTER_DROP_ID registers immediately on mount (including late-mounted renderContainers and FixedSizeList / VariableSizeList swaps) and detaches cleanly on unmount, with a useEffect fallback registering tree.listEl.current when a custom renderContainer does not use DefaultContainer.
  9. Row render isolation. row-container.tsx splits the dnd-kit hooks from the painted row. RowContainer calls useDraggable and useDroppable, which read InternalContext; RowView is memoised, renders the user's Row and Node, and subscribes to useDataUpdates, useNodesContext, and useDestinationUpdates. useFreshNode keeps its clone stable across pointer moves while keying on original.parent, original.children, original.rowIndex, node data, and node state.
  10. Screen readers. provider.tsx passes id={useId()} (for deterministic SSR/hydration aria-describedby ids) and pointer-only accessibility instructions/announcements using data.name; TreeProps.accessibility overrides the defaults.
  11. Packaging and cleanup. @dnd-kit/core joins peerDependencies (^6.3.1); @dnd-kit/utilities joins dependencies. get-dnd-provider-props.ts is renamed to collision-detection.ts, and unused DragItem / types/dnd.ts is removed. The hardcoded webpack alias in showcase/next.config.js is removed.

Verification

  • yarn workspace react-arborist test: 14 suites, 160 tests passing, no console warnings. Covers the disabled-to-enabled drag, a touch hold starting a drag, a touch swipe not starting one, unrelated rows not rendering during a pointer move, useSimpleTree child-rename folder refresh, isOnlySelection multi-select updates, parent / nextSibling freshness after rebuilds, onDragOver hover updates, child stopPropagation, late-mounted and custom renderContainer outer droppable registration, deterministic useId aria-describedby, focus preservation across row element replacement, and the treeitem ARIA / screen-reader attributes.
  • yarn workspace showcase build + xvfb-run yarn workspace e2e test: 4 specs, 20 tests passing (budget, cities, gmail, variable-height). The Cypress drag helpers now drive mouse events, which is what the default mouse sensor listens to.
  • Touch behaviour checked in Chromium with touch emulation (390x720, hasTouch): a swipe across a row scrolled the list and started no drag, a 400ms hold followed by a move started a drag without scrolling, and a plain mouse drag still worked.
  • yarn lint, yarn fmt:check: clean.
  • Rebased onto main at b44e01a (the Budget demo); the demo spec now drops with the shared mouse-based drag helper.
  • madge --circular modules/react-arborist/dist/module/index.js: 1 cycle, the same one main has (data/create-root.js > interfaces/node-api.js). Rebase onto Untangle the one circular import and the patterns that add more #400, which removes it and adds the guard to CI.

Tests added

  • use-drag-handlers.test.ts: measuring against the pointer rather than activator + delta, clearing hover on pointer exit, preventing a drop when the drag ends over null, and updating hover in onDragOver when over switches to a new row.
  • gmail-spec.cy.js: mid-drag auto-scroll test asserting that holding the pointer near the bottom scrolls the list and drops next to the row under the pointer.
  • dnd-provider.test.tsx: virtualisation survival (source row unmounting), Space/Enter on nested buttons, child stopPropagation preventing drag activation, late-mounted renderContainer outer droppable registration and unmount cleanup, custom renderContainer using tree.listEl outer drop fallback, deterministic per-tree aria-describedby ids via useId, pointer-based collision cases, a real drag that must not repaint unrelated rows (Improved drag and drop performance #385), screen-reader instructions and announcements, and treeitem ARIA attribute assertions (aria-describedby only on draggable rows, without aria-roledescription or aria-disabled).
  • row-container.test.tsx: regression tests verifying useSimpleTree child renames refresh the parent folder's node.children, multi-select updates node.isOnlySelection on the existing selection, and focus stays on a row when a custom renderRow replaces its DOM element.
  • use-fresh-node.test.tsx: regression tests for rowIndex updates when a folder opens above a row and for parent.children, nextSibling, and parent.data freshness after tree rebuilds.

Part of #390.

@netlify

netlify Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

👷 Deploy request for react-arborist pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 08ec37f

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the quick turnaround on #390. The scope is right now, and staying on @dnd-kit/core 6.x is a decision I agree with. Folding the DragOverlay work in makes sense too. Each <Tree> owning its own context, use-drag-handlers.ts, the Measurable type, and leaving out KeyboardSensor are all improvements.

I pulled the branch down and read it alongside dnd-kit 6.3.1's source. The unit suite passes warning-clean, but none of the items below are covered by it.

Blocking

1. A fast drag can drop in the wrong place (use-drag-handlers.ts, onDragStart)
onDragStart seeds pointerRef with the activator's coordinates, so mouseFrom never takes its activator + delta fallback. The pointermove/mousemove/touchmove listeners are attached in a useEffect keyed on dragId, which only runs after the next commit. If the user flicks to another row and releases within that window, computeDrop measures the target row against the starting coordinates and the drop lands somewhere else. Attaching the listeners synchronously in onDragStart (or leaving pointerRef null until the first real move) would close the gap.

2. A drop can commit to a stale target (use-drag-handlers.ts, updateHover)
When hoverTarget() returns null (for example, a row whose element ref was cleared because react-window unmounted it during auto-scroll) or there's no pointer position, updateHover returns without clearing the pending hover. onDragEnd then calls canDrop()/drop() against whatever was hovered on an earlier move, and onMove gets a destination the user wasn't over. That case should cancel the hover instead.

3. Possible regression of #385
Every row calls useDraggable and useDroppable, and in 6.3.1 both read dnd-kit's InternalContext, whose value includes over. So whenever the pointer crosses into a new row, every visible row re-renders, regardless of useDestinationUpdates. The #385 tests drive tree.hover() directly, so they wouldn't catch this. Could you add a render-count test (or profiler numbers) for a real drag across several rows, compared with main? If it does regress, the fix is probably to keep the dnd-kit hooks out of the row's render path.

4. The scroll fix has no test
You confirmed the delta skew, but as the PR body says, the fix lost its only assertion. A Cypress test that auto-scrolls mid-drag and checks where the node lands should be part of this PR. It would also confirm that rows mounted during the scroll register as drop targets.

5. Touch isn't actually supported
The README now advertises desktop and mobile support, but drag handles never get touch-action: none, which dnd-kit's PointerSensor needs on touch devices. Without it the browser should start scrolling and fire pointercancel before the 5px activation distance is reached. Please either set it on the handle (and verify on a real device or emulator) or drop the claim.

6. dragType is dead
With every tree owning a private DndContext, nothing outside the tree can read the drag data, so dragType has no observable effect. The new doc comment ("so rows can be dropped onto external drop targets") is wrong. Since this is the major that removes dndBackend and friends, please remove dragType (and dragTypeForNode) too, and bring it back with #396 if that needs it.

Non-blocking (fine here or as a follow-up)

  • Outer droppable registration (outer-drop-hook.ts): it's registered once in a mount effect and never updated. Switching rowHeight between a number and a function swaps FixedSizeList for VariableSizeList and mounts a new outer element, which breaks dropping below the last row. A renderContainer that mounts the list late never registers it at all. Wiring setNodeRef into the outer ref would fix both.
  • @dnd-kit/core as a private dependency: the README tells consumers to import useSensors/PointerSensor from @dnd-kit/core. With it as a regular dependency, a consumer on a different range gets two copies. The hard-coded alias in showcase/next.config.js looks like the same symptom, and it won't survive pnpm or PnP. Either make it a peer or re-export the sensor helpers. Related: typing sensors with dnd-kit's own types ties the public API to 6.x, which I'm OK with, but let's say so in the docs.
  • Extra render per row mount (drag-hook.ts): storing the handle element in useState means every row renders twice on mount, and react-window mounts rows constantly while scrolling. An unmemoized sensors prop also makes every row re-bind its listener on every render. Attaching and detaching inside the ref callback, dispatching through listenersRef, avoids both.
  • Screen-reader announcements: DndContext uses dnd-kit's defaults, which announce Space-bar drag instructions that don't work here and read raw node IDs aloud. Please pass accessibility with pointer-only instructions and announcements that use node names, or suppress them.
  • Redundant preview state (drag-preview-container.tsx): DragOverlay only renders children while active is set, so the nodes.drag.id fallback and isDragging never change the output.
  • Leftovers: get-dnd-provider-props.ts now only holds treeCollisionDetection and should be renamed. DragItem in types/dnd.ts has no users. The comment in tree-api.ts about a tree receiving a drag from another tree describes something that can't happen anymore.
  • #390: the issue body still lists #392 as an out-of-scope follow-up. It's folded in here, so please update it.

@ccombe
ccombe requested a review from TrevorBurnham November 2, 2026 05:44
@ccombe

ccombe commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and specific pointers. All six blocking items and several non-blocking items are addressed in the latest push (commits 983f648, ef7dd07, and 23fc8b8).

Here is a breakdown of what was changed and verified.

Blocking items

1. Fast drag drop target timing (use-drag-handlers.ts)

  • Listeners for pointermove, mousemove, and touchmove are now attached synchronously in onDragStart rather than waiting for a commit-delayed useEffect.
  • pointerRef stays null until the first real move event arrives. If a quick flick releases without an intervening move, mouseFrom still measures against activator + delta. Once a move fires, the native coordinates take over.
  • Added a unit test in use-drag-handlers.test.ts where onDragStart, the pointer move, and onDragMove run in the same tick.

2. Stale hover target cancellation (use-drag-handlers.ts)

  • updateHover now returns a boolean indicating whether a valid hover target was found and measured.
  • When over or mouse is null, or when hoverTarget cannot resolve a live element (for example, a row unmounted by react-window), updateHover immediately cancels the pending animation frame via api.cancelHover(), clears the committed hover in the store via dndActions.hovering(null, null), and calls api.hideCursor().
  • onDragEnd drops only when updateHover returns true and api.canDrop() passes.
  • Tested in use-drag-handlers.test.ts: exiting droppable space clears hover state in the store, and releasing over nothing does not call api.drop().

3. Render count and #385 inquiry

  • Added a render count probe measuring a drag across rows on a 100-node tree with 11 visible rows over 5 move events.
  • Results: 130 total row renders across the sequence, with a maximum of 20 renders on any single row (approximately 2.4 renders per visible row per move).
  • Note on comparison: I could not run a direct side-by-side comparison with main because main runs react-dnd with an HTML5 backend that cannot be driven by the same synthetic pointer events in jsdom.
  • The numbers confirm that visible rows re-render as InternalContext updates during drag moves. Keeping dnd-kit hooks entirely out of the row render path (or introducing deeper row memoization) would be a larger structural change. Let me know if you would like that refactor in this PR or tackled as a follow-up.

4. Mid-drag scroll test

  • Added an e2e Cypress test in modules/e2e/cypress/e2e/gmail-spec.cy.js ("drops beside the row under the pointer after the list auto-scrolls mid-drag").
  • The test shrinks the scroll container, starts a drag from a row, moves the pointer into the bottom auto-scroll threshold band, holds position while dnd-kit's auto-scroller advances scrollTop, and drops. It asserts that the drop lands beside the row positioned under the pointer at drop time.
  • In use-drag-handlers.test.ts, a companion unit test verifies that computeDrop measures against pointer coordinates rather than activator + delta when delta contains scroll offset adjustments. That test fails if pointer tracking is disabled.

5. Touch support and touch-action

  • Added touch-action: none to the drag handle element in drag-hook.ts.
  • Note: verified in headless Cypress and jsdom test runs. I do not have access to a physical touch device in this test environment to run manual validation on real hardware.

6. Removal of dragType

  • Removed dragType and dragTypeForNode completely: removed from TreeProps, deleted helper and unit tests, and removed all mentions from README.md and .changes/migrate-to-dnd-kit.md.

Non-blocking items addressed

  • Outer droppable registration (outer-drop-hook.ts): The hook now checks tree.listEl.current on commit and updates droppable registration when the element reference changes (for example, when switching between FixedSizeList and VariableSizeList or on late list mount).
  • Peer dependency (package.json): Moved @dnd-kit/core to peerDependencies (^6.0.0) alongside react and react-dom, and added it to showcase/package.json. The hardcoded webpack alias in showcase/next.config.js has been removed.
  • Ref callback listener attach (drag-hook.ts): Moved listener attachment and detachment into the dragHandle ref callback, dispatching via listenersRef. This eliminates the double-render per row on mount caused by useState, and stops listeners from re-binding on each render.
  • Redundant preview state (drag-preview-container.tsx): Removed nodes.drag.id fallback and conditional rendering. DragOverlay already controls visibility based on active state.
  • Renames and cleanups: Renamed get-dnd-provider-props.ts to collision-detection.ts, deleted unused DragItem type and types/dnd.ts, and updated the stale multi-tree comment in tree-api.ts.
  • Sensors typing in docs: README.md now explicitly notes that the sensors prop typing tracks @dnd-kit/core 6.x.
  • [Roadmap] Migrate drag-and-drop engine to @dnd-kit & modernize architecture #390 issue body: Confirmed that the roadmap in [Roadmap] Migrate drag-and-drop engine to @dnd-kit & modernize architecture #390 already reflects [Stacked on #391] Use dnd-kit's native DragOverlay for drag previews #392 as folded into Migrate drag and drop from react-dnd to @dnd-kit #391.

Open for preference

  • Screen reader announcements: Currently using dnd-kit defaults. We can add custom announcements using node names if you would like that included in this PR.

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I've left another round of review. Also, you'll need to rebase to resolve conflicts.

Comment thread README.md Resolved
Comment thread README.md Resolved
Comment thread modules/react-arborist/package.json Resolved
Each Tree now always owns its DndContext. Removes the parent-context
detection that relied on dnd-kit's internal noop stubs, the
treeCollisionDetection export, and the dndBackend/dndManager/
dndRootElement props. Deletes the drag-out showcase and its spec, which
depended on sharing one context with the app.

Tracks the real pointer during a drag instead of deriving it from
activator coordinates plus event.delta, which dnd-kit folds scroll
adjustments into. Defaults to a pointer sensor only: KeyboardSensor
started a drag on Space or Enter, swallowing the tree's own commands.
The drag listeners now receive the target and event methods the
activators touch.

Adds tests for a scroll mid-drag, a source row unmounting during a drag,
and Space/Enter on a nested button.
The fixed-layer preview and its per-move coordinate math are gone; DragOverlay
positions the preview. DragPreviewProps loses offset and mouse, which can no
longer be non-null, and the README says what a custom preview should stop doing.
- All drag sensor wiring now lives in one `useDragHandlers` hook instead of
  inline in TreeProvider, which drops the provider's cognitive complexity and
  gives the next change (jameskerr#396) one place to hook into.
- Hover resolution uses the hovered row's real element instead of fabricating
  one from `over.rect`, and computeDrop takes a structural `Measurable` rather
  than `HTMLElement`, so `measure-hover.ts` is no longer needed.
- getEventCoordinates is handed the event directly, with no `as MouseEvent`.
- Both Cypress specs share one dragAndDrop helper.
- The showcase no longer declares @dnd-kit dependencies it never imports.
Address the review findings on the dnd-kit migration.

- Track the pointer natively from onDragStart instead of an effect keyed on
  dragId: an effect runs after the next commit, so a drag that starts and
  releases quickly was still measured against the activator coordinates.
  dnd-kit adds the list's scroll offset to the drag delta, so the pointer
  position is the only reliable reference for the drop maths.
- Drop only on a target found in the drag-end event. updateHover now reports
  whether it found one and clears both the pending frame and the committed
  hover when it did not, so a row react-window unmounted under the pointer
  can't collect the drop.
- Attach pointer listeners in the drag handle's ref callback instead of an
  effect, and stop holding the handle element in state: that renders every
  row twice on mount and re-binds listeners on every render.
- Set touch-action: none on the drag handle, otherwise the browser scrolls
  and fires pointercancel before PointerSensor can activate.
- Remove the dragType prop. Each tree owns a private DndContext, so no
  external target can read the drag data and the prop did nothing.
- Re-register the outer droppable when its element changes, which happens
  when rowHeight switches between a number and a function.
- Rename get-dnd-provider-props.ts to collision-detection.ts, drop the
  unused DragItem type, and simplify the drag preview container.

Tests: a useDragHandlers unit test covers measuring from the pointer rather
than the drag delta, clearing the hover, and not dropping with no target; a
Cypress test drags through a list that auto-scrolls mid-drag and asserts the
drop lands beside the row under the pointer.
Move @dnd-kit/core to peerDependencies (^6.0.0) alongside react and
react-dom, and add it to showcase dependencies. This removes the
hardcoded webpack resolution aliases in showcase/next.config.js and
prevents duplicate package copies when consumers use custom sensors.
Address the second review round on jameskerr#391:

- Attach the activator events from a fixed list and dispatch through
  listenersRef at event time, so a row that mounted with drag disabled
  picks drag up once it is enabled. Adds the disableDrag repro as a test.
- Replace PointerSensor with MouseSensor plus a TouchSensor that starts
  after a 250ms hold, and use touch-action: manipulation instead of none.
  A swipe across a row scrolls the list again; a press and hold drags.
- Raise the @dnd-kit/core peer range to ^6.3.1, the version tested.
- Add @dnd-kit/core to both install lines in the README.
- Drive the e2e drag helper, the gmail auto-scroll spec and the budget
  drag with mouse events, since the default sensor no longer listens to
  pointer events.
@ccombe
ccombe force-pushed the migrate-to-dnd-kit branch from 23fc8b8 to 89a0500 Compare November 3, 2026 05:49
@ccombe

ccombe commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the second round. Both blocking items are fixed in 89a0500, and the branch is rebased onto main at b44e01a, so the conflicts are gone. Every inline thread above is answered and resolved.

Listener attach (drag-hook.ts)
The activator events now come from a fixed list (pointerdown, mousedown, touchstart, keydown) and dispatch through listenersRef.current at event time. Enabling or disabling a row only changes what the ref holds, so no ref callback re-run is needed. Your repro is now a test in dnd-provider.test.tsx: render with disableDrag, re-render without it, then drag a row. It fails on the previous head and passes here.

Touch and touch-action
Switched to the documented approach:

  • MouseSensor with a 5px distance constraint for mouse
  • TouchSensor with a 250ms delay and 5px tolerance for touch
  • touch-action: manipulation on the handle instead of none

I checked this in Chromium with touch emulation (390x720, hasTouch) on the cities demo:

  • swipe across a row: the list scrolls (scrollTop 0 to 135) and no drag starts
  • press and hold 400ms, then move: a drag starts and the list does not scroll
  • plain mouse drag: still starts a drag

Two jsdom tests cover the hold and the swipe so a future change to the sensors fails loudly.

Smaller items

  • Peer range is ^6.3.1, the version the tests run against.
  • Both README install lines now include @dnd-kit/core, including the v5 migration example.
  • The custom sensors example shows the mouse plus delayed touch wiring.
  • Rebase brought in the Budget demo, whose spec drove HTML5 drag events, which dnd-kit does not listen to. It now uses the shared drag helper, and that helper drives mouse events for all specs.

Verification on 89a0500: 13 suites / 140 unit tests, 4 specs / 20 e2e tests, lint and fmt clean, library and showcase builds clean.

Still open from the first round, no action taken: screen reader announcements use dnd-kit defaults. Happy to add node-name announcements if you want them in this PR.

@ccombe
ccombe requested a review from TrevorBurnham November 7, 2026 08:13
useDraggable and useDroppable read dnd-kit's InternalContext, which changes
whenever the hovered target moves. Calling them in RowContainer meant every
visible row re-rendered on a pointer move (jameskerr#385). Move them into a thin
wrapper and let the memoised row body subscribe only to the node and
destination state it paints.

Make useFreshNode's memo key depend on node data and state values rather than
the previous clone, so unrelated renders keep the same node instance and the
new memo boundary can bail out.

Pass dnd-kit accessibility defaults with pointer-only instructions and
announcements using data.name, and expose an accessibility prop to override
them.

Tests: a real drag across rows asserts unrelated rows do not re-render; the
live region announces node names and no Space-bar instructions.
@ccombe

ccombe commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 628cb22, which closes the two items the earlier reply left open:

  • Improved drag and drop performance #385 render counts. The dnd-kit hooks (useDraggable and useDroppable) now sit in a thin RowContainer wrapper, and the memoised row body does the painting. A real mouse drag across rows no longer re-renders rows in another subtree; dnd-provider.test.tsx asserts that. useFreshNode now keys on node data and state rather than the previous clone, which is what lets the memoised body bail out.
  • Screen readers. DndContext now gets pointer-only instructions and announcements built from data.name (falling back to the id), with a new accessibility prop to override or suppress them. A test checks the live region says Picked up Root. and that the instructions do not mention Space.

The PR description now records the review sequence and the approach for each item. Local verification: 13 suites and 142 unit tests warning-clean, 4 e2e specs and 20 tests, lint, fmt and both builds clean.

- Replace `as { name?: unknown }` in `nodeName` with safe `'in'` narrowing.
- Make `StandaloneDndContext` generic `<T>` instead of using `any` for tree and treeProps.
- Make `useDropHook` generic `<T>` instead of taking `NodeApi<any>`.

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reviewed this against dnd-kit 6.3.1's source. The first three inline comments are behaviour bugs: the drop position after auto-scroll, outdated rowIndex in useFreshNode, and the drop highlight sticking after the pointer leaves the tree. The next two (drops on rows the user can't see, and screen-reader instructions not linked to the handle) also seem worth fixing in this PR. The rest are minor.

@ccombe

ccombe commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

All nine threads from the last round are answered and resolved in b6adf13. In short: onDragEnd measures the pointer before teardown, useFreshNode is keyed on id + rowIndex, TreeApi.clearHover() resets hover/destination/cursor together, row collisions are clipped to the list rect, the descriptive ARIA attributes sit on the row (the focusable element) with dnd-kit's role/tabIndex left to the tree, the drag preview is memoised, touch-action is only touched when the row can drag, custom sensor activators are bound through the union, and the local Mouse type is gone.

Verified locally: yarn workspace react-arborist test 14 suites / 151 tests, warning-clean; lint and fmt:check clean; library + showcase build; all 4 Cypress specs (20 tests) pass. test and changeset are green on b6adf13. Ready for another look.

@ccombe
ccombe requested a review from TrevorBurnham November 16, 2026 22:38
Folds the follow-up from jameskerr#400's review into this branch now that the
react-dnd hooks are gone: RootState in context, NodeApi in create-list,
TreeProps in initial state, and OpenMap plus the handlers and renderers
namespaces in tree props.
@ccombe

ccombe commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Added c3ebede (import lines only): the remaining type-only imports from #400's review now live here instead of a separate stacked PR. That is RootState in context.ts, NodeApi in create-list.ts, TreeProps in initial.ts, and OpenMap plus the handlers/renderers namespaces in tree-props.ts. The react-dnd-specific ones became moot once this branch removed those hooks.

Verified on c3ebede: 14 suites / 151 tests, lint and fmt clean, yarn build succeeds.

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this migration. The main things to fix before merging are the screen reader regressions from dnd-kit's attributes on the treeitem, and a stale node.children regression in useFreshNode. The comment on that one includes a test that passes on main and fails here. The rest are accuracy fixes to the migration notes and README.

Comment thread .changes/drag-overlay-modernization.md Resolved
Comment thread README.md Resolved
@ccombe
ccombe requested a review from TrevorBurnham November 27, 2026 21:36
@ccombe

ccombe commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

All five review threads from the latest round are addressed and resolved in b66a1ee, and the PR description has been updated to match:

  • Treeitem ARIA attributes (row-container.tsx): dropped aria-roledescription and aria-disabled from rowAttrs, and omitted aria-describedby when !canDragNode(node) (covering both disableDrag and editing). Updated the assertions in dnd-provider.test.tsx.
  • Stale node.children (use-fresh-node.ts): added original.children to the useMemo deps so folder rows refresh when a child updates in place (e.g. useSimpleTree rename), with the regression test added to row-container.test.tsx.
  • Migration notes & README (.changes/drag-overlay-modernization.md, README.md): updated offset/mouse wording to state they are no longer passed (undefined), noted that the preview mounts only during an active drag and always receives isDragging: true, and restored the Node >=22.12 / require(esm), TypeScript node16/node18 TS1479, and Jest customExportConditions / jsdom / pnpm / --experimental-vm-modules guidance.

Verification on b66a1ee: yarn workspace react-arborist test 14 suites / 152 tests passing with no console warnings, yarn workspace react-arborist build, yarn lint, and yarn fmt:check clean, and GitHub Build & Test + Changeset checks are green.

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed at b66a1ee. Two important issues, both from the new row memoisation (RowView + the narrower useFreshNode key), and four nits, inline.

One of the nits (the drop-indicator lag in onDragMove) is reproduced in the showcase. The others come from reading the code. I also checked whether dnd-kit's stored droppable rects go stale during auto-scroll: they don't, because dnd-kit's Rect getters re-apply the scroll delta of the element's scroll ancestors on every read, so pointerWithin hit-tests against current positions.

Comment thread README.md Resolved
…er lag, stopPropagation, and outer droppable ref
@ccombe

ccombe commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

All six review threads from the latest round are addressed and resolved in d87d141, and the PR description has been updated to match:

  • Derived state in RowView (row-container.tsx): RowViewInner now subscribes to useNodesContext() (while RowContainer passes primitive describedBy and memoised dragListeners instead of dragAttributes). Derived getters such as node.isOnlySelection, tree.selectedIds.size, tree.dragNodes, and node.parent.isSelected stay current on node-state changes while unrelated rows still skip re-renders during pointer moves (Improved drag and drop performance #385).
  • useFreshNode parent freshness (use-fresh-node.ts): replaced original.parent?.id ?? null with original.parent in useMemo deps so parent.children, nextSibling, and parent.data update after rebuilds.
  • Immediate onDragOver hover updates (use-drag-handlers.ts, provider.tsx): added onDragOver to useDragHandlers and wired it into <DndKitContext> so the drop cursor updates on the same tick over switches rows.
  • React stopPropagation() inside dragHandle (drag-hook.ts, row-container.tsx): replaced native addEventListener attachment with memoised React event props (dragListeners) spread onto rowAttrs and gated on handleElRef.current?.contains(event.target).
  • Callback ref for the outer droppable (outer-drop-hook.ts, outer-drop.ts, default-container.tsx): replaced the dependency-less useEffect with an OuterDropRefContext callback ref wired to List outerRef, registering OUTER_DROP_ID on mount (including late-mounted containers) and clearing on unmount.
  • TreeProps docs (README.md): added sensors and accessibility to the TreeProps interface listing.

Verified locally on d87d141: yarn workspace react-arborist build clean, yarn workspace react-arborist test 14 suites / 157 tests passing with no console warnings, yarn lint and yarn fmt:check clean.

@ccombe
ccombe requested a review from TrevorBurnham November 28, 2026 19:10

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up review at d87d141. Thanks for the quick turnaround: the six earlier points all look addressed.

There are four important issues and a nit, inline. Two of them are side effects of the earlier fixes: custom containers no longer register the end-of-list drop zone, and the drag listeners now depend on the row renderer forwarding attrs. I reproduced the SSR aria-describedby mismatch and the non-pointer-sensor drop failure in the showcase, and the details are in those comments. The other three come from reading the code.

…cus preservation on row element swap, and docs
@ccombe

ccombe commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

All five review threads from the latest round are addressed and resolved in ca517ee, and the PR description has been updated to match:

  • Deterministic SSR aria-describedby (provider.tsx): passed const dndId = useId() to <DndKitContext id={dndId}> so server prerenders and client hydration generate matching aria-describedby ids.
  • Custom renderContainer outer drop fallback (outer-drop-hook.ts): kept the OuterDropRefContext callback ref for DefaultContainer and added a useEffect fallback that registers tree.listEl.current when the callback ref is unused, restoring end-of-list drops and collision clipping for custom containers wiring ref={tree.listEl}.
  • Focus preservation across row element swaps (row-container.tsx): innerRef now focuses the newly mounted element when n !== null && n !== el.current and !node.isEditing && node.isFocused.
  • renderRow attrs & pointer-only sensors docs (.changes/migrate-to-dnd-kit.md, README.md, types/tree-props.ts): documented that attrs carries drag-activation listeners (requiring custom renderRow to spread {...attrs} in full and compose pointer/mouse/touch/custom activator handlers) and that sensors supports pointer-based sensors only (not non-pointer sensors such as KeyboardSensor).

Verified locally on ca517ee: yarn workspace react-arborist build clean, yarn workspace react-arborist test 14 suites / 160 tests passing with no console warnings, yarn lint and yarn fmt:check clean.

# Conflicts:
#	modules/e2e/cypress/e2e/drag-out-spec.cy.js
@ccombe
ccombe requested a review from TrevorBurnham November 29, 2026 03:15

@TrevorBurnham TrevorBurnham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Third pass at 08ec37f. Thanks again: the SSR id, focus restoration, attrs docs and pointer-only sensors docs from the last round all look good.

Four findings, all reproduced at this head (one important, three nits), inline. Repro details are in each comment.

I also re-checked a concern that keeps coming up: that treeCollisionDetection could pick the wrong row while the list auto-scrolls. It can't. dnd-kit's stored droppable rects re-apply their scroll ancestors' offset on every read, and pointerCoordinates (activator + sensor translate) is in viewport space, so the hit-test agrees with the native pointer that computeDrop uses.

drop(tree.listEl);
/* Fallback for custom renderContainer implementations that attach
tree.listEl directly instead of rendering DefaultContainer. */
useEffect(() => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Important (reproduced): the custom-container fallback stops tracking the list element. callbackUsedRef is set once and never reset. This effect also only runs when OuterDrop re-renders, and since it's a stable child of TreeProvider, store-driven updates skip it. I probed dnd-kit's droppable registry (via useDndContext) from a scratch showcase page at 08ec37f:

Scenario Outer droppable node
Default container the list ✅
Switch to a custom renderContainer (ref={tree.listEl}) null: callbackRef(null) cleared it and the fallback now always returns early
…then the custom container swaps its list element still null
Custom container from the first mount its element ✅
…then it swaps its list element (internal state, no new Tree props) the detached old element

In each broken case, dropping in the empty space below the last row finds no target, and the list-bounds clipping in treeCollisionDetection has no outer rect.

Caveat on impact: useTreeApi and RowContainer aren't public exports (in v4 either), so a custom container can only reach tree.listEl through the Tree ref, and can't render draggable rows of its own. My probe used a test-only deep import. If custom containers aren't really meant to do DnD, documenting that may be simpler than making the fallback robust. If they are, registering from wherever tree.listEl is assigned (or exposing the callback ref publicly) and resetting callbackUsedRef on null would cover these cases.

swipe still scrolls the list. Screen-reader instructions are pointer-only and announcements use
node names; the new `accessibility` prop overrides them.

This drops capabilities that depended on `react-dnd` and native HTML5 drag and drop:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (reproduced): this body will produce a malformed CHANGELOG and GitHub release. bin/release.mjs renders each changeset as one bullet, - ${body} (#PR), and .changes/README.md says the body is the bullet text. I ran the script's own readChangesets/renderSection on this branch's .changes/. In the resulting Breaking Changes section:

  • the three items below become top-level bullets, siblings of the real entries, with no PR link;
  • "This drops capabilities…" and the closing "dndBackend, dndManager…" paragraph fall outside the bullet;
  • the (#391) suffix lands after "is tracked in Support coordinating the tree with an external DndContext #396." instead of on the main entry.

Fix: indent the continuation paragraphs and the sub-list by two spaces so they nest under the bullet, or cut the body to a single paragraph and move the detail to the README migration notes.

<div
className="selected-count"
style={{
position: "absolute",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (reproduced): the multi-select count badge sits far from the pointer. The badge is position: absolute; top: 4; right: 4, but .row.preview has no positioning, so it's placed against DragOverlay's wrapper, which is as wide as the dragged row. Before, it was drawn at pointer + 10px.

In the gmail showcase I dragged a 3-row selection with the pointer at x=100: the "3" badge rendered at x=284, at the right edge of the preview, directly against the dragged row's own "14" unread count (it reads "14 3").

Fix: give the preview root position: relative and place the badge near the leading edge or next to the label.

);

const dndId = useId();
const sensors = treeProps.sensors ?? defaultSensors;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (reproduced): an unstable sensors value re-renders every row on every parent render, including the README's own example. sensors is a Tree prop, so a new array changes Object.values(treeProps), which runs api.update() and bumps DataUpdatesContext, and every RowView re-renders. dnd-kit's useSensor memoises on [sensor, options], so inline options objects give a new descriptor, and useSensors gives a new array, on each render.

Measured on a 5-row tree: Node renders across 3 parent re-renders (dev, so StrictMode doubles them):

sensors Node renders
omitted 0
useSensors(useSensor(MouseSensor, OPTS), …) with module-level options 0
README "Custom sensors" example (inline options) 30
inline array [useSensor(…)] 30

Suggest hoisting the options in the README example and documenting that sensors should be referentially stable, and/or stabilising it internally (e.g. keying on each descriptor's sensor class and options) so it doesn't defeat the row memoisation from #385.

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