Skip to content

Untangle the one circular import and the patterns that add more - #400

Open
ccombe wants to merge 13 commits into
jameskerr:mainfrom
ccombe:untangle-circular-deps
Open

ccombe wants to merge 13 commits into
jameskerr:mainfrom
ccombe:untangle-circular-deps

Conversation

@ccombe

@ccombe ccombe commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

madge --circular on the built library reports one cycle, data/create-root.js > interfaces/node-api.js: node-api.ts imports ROOT_ID from create-root.ts, and create-root.ts imports NodeApi back. Two further patterns will add cycles as the module graph grows: value imports where only a type is needed, and state slices importing initial.ts / root-reducer.ts for their initial slices.

This removes that cycle. Selection add and remove copy the selection Set instead of mutating the previous one. An earlier tree.selectedIds snapshot 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. The madge --circular CI step is in this PR (5d6fc9d, pinned to madge 8 in b6d5252), so the guard ships in the same change as the cycle fix.

Merge order

  1. Untangle the one circular import and the patterns that add more #400 (this PR) first. It removes the cycle that main still has and adds the madge guard, so the other PRs rebase onto a cycle-free main and the new CI step passes on their trees.
  2. Simplify keyboard handling and dedupe computeDrop branches #399 second. Small, self-contained keyboard diff; it shares compute-drop.ts and tree-api.ts with Migrate drag and drop from react-dnd to @dnd-kit #391, so landing it first leaves only trivial hunks for the migration.
  3. Migrate drag and drop from react-dnd to @dnd-kit #391 last, then rebase it onto the updated 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_ID lives in data/root-id.ts. interfaces/node-api.ts imports it from there, so it is not a new public export.
  • Every slice exports an initial-state factory (initialSelectionState, initialDndState, initialDragState, initialOpenState, initialFocusState, initialEditState). state/initial.ts calls those six, and the slices do not import initial.ts.
  • import type on the imports that formed the cycle (TreeApi, NodeApi on that path, DropResult, Cursor, and RootState in initial.ts). The leftovers listed in review are not in this pull request.
  • interfaces/tree-api.ts: dragNodes filters with a n is NodeApi<T> predicate instead of casting the array.

What did not change

TreeApi keeps the five renderRow / renderNode / renderCursor / renderContainer / renderDragPreview getters with their || DefaultX fallbacks. Inlining those defaults at each call site was the first attempt at removing the cycle, but it changes what tree.renderRow returns 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 after yarn build.
  • yarn workspace react-arborist test: 13 suites, 138 tests passing, no console warnings.
  • yarn workspace react-arborist build, yarn lint, and yarn fmt:check: clean.
  • The Build & Test workflow is green after rebasing onto main at b44e01a.

The Cypress budget spec was failing because the synthetic dragover carried no pointer, so the offset resolved to 0,0 and hover never reached a folder row's middle band. The helper now sends dragenter (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 through computeDrop's node.isInternal && hover.inMiddle branch, which is what the test comment says. Verified locally: library and showcase rebuilt, budget-spec.cy.js 2/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-deps reports 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 into import 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-based support/drag.js helper while react-dnd needs the DataTransfer one 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.

@netlify

netlify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

👷 Deploy request for react-arborist pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit b6d5252

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

Comment thread .changes/untangle-circular-deps.md Resolved
@ccombe

ccombe commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

All six points are addressed in a68ddf1.

  • initialSelectionState, initialDndState and initialDragState are factories now, so each store gets its own Set, array and cursor.
  • SELECTION_ADD and SELECTION_REMOVE copy the Set before changing it.
  • ROOT_ID moved to src/data/root-id.ts, imported from there by node-api.ts, create-root.ts, tree-api.ts and compute-drop.test.ts. It no longer appears in dist/module/index.d.ts.
  • Your 4 tests are in as state/selection-slice.test.tsx and pass.
  • Changeset dropped, skip-changelog applied.

Local checks on a68ddf1: 139 tests pass, warning-clean, yarn build passes, lint and fmt clean, madge reports no circular dependencies.

@ccombe

ccombe commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Correction on the last bullet: I could not apply skip-changelog. The labels API returns 403 for this account ("Must have admin rights to Repository") and gh pr edit hits the Projects classic error. The changeset is dropped as you asked, so the Changeset job will fail until the label is on. Say the word if you would rather I keep the file in place until then.

@ccombe

ccombe commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

The Changeset check was failing because the PR touches modules/react-arborist/src/ and had no .changes/ entry, and I cannot apply the skip-changelog label (no admin rights on this repo). Added .changes/untangle-circular-deps.md in d3f4afb describing the change as internal with no public API or rendered-output change. If you would rather keep it out of the release notes, apply skip-changelog and the entry can be dropped.

@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 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.ts owns ROOT_ID with create-root re-exporting it. At the head commit, ROOT_ID lives in data/root-id.ts and create-root doesn't re-export it, and the selection reducer does change behavior (see inline). Could you update the description to match?

Comment thread .changes/untangle-circular-deps.md Resolved
ccombe and others added 7 commits November 14, 2026 21:50
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>
@ccombe
ccombe force-pushed the untangle-circular-deps branch from 4ee71c6 to b554511 Compare November 14, 2026 10:50
@ccombe

ccombe commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main at b44e01a and fixed the red Build & Test check in b554511.

The failing job was the budget e2e spec: synthetic dragover events never land in a folder row's middle band, so the drop into "Entertainment" never registered. b554511 applies the same fix that is already on #399 (drop just above a row inside the folder), which exercises the same totals without depending on the synthetic pointer position. If #399 lands first, this commit drops out on rebase.

test and changeset are both green now.

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

Comment thread .changes/untangle-circular-deps.md Resolved
@ccombe
ccombe force-pushed the untangle-circular-deps branch from b554511 to 8b38f05 Compare November 16, 2026 20:49
@ccombe

ccombe commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

All seven threads are answered and resolved in 8b38f05 / the PR body. The budget spec now uses the same deterministic helper as #399 (byte-identical, so the hunk drops out on rebase), which puts the drop back on the middle of the Entertainment row. The type-only imports are in #391 (c3ebede); the slice factories (92c28c8) and the madge CI guard (5d6fc9d) are in this PR. All fork follow-ups are closed. The setupApi copy moved to tree-api.test.ts, the import reorder was dropped, and the changeset covers the selection-copy fix.

test and changeset are green on 8b38f05.

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

ccombe commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Folded the last deferred nit into this PR in 92c28c8: open, focus and edit now export initial-state factories like the other slices, and state/initial.ts calls all six. Follow-up #5 is closed and its branch deleted.

Re-verified on b6d5252: 13 suites / 138 tests passing, lint and fmt clean, yarn build succeeds, madge --circular finds 0 cycles.

The madge CI guard is now in this PR too (5d6fc9d, pinned in b6d5252): adding it to main ahead of the cycle fix would have failed every PR, so it ships with the fix. No fork follow-ups remain open.

The type-only imports moved to #391 instead of staying a separate PR (c3ebede), since #391 deletes the react-dnd hooks they would otherwise touch.

ccombe added a commit to ccombe/react-arborist that referenced this pull request Nov 20, 2026
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>
@ccombe

ccombe commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Also folded in the madge CI guard (5d6fc9d) in .github/workflows/build-and-test.yml: one line, running madge --circular on the built module after yarn build. No fork follow-ups remain.

Verified on 5d6fc9d: 13 suites / 138 tests, lint and fmt clean, yarn build succeeds, madge --circular reports 0 cycles.

@ccombe
ccombe requested a review from TrevorBurnham November 20, 2026 21:36
@ccombe

ccombe commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Pinned the new madge step to major version 8 (b6d5252) so a future major release cannot break CI unexpectedly. Verified locally and the CI step reports No circular dependency found!. No changeset or follow-up PR needed for the workflow line.

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