Repository navigation
Conversation
👷 Deploy request for react-arborist pending review.Visit the deploys page to approve it
|
9b0a3ce to
7e4d96a
Compare
TrevorBurnham
left a comment
There was a problem hiding this comment.
Thanks for untangling these! I found one regression that needs fixing before this merges, plus a couple of smaller things. I've left inline suggestions for each one. I checked the full set locally against this branch: all 139 existing tests pass, the new test below passes, yarn build succeeds, and madge finds no new cycles.
Selection state can leak between trees (regression)
initialSelectionState, initialDndState and initialDragState are now module-level objects, so every store created by initialState() (and the module-level SERVER_STATE in provider.tsx) shares one selection.ids Set. Separately, and already true on main, SELECTION_ADD/SELECTION_REMOVE modify state.ids in place before copying it. On main that was harmless because each store had its own Set. With this PR the change goes into the shared one.
For ordinary click-driven selection, the provider's mount effect (deselectAll()) swaps in a new Set first, so that path is safe. But a selection made through the ref before that passive effect runs, for example from a parent's useLayoutEffect, lands in the shared Set. After that, every tree mounted later briefly renders with that node selected (until its own mount effect clears it), and the server snapshot is affected too.
Here's a test that reproduces it. On this branch all 4 tests fail. On main the first two pass and the last two (the in-place mutation) fail. With the suggestions below, all 4 pass, with no warnings:
modules/react-arborist/src/state/selection-slice.test.tsx
import { createRef, useLayoutEffect } from "react";
import { act, render } from "@testing-library/react";
import { Tree } from "../components/tree.js";
import type { TreeApi } from "../interfaces/tree-api.js";
import { initialState } from "./initial.js";
import { actions, reducer } from "./selection-slice.js";
type Datum = { id: string; name: string };
const data: Datum[] = [
{ id: "a", name: "a" },
{ id: "b", name: "b" },
];
/* A parent's layout effect runs before the provider's passive mount effect
(which resets selection via deselectAll), so this add lands on the store's
initial selection Set. */
test("selecting from a parent layout effect does not leak into later initial state", async () => {
function SelectOnMount() {
const ref = createRef<TreeApi<Datum> | undefined>();
useLayoutEffect(() => {
ref.current!.selectMulti("a", { focus: false });
}, []);
return <Tree<Datum> data={data} ref={ref} />;
}
const { unmount } = render(<SelectOnMount />);
await act(async () => {});
unmount();
expect(initialState().nodes.selection.ids.has("a")).toBe(false);
});
test("each initialState() call gets its own selection Set", () => {
expect(initialState().nodes.selection.ids).not.toBe(initialState().nodes.selection.ids);
});
test("SELECTION_ADD does not mutate the previous state's ids", () => {
const before = { ids: new Set<string>(), anchor: null, mostRecent: null };
reducer(before, actions.add("a"));
expect(before.ids.has("a")).toBe(false);
});
test("SELECTION_REMOVE does not mutate the previous state's ids", () => {
const before = { ids: new Set(["a"]), anchor: null, mostRecent: null };
reducer(before, actions.remove("a"));
expect(before.ids.has("a")).toBe(true);
});The fix is to make the initial*State exports factory functions, so each call builds new objects, and to have SELECTION_ADD/SELECTION_REMOVE copy the Set before changing it.
ROOT_ID becomes a public export
Moving ROOT_ID into interfaces/node-api.ts adds it to the package's public API, because index.ts does export * from "./interfaces/node-api.js". Once that ships, removing it would be a breaking change. Putting it in its own module, src/data/root-id.ts, still breaks the cycle and keeps it internal:
export const ROOT_ID = "__REACT_ARBORIST_INTERNAL_ROOT__";Then import it from there in node-api.ts, create-root.ts, tree-api.ts (line 16, which is outside the diff so I can't leave a suggestion on it) and dnd/compute-drop.test.ts. With that change, ROOT_ID no longer appears in dist/module/index.d.ts.
Changeset
This is a refactor with no user-facing effect, so per AGENTS.md the changeset should be dropped and the PR labeled skip-changelog. As written, it forces a patch release. Its text also mentions decoupling "renderer components", but the PR description says those imports were left as they are.
|
All six points are addressed in a68ddf1.
Local checks on a68ddf1: 139 tests pass, warning-clean, |
|
Correction on the last bullet: I could not apply |
|
The |
TrevorBurnham
left a comment
There was a problem hiding this comment.
Thanks for untangling this! The cycle break itself looks correct to me (and the new n !== null check in dragNodes matches TreeApi.get's return type). A few notes inline, mostly about how the change is described:
- The PR description says "No behavior change" and that
node-api.tsownsROOT_IDwithcreate-rootre-exporting it. At the head commit,ROOT_IDlives indata/root-id.tsandcreate-rootdoesn't re-export it, and the selection reducer does change behavior (see inline). Could you update the description to match?
Neither fallow nor `madge --circular` reports a cycle now. The public API is unchanged: TreeApi's renderer getters still fall back to the default components, and the only new imports are type-only ones. - context, create-root, use-destination-updates, node-api and the types modules import TreeApi as a type. - Each state slice owns its initial state, so a slice no longer imports the aggregate that imports it back.
The initial*State exports are now factories, so each store gets its own selection Set, dragIds array and cursor. SELECTION_ADD and SELECTION_REMOVE copy the Set before changing it, so a reducer run can no longer reach into state another store still holds. ROOT_ID moves to data/root-id.ts. interfaces/node-api.ts is re-exported by index.ts, so defining it there made it a public export. Dropped the changeset: this is a refactor with no user-facing effect.
The changelog and the test were describing a shared initial Set that never shipped. Selection add and remove already copy the Set; the test now holds that snapshot across a later selectMulti.
These symbols are only used as types: NodeApi in create-list, RootState in context, TreeProps in initial state, DragItem in the drag and drop hooks, and OpenMap plus the handlers and renderers namespaces in tree props. Co-authored-by: Cursor <cursoragent@cursor.com>
initial.ts still inlined open, focus, and edit while drag, selection, and dnd already came from factories. Each store now gets those three from the slice factories too. Co-authored-by: Cursor <cursoragent@cursor.com>
Those notes asked for their own pull requests. This branch keeps the cycle break and the stable selection Set. Co-authored-by: Cursor <cursoragent@cursor.com>
4ee71c6 to
b554511
Compare
|
Rebased onto The failing job was the budget e2e spec: synthetic
|
TrevorBurnham
left a comment
There was a problem hiding this comment.
Thanks for untangling this! I checked out b554511 locally: yarn workspace react-arborist build and yarn lint pass, and all 138 Jest tests pass with no console.error/warn or act() warnings (the new selection-slice.test.ts included). I didn't run the Cypress suite.
The selection fix looks right to me, and moving ROOT_ID doesn't touch the public API, since index.ts never re-exported create-root.
I also built the base commit (b44e01a) and diffed the emitted JS. The cycle is actually broken by moving ROOT_ID into root-id.ts and by having initial.ts import the slice factories (instead of the slices importing initial.ts). None of the 20 import type changes alters the emitted imports. More on that, plus a few smaller notes, inline.
b554511 to
8b38f05
Compare
|
All seven threads are answered and resolved in
|
initial.ts still inlined open, focus, and edit while drag, selection, and dnd already came from factories. Each store now gets those three from the slice factories too. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Folded the last deferred nit into this PR in Re-verified on The madge CI guard is now in this PR too ( The type-only imports moved to #391 instead of staying a separate PR ( |
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.
This branch already reports no cycles. Run madge after the build so a new one fails the pull request. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Also folded in the madge CI guard ( Verified on |
|
Pinned the new madge step to major version 8 ( |
Summary
madge --circularon the built library reports one cycle,data/create-root.js > interfaces/node-api.js:node-api.tsimportsROOT_IDfromcreate-root.ts, andcreate-root.tsimportsNodeApiback. Two further patterns will add cycles as the module graph grows: value imports where only a type is needed, and state slices importinginitial.ts/root-reducer.tsfor their initial slices.This removes that cycle. Selection add and remove copy the selection
Setinstead of mutating the previous one. An earliertree.selectedIdssnapshot stays unchanged after the next select or deselect. The shared initial object from the first commit on this branch never shipped.The leftover type-only imports land with #391 (
c3ebede), since that branch is the one that rewrites the react-dnd files they would otherwise touch. Themadge --circularCI step is in this PR (5d6fc9d, pinned to madge 8 inb6d5252), so the guard ships in the same change as the cycle fix.Merge order
mainstill has and adds the madge guard, so the other PRs rebase onto a cycle-freemainand the new CI step passes on their trees.compute-drop.tsandtree-api.tswith Migrate drag and drop from react-dnd to @dnd-kit #391, so landing it first leaves only trivial hunks for the migration.main. Its dnd-kit rewrite overlaps this PR in eight files; the resolutions keep this PR's type imports and factories and Migrate drag and drop from react-dnd to @dnd-kit #391's dnd-kit mechanics.What changed
ROOT_IDlives indata/root-id.ts.interfaces/node-api.tsimports it from there, so it is not a new public export.initialSelectionState,initialDndState,initialDragState,initialOpenState,initialFocusState,initialEditState).state/initial.tscalls those six, and the slices do not importinitial.ts.import typeon the imports that formed the cycle (TreeApi,NodeApion that path,DropResult,Cursor, andRootStateininitial.ts). The leftovers listed in review are not in this pull request.interfaces/tree-api.ts:dragNodesfilters with an is NodeApi<T>predicate instead of casting the array.What did not change
TreeApikeeps the fiverenderRow/renderNode/renderCursor/renderContainer/renderDragPreviewgetters with their|| DefaultXfallbacks. Inlining those defaults at each call site was the first attempt at removing the cycle, but it changes whattree.renderRowreturns when no renderer prop is set, which is part of the public surface. Type-only imports break the cycle instead, so the getters stay as they are.Testing
madge --circular modules/react-arborist/dist/module/index.js: 0 cycles (was 1). CI now runs the same check afteryarn build.yarn workspace react-arborist test: 13 suites, 138 tests passing, no console warnings.yarn workspace react-arborist build,yarn lint, andyarn fmt:check: clean.Build & Testworkflow is green after rebasing ontomainat b44e01a.The Cypress budget spec was failing because the synthetic
dragovercarried no pointer, so the offset resolved to 0,0 and hover never reached a folder row's middle band. The helper now sendsdragenter(react-dnd needs it to register the drop target) and passes explicit client coordinates at the middle of the target row. The expense therefore nests into the empty "Entertainment" folder throughcomputeDrop'snode.isInternal && hover.inMiddlebranch, which is what the test comment says. Verified locally: library and showcase rebuilt,budget-spec.cy.js2/2 passing. The helper is byte-identical to #399's copy, so whichever lands second drops it out on rebase.Interaction with #391
git merge-tree migrate-to-dnd-kit untangle-circular-depsreports eight conflicting files. Three are the import lines #391 swaps for@dnd-kit(dnd/compute-drop.ts,dnd/drop-hook.ts,types/renderers.ts); four are adjacent import lines that both branches turn intoimport type(context.ts,data/create-list.ts,state/initial.ts,types/tree-props.ts); and the budget spec differs by design, because #391 drives its drag with the mouse-basedsupport/drag.jshelper while react-dnd needs theDataTransferone here.This branch should land first. #391's rebase then resolves each file by keeping #391's dnd-kit mechanics and this PR's type-only imports and factories.