Repository navigation
Conversation
👷 Deploy request for react-arborist pending review.Visit the deploys page to approve it
|
c63a326 to
2cb8e28
Compare
TrevorBurnham
left a comment
There was a problem hiding this comment.
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. SwitchingrowHeightbetween a number and a function swapsFixedSizeListforVariableSizeListand mounts a new outer element, which breaks dropping below the last row. ArenderContainerthat mounts the list late never registers it at all. WiringsetNodeRefinto the outer ref would fix both. @dnd-kit/coreas a private dependency: the README tells consumers to importuseSensors/PointerSensorfrom@dnd-kit/core. With it as a regular dependency, a consumer on a different range gets two copies. The hard-coded alias inshowcase/next.config.jslooks like the same symptom, and it won't survive pnpm or PnP. Either make it a peer or re-export the sensor helpers. Related: typingsensorswith 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 inuseStatemeans every row renders twice on mount, and react-window mounts rows constantly while scrolling. An unmemoizedsensorsprop also makes every row re-bind its listener on every render. Attaching and detaching inside the ref callback, dispatching throughlistenersRef, avoids both. - Screen-reader announcements:
DndContextuses dnd-kit's defaults, which announce Space-bar drag instructions that don't work here and read raw node IDs aloud. Please passaccessibilitywith pointer-only instructions and announcements that use node names, or suppress them. - Redundant preview state (
drag-preview-container.tsx):DragOverlayonly renders children whileactiveis set, so thenodes.drag.idfallback andisDraggingnever change the output. - Leftovers:
get-dnd-provider-props.tsnow only holdstreeCollisionDetectionand should be renamed.DragItemintypes/dnd.tshas no users. The comment intree-api.tsabout 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.
|
Thanks for the thorough review and specific pointers. All six blocking items and several non-blocking items are addressed in the latest push (commits Here is a breakdown of what was changed and verified. Blocking items1. Fast drag drop target timing (
|
TrevorBurnham
left a comment
There was a problem hiding this comment.
I've left another round of review. Also, you'll need to rebase to resolve conflicts.
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.
23fc8b8 to
89a0500
Compare
|
Thanks for the second round. Both blocking items are fixed in Listener attach ( Touch and
I checked this in Chromium with touch emulation (390x720,
Two jsdom tests cover the hold and the swipe so a future change to the sensors fails loudly. Smaller items
Verification on 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. |
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.
|
Pushed
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
left a comment
There was a problem hiding this comment.
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.
|
All nine threads from the last round are answered and resolved in Verified locally: |
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.
|
Added Verified on |
TrevorBurnham
left a comment
There was a problem hiding this comment.
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.
…ldren refresh, and docs
|
All five review threads from the latest round are addressed and resolved in
Verification on |
TrevorBurnham
left a comment
There was a problem hiding this comment.
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.
…er lag, stopPropagation, and outer droppable ref
|
All six review threads from the latest round are addressed and resolved in
Verified locally on |
TrevorBurnham
left a comment
There was a problem hiding this comment.
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
|
All five review threads from the latest round are addressed and resolved in
Verified locally on |
# Conflicts: # modules/e2e/cypress/e2e/drag-out-spec.cy.js
TrevorBurnham
left a comment
There was a problem hiding this comment.
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(() => { |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
Part 1 of the roadmap in #390.
Merge order
mainand adds the madge CI guard.mainonce 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-arboristfromreact-dndto@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-dndfor@dnd-kitrather than maintaining compatibility withreact-dndforks. Moving offreact-dndremoves 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:
A fast drag could drop in the wrong place.
onDragStartseededpointerRefwith 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 inonDragStart, keeppointerRefnull until a real move, and useactivator + deltaonly for a release with no move.use-drag-handlers.test.tsruns start, move and end in one tick.A drop could commit to a stale target.
updateHoverleft the previous hover in place whenoveror the pointer was missing, soonDragEnddropped where the user had last been. Approach:updateHoverreturns false, cancels the pending frame, dispatcheshovering(null, null)and hides the cursor.onDragEndonly drops when the same event produces a valid target. Tested by leaving droppable space and releasing over nothing.Possible Improved drag and drop performance #385 regression (row render counts). This was the item Round 1 left open.
useDraggableanduseDroppableread dnd-kit'sInternalContext, whose value includesover, so every visible row re-rendered on a pointer move. Approach: the hooks now live in a thinRowContainerwrapper, and the memoisedRowViewrenders the user's Row and Node and subscribes only to the node, data and destination state it paints.useFreshNodenow keys on node data and state values instead of the previous clone, so unrelated renders keep the same node instance.dnd-provider.test.tsxdrives a real mouse drag across rows and asserts that a row in another subtree does not render again.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 afterscrollTopadvances.use-drag-handlers.test.tsalso verifies thatcomputeDropmeasures the pointer, notactivator + delta, when dnd-kit's delta contains scroll adjustment.Touch was not supported. The claim now matches the implementation: the handle uses
touch-action: manipulation, the default sensors areMouseSensor(5px distance) andTouchSensor(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.dragTypewas dead. RemoveddragTypeanddragTypeForNodefrom props, code, docs and the changeset.Non-blocking items from Round 1:
outer-drop-hook.tscheckstree.listEl.currentafter every commit and re-registers when the element changes, covering the fixed/variable list swap and late mounts.@dnd-kit/coreis 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.listenersRef, so there is nouseStateelement and no re-bind per render.data.name(id fallback). Anaccessibilityprop overrides or suppresses them. Tested indnd-provider.test.tsx.nodes.drag.idfallback andisDraggingcondition fromdrag-preview-container.tsx.get-dnd-provider-props.tstocollision-detection.ts, deletedtypes/dnd.tsandDragItem, and corrected the stale multi-tree comment intree-api.ts.Round 2: the fixes themselves
Review: #391 review 5736361132. Five inline threads:
listenersRef.currentat event time, so a row that mounts disabled starts dragging when it is enabled without re-running the ref callback. Tested.touch-action: noneon every row would block scrolling. The handle now usestouch-action: manipulation, paired with the delayedTouchSensor.@dnd-kit/core.^6.0.0to^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:
onDragEndread the pointer afterstopTracking()had already cleared it, so a release fell back toactivator + scrollAdjustedTranslate. It reads the pointer first now. Test: the pointer sits on the bottom half of a row whiledeltapoints above it, so the two produce different targets.rowIndexinuseFreshNode. The clone was memoised on node data and state but not the node's position, so a row kept its oldrowIndexafter a folder above it moved.original.idandoriginal.rowIndexare in the deps; the regression test opens a folder above a row and asserts the clone'sprevfollows it.TreeApi.clearHover(), which cancels the pending frame and resetshovering, the destination and the cursor in one place.updateHover,onDragEndandonDragCancelcall it, andtree-api.test.tsasserts the three reset together.aria-describedby,aria-roledescriptionandaria-disablednow go on the row, the element that actually takes focus; dnd-kit'srole="button"/tabIndexstay 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.dragIdsitself is memoised so the fallback[id]array keeps its identity. dnd-kit context updates no longer re-run the consumer'srenderDragPreview.touch-actionof its own, and the previous value is restored on detach.contextmenuworks. Tested with a minimalSensorInstancepassed through thesensorsprop.Mousetype. Replaced with the sharedXYCoordfromtypes/renderers.ts.c3ebedemarks 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 thehandlers/renderersnamespaces) 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,
useFreshNodechildren refresh, and docsReview: #391 review 6079134194. Five inline threads fixed in
b66a1ee:row-container.tsx). Droppedaria-roledescriptionandaria-disabledfromrowAttrs, and omittedaria-describedbywhen!canDragNode(node)(bothdisableDragand while editing), so screen readers announce rows as activetreeitems rather than"draggable"or disabled. Updated the assertions indnd-provider.test.tsx.node.childreninuseFreshNode. Addedoriginal.childrentouseFreshNode'suseMemodeps so folder rows refresh when a child updates in place (such as auseSimpleTreerename keeping the folder'sdatareference unchanged), with the regression test inrow-container.test.tsx..changes/drag-overlay-modernization.mdandREADME.mdto state thatoffsetandmouseare no longer passed (undefined) rather thannull, and thatisDraggingis still passed while the preview mounts only during an active drag and always receivestrue. Restored the Node>=22.12/require(esm), TypeScriptnode16/node18TS1479, and JestcustomExportConditions/jsdom/ pnpm /--experimental-vm-modulesguidance inREADME.md.Round 5:
RowViewderived state,useFreshNodeparent,onDragOver, ReactstopPropagation, andouterRefReview: #391 review 6098482648. Six inline threads fixed in
d87d141:RowView(row-container.tsx).RowViewInnernow subscribes touseNodesContext()(whileRowContainerpasses primitivedescribedByand memoiseddragListenersinstead of the unmemoiseddragAttributesobject). Derived getters such asnode.isOnlySelection,tree.selectedIds.size,tree.dragNodes, andnode.parent.isSelectedstay current on every node-state change, whileRowViewstill skips re-renders for unrelated rows during dnd-kitInternalContextpointer moves (Improved drag and drop performance #385).node.parentinuseFreshNode. Replacedoriginal.parent?.id ?? nullwithoriginal.parentinuseFreshNode'suseMemodeps soparent.children,nextSibling, andparent.datarefresh after tree rebuilds.use-drag-handlers.ts,provider.tsx). Added anonDragOverhandler alongsideonDragMovesoupdateHoverruns with the updatedevent.overas soon as the pointer crosses a row boundary.stopPropagation()insidedragHandle(drag-hook.ts,row-container.tsx). Replaced nativeaddEventListenerattachment with React event props (dragListeners) spread ontorowAttrs, gated onhandleElRef.current?.contains(event.target), so a child<button onMouseDown={e => e.stopPropagation()}>stops drags cleanly.outer-drop-hook.ts,outer-drop.ts,default-container.tsx). Replaced the dependency-lessuseEffectwith anOuterDropRefContextcallback ref wired toList'souterRef, so late-mounted containers registerOUTER_DROP_IDimmediately on mount and cleartree.listEl/ droppable state on unmount.TreePropsdocs (README.md). Addedsensorsandaccessibilityto theTreePropslisting.Round 6: SSR
DndContextid, customrenderContainerouter drop fallback, focus preservation, and docsReview: #391 review 6100477489. Five inline threads fixed in
ca517ee:aria-describedby(provider.tsx). Passedconst dndId = useId()to<DndKitContext id={dndId}>, avoiding dnd-kit's module-level counter mismatch between server prerender and client hydration. Added a test indnd-provider.test.tsx.renderContainerouter drop fallback (outer-drop-hook.ts). Kept theOuterDropRefContextcallback ref forDefaultContainer'sListand restored a fallbackuseEffectthat registerstree.listEl.currentwhen the callback ref was never used, so customrenderContainercomponents wiringref={tree.listEl}still support dropping below the last row and list-bounds clipping. Added a test indnd-provider.test.tsx.row-container.tsx).innerRefnow focuses the newly mounted element whenn !== null && n !== el.currentand!node.isEditing && node.isFocused, so customrenderRowcomponents that switch element tags while focused do not drop focus todocument.body. Added a test inrow-container.test.tsx.renderRowattrs& pointer-onlysensorsdocs (.changes/migrate-to-dnd-kit.md,README.md,types/tree-props.ts). Documented thatattrscarries drag-activation listeners (so customrenderRowmust spread{...attrs}in full and composeonMouseDown/onTouchStart/onPointerDown/custom sensor handlers), and clarified thatsensorssupports pointer-based sensors only (MouseSensor,TouchSensor,PointerSensor, or custom pointer/mouse/touch sensors), notKeyboardSensor.Where the rest of the scope lives
computeDropdedupe, and Backspace multi-selection focus fallback (folded from Fix focus fallback on Backspace deletion of trailing nodes #402).c3ebede).DndContext. Not supported in this PR.Version decision
@dnd-kit/core6.3.1 (Dec 2024) is the target.@dnd-kit/react/@dnd-kit/dom0.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/coreis 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-dndandreact-dnd-html5-backendare removed frompeerDependencies;@dnd-kit/core(^6.3.1) joinspeerDependencies, so it has to be installed alongsidereact-arborist.dndBackend,dndManager,dndRootElement, anddragTypeare removed fromTreeProps, not deprecated, so TypeScript flags existing uses.DragPreviewPropslosesoffsetandmouse, which are no longer passed (undefined). With<DragOverlay>positioning the preview, a customrenderDragPreviewthat positioned itself withoffsetshould stop doing so.idanddragIdsare unchanged;isDraggingis still passed, though the preview now mounts only during an active drag and always receivestrue(so a preview that previously animated out onisDragging === falsewill not get that render).MouseSensor(5px distance) and aTouchSensor(250ms hold, 5px tolerance).@dnd-kit'sKeyboardSensoris 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 viasensorsare not supported because hover targeting measures live pointer coordinates. The drag handle usestouch-action: manipulation, so a swipe still scrolls the list.renderRowcomponents receive drag-activation event listeners onattrsand must spread{...attrs}in full (composing rather than overwritingattrs.onMouseDown,attrs.onTouchStart,attrs.onPointerDown, or custom sensor activator handlers). Node renderers that only attachref={dragHandle}keep working unchanged when using the default row renderer or a customrenderRowthat spreadsattrs.Capabilities v5 gives up
These depended on
react-dndor native HTML5 drag and drop, and are listed in the changeset as well:react-dndtargets (thedrag-outdemo), and dropping the app'sreact-dnditems into the tree. The demo and its Cypress spec are removed with the capability.dndRootElement.dragType: with each tree owning a privateDndContext, no external target can read the drag data, so the prop had no observable effect. Removed entirely rather than kept as a dead label.<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 (whenrenderRowspreadsattrs).renderDragPreviewkeeps working; only its coordinate props are gone.XYCoordis defined locally as{ x: number, y: number }instead of re-exportingreact-dnd's.sensorsprop for customising the default pointer sensors (supports pointer-based sensors such asMouseSensor,TouchSensor,PointerSensor, or custom pointer/mouse/touch sensors; the typing tracks@dnd-kit/core6.xSensorDescriptor<SensorOptions>[]).accessibilityprop 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
TreeProvideralways wraps the tree in its own<DndContext>. TheuseHasParentDndContextprobe, the shared-context mode,ExternalDndListener, thetreeCollisionDetectionexport and thedrag-outdemo are gone; Support coordinating the tree with an external DndContext #396 tracks reintroducing a supported form.src/dnd/use-drag-handlers.tsowns the four dnd-kit callbacks and the pointer state, soTreeProviderstays a wiring component and Support coordinating the tree with an external DndContext #396 has one place to add to.event.deltais dnd-kit'sscrollAdjustedTranslate, soactivator + deltais not the pointer once the list auto-scrolls mid-drag. Capture-phase pointer listeners attach synchronously inonDragStartrather than via a commit-delayed effect, leavingpointerRefnull until the first move so flicks measure against activator + delta while real moves track the pointer.updateHoverreturns false and dispatcheshovering(null, null)alongsidecancelHover()when the pointer leaves droppable space or points to an unmounted row, ensuringonDragEnddrops only on targets valid in that event.useDroppableputs the row's element ref on the droppable's data, andcomputeDroptakes a structuralMeasurable(any object withgetBoundingClientRect) instead of anHTMLElement, so the hover maths runs against the live row with no casts or fabricated elements.<DragOverlay dropAnimation={null}>positions the preview;provider.tsxno longer keepsdragPreviewState, andDragPreviewContextis removed.drag-hook.tsreturns memoised React-leveldragListenersspread ontorowAttrsand gated onhandleElRef.current?.contains(event.target), so a child's synthetice.stopPropagation()cancels drags before reaching dnd-kit while keepingRowViewmemoised. ThedragHandleref callback setstouch-action: manipulation(and restores it on detach) without re-binding listeners on every render; with the delayedTouchSensor, swiping a row scrolls the list and holding still starts the drag.outer-drop-hook.tsexposes a callback ref viaOuterDropRefContext(read byList'souterRef) soOUTER_DROP_IDregisters immediately on mount (including late-mountedrenderContainers andFixedSizeList/VariableSizeListswaps) and detaches cleanly on unmount, with auseEffectfallback registeringtree.listEl.currentwhen a customrenderContainerdoes not useDefaultContainer.row-container.tsxsplits the dnd-kit hooks from the painted row.RowContainercallsuseDraggableanduseDroppable, which readInternalContext;RowViewis memoised, renders the user's Row and Node, and subscribes touseDataUpdates,useNodesContext, anduseDestinationUpdates.useFreshNodekeeps its clone stable across pointer moves while keying onoriginal.parent,original.children,original.rowIndex, node data, and node state.provider.tsxpassesid={useId()}(for deterministic SSR/hydrationaria-describedbyids) and pointer-onlyaccessibilityinstructions/announcements usingdata.name;TreeProps.accessibilityoverrides the defaults.@dnd-kit/corejoinspeerDependencies(^6.3.1);@dnd-kit/utilitiesjoinsdependencies.get-dnd-provider-props.tsis renamed tocollision-detection.ts, and unusedDragItem/types/dnd.tsis removed. The hardcoded webpack alias inshowcase/next.config.jsis 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,useSimpleTreechild-rename folder refresh,isOnlySelectionmulti-select updates,parent/nextSiblingfreshness after rebuilds,onDragOverhover updates, childstopPropagation, late-mounted and customrenderContainerouter droppable registration, deterministicuseIdaria-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.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.mainatb44e01a(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 onemainhas (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 thanactivator + delta, clearing hover on pointer exit, preventing a drop when the drag ends over null, and updating hover inonDragOverwhenoverswitches 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, childstopPropagationpreventing drag activation, late-mountedrenderContainerouter droppable registration and unmount cleanup, customrenderContainerusingtree.listElouter drop fallback, deterministic per-treearia-describedbyids viauseId, 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-describedbyonly on draggable rows, withoutaria-roledescriptionoraria-disabled).row-container.test.tsx: regression tests verifyinguseSimpleTreechild renames refresh the parent folder'snode.children, multi-select updatesnode.isOnlySelectionon the existing selection, and focus stays on a row when a customrenderRowreplaces its DOM element.use-fresh-node.test.tsx: regression tests forrowIndexupdates when a folder opens above a row and forparent.children,nextSibling, andparent.datafreshness after tree rebuilds.Part of #390.