Skip to content

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

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

ccombe wants to merge 14 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 eight overlapping files resolve by keeping this PR's dnd-kit mechanics and Untangle the one circular import and the patterns that add more #400's type imports and factories.

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 three 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.

Where the rest of the scope lives

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. With <DragOverlay> positioning the preview, those values would always be null; a custom renderDragPreview that positioned itself with offset should stop doing so. id, dragIds and isDragging are unchanged.
  • 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). The drag handle uses touch-action: manipulation, so a swipe still scrolls the list.

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 row renderers.
  • 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 defaults. The README notes that the typing tracks @dnd-kit/core 6.x, with an example of the default mouse and touch wiring.
  • 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 attaches the activator events (pointerdown, mousedown, touchstart, keydown) inside the ref callback rather than an effect, avoiding double-renders on mount and re-binding on render. The events are a fixed list and dispatch through listenersRef.current at event time, so a row that mounted with drag disabled starts dragging once it is enabled without re-running the ref callback. The handle sets touch-action: manipulation; with the delayed TouchSensor, swiping a row scrolls the list and holding still starts the drag.
  8. Droppable registration. outer-drop-hook.ts checks the element ref on commit and updates droppable registration when rowHeight toggles between fixed and variable lists.
  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 only to node, data and destination state. useFreshNode keeps its clone stable across unrelated renders by keying on node data and state values instead of the previous clone.
  10. Screen readers. provider.tsx passes dnd-kit accessibility with pointer-only instructions and 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, 151 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, and the screen-reader text.
  • 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, and preventing a drop when the drag ends over null.
  • 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, pointer-based collision cases, a real drag that must not repaint unrelated rows (Improved drag and drop performance #385), and the screen-reader instructions and announcements.

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 c3ebede

@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.

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