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 |
Part 1 of the roadmap in #390.
Merge order
mainand adds the madge CI guard.mainonce 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-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 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:
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.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. With<DragOverlay>positioning the preview, those values would always benull; a customrenderDragPreviewthat positioned itself withoffsetshould stop doing so.id,dragIdsandisDraggingare unchanged.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). The drag handle usestouch-action: manipulation, so a swipe still scrolls the list.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 row renderers.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 defaults. The README notes that the typing tracks@dnd-kit/core6.x, with an example of the default mouse and touch wiring.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.tsattaches 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 throughlistenersRef.currentat event time, so a row that mounted with drag disabled starts dragging once it is enabled without re-running the ref callback. The handle setstouch-action: manipulation; with the delayedTouchSensor, swiping a row scrolls the list and holding still starts the drag.outer-drop-hook.tschecks the element ref on commit and updates droppable registration whenrowHeighttoggles between fixed and variable lists.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 only to node, data and destination state.useFreshNodekeeps its clone stable across unrelated renders by keying on node data and state values instead of the previous clone.provider.tsxpasses dnd-kitaccessibilitywith pointer-only instructions and 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, 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.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, 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.