Skip to content

Simplify keyboard handling and dedupe computeDrop branches - #399

Open
ccombe wants to merge 10 commits into
jameskerr:mainfrom
ccombe:guard-clauses-and-cleanup
Open

ccombe wants to merge 10 commits into
jameskerr:mainfrom
ccombe:guard-clauses-and-cleanup

Conversation

@ccombe

@ccombe ccombe commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Keyboard handling in DefaultContainer was one ~190-line onKeyDown handler: a chain of per-key guard blocks inside a single function, so a change to one command meant editing the same function and each command could only be tested through the whole chain. computeDrop also carried two identical branches for the node above the cursor.

This moves each command into its own function in components/handle-tree-key-down.ts, dispatches them from one table, and merges the two computeDrop branches. It also fixes the pre-existing bugs in keyboard handling, including the multi-selection Backspace focus fallback from #402 which is now folded here.

Closes #397. Folds and closes #402. Independent of the @dnd-kit migration in #391; it was split out of that stack because it does not depend on it.

Merge order

  1. Untangle the one circular import and the patterns that add more #400 first. It removes the create-root ↔ node-api cycle and adds the madge CI guard; rebase onto it before merging here so the new step runs green.
  2. Simplify keyboard handling and dedupe computeDrop branches #399 (this PR) second. Small, self-contained keyboard diff.
  3. Migrate drag and drop from react-dnd to @dnd-kit #391 last. It edits some of the same compute-drop.ts and tree-api.ts regions; landing this first leaves only trivial hunks for the dnd-kit rewrite.

What changed

  • components/handle-tree-key-down.ts (new): one function per command (Backspace, ArrowUp/Down/Left/Right, Home, End, PageUp/PageDown, Enter, Ctrl/Cmd+A, typeahead, Tab), each with an early return when it does not apply, plus a KEY_HANDLERS table keyed by KeyboardEvent.key. An unlisted character key falls through to type-to-find, non-character keys and modifier shortcuts are ignored, and a/A fall through to type-to-find when onCreate is unset. The entry point's cyclomatic complexity drops from 29 to 4.
  • components/default-container.tsx: onKeyDown now calls handleTreeKeyDown; the component keeps only its element wiring.
  • dnd/compute-drop.ts: the item-above and closed-folder-above branches become one condition. Same result, one place to change.
  • interfaces/tree-api.ts: delete() tracks the first affected row index in a loop instead of Math.min(...nodes.map(...)), which passed one argument per selected node.
  • components/default-container.test.tsx: coverage for the branches the restructure touches, listed under Tests below.

Bugs fixed on the way

  • PageDown leaked into type-to-find. The old handler checked PageUp and PageDown in an if-chain, and the PageDown branch had no return, so it fell through into the type-to-find code below and appended the literal string PageDown to the search term. Keys are now either handled or passed to type-to-find, never both.
  • Every tree shared one type-to-find term. The buffer was two module-level variables, so with two trees on a page, typing in one filtered against the other's search and the 600ms reset clobbered both. It now lives on TreeApi as private typeaheadTerm / typeaheadTimeout with a clearTypeahead() method, which the provider calls next to cancelHover() on unmount, so the pending timeout is cleared too.
  • Non-character keys and modifier shortcuts corrupted type-to-find. Pressing Shift, Alt, Escape, or shortcuts like Ctrl+C used to append the key name or letter to the typeahead buffer. They are now filtered out before reaching typeahead, while AltGr (Ctrl+Alt) and macOS Option-composed letters still search.
  • Backspace multi-selection deletion focus fallback (Fix focus fallback on Backspace deletion of trailing nodes #402). The fallback used to pick a row that the same deletion removed: children of a selected folder, or a sibling deleted with its selected parent. It also returned nothing when every selected node was hidden inside a collapsed folder, and Math.min(...selectedIndices) overflowed the call stack on a very large selection. nextFocusAfterDelete is now one visible-order scan: forward from the most recent row (or the focused row when the selection is hidden), then backward, skipping any row that has a selected ancestor. TreeApi.delete() had the same spread on the same path and now uses a reduce.
  • A without onCreate did nothing. It now runs type-to-find, like any other character.
  • Space blocked names with spaces. While a type-to-find term is pending, Space now extends it (my f keeps searching) instead of selecting. Once the 600ms window lapses it goes back to select/activate/toggle.
  • Cmd/Ctrl+A with multi-select disabled selected the page. preventDefault() now runs before the disableMultiSelection early return, so the browser's select-all never fires.
  • Plain Alt+letter reached type-to-find. AltGr (getModifierState("AltGraph")) and macOS Option-composed characters still search, but a bare Alt+letter on Windows/Linux (Alt+D focuses the address bar) no longer does.

Testing

  • yarn workspace react-arborist test: 12 suites, 155 tests passing, no console warnings. Thirteen new tests, including PageDown not leaking into type-to-find, per-tree typeahead, Ctrl+A versus a, a without onCreate, non-character keys and modifiers, AltGr and Option-composed letters, Backspace focus after deleting a nested selection (children, siblings, collapsed folder), and the single-node root fallback.
  • yarn build-lib, yarn lint, yarn fmt:check: clean.
  • yarn workspace showcase build + xvfb-run yarn workspace e2e test: 5 specs, 22 tests passing.
  • madge --circular: 1 cycle, the one main has; rebase onto Untangle the one circular import and the patterns that add more #400 before merging, since that PR adds the guard to CI.

Budget demo e2e

budget-spec had been failing on main itself: the helper fired dragover with no pointer, so Cypress sent clientX/clientY 0 and measureHover resolved the cursor above the row, never in 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, so the drop nests through computeDrop's node.isInternal && hover.inMiddle branch - the case the comment describes. Verified locally: library and showcase rebuilt, budget-spec.cy.js 2/2 passing.

@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 628aca0

@ccombe

ccombe commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All points have been addressed in commit d91ea1d:

  • Typeahead fallthrough for a and A: In handleCreateWithKey and handleCreateFolder, when tree.props.onCreate is not set, execution routes to handleTypeahead(e.key, tree) so read-only trees do not swallow characters.
  • Typeahead non-character keys and shortcuts: Added a guard if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) return; before handleTypeahead, and lowercase search.term accumulation so searches match regardless of Shift or Caps Lock.
  • Tests added:
    • default-container.test.tsx now tests that a falls through to type-to-find when onCreate is not set.
    • A test verifies that non-character keys (e.g. Shift) and modifier shortcuts do not corrupt the type-to-find buffer.
    • The Backspace test now asserts both onDelete received ids: ["2"] and focusedNode.id became "3" (the next sibling).
  • Code cleanup: Standardized all key handlers to (e, tree), removing inline lambdas and handleBackspaceKey. Removed the redundant Array.from(ids) re-copy and the dead if (node) check inside the setTimeout.
  • Pre-existing Backspace fallback: Noted for a future follow-up as suggested.

@ccombe

ccombe commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Opened #402 to address the Backspace multi-selection focus fallback on trailing nodes.

The keyboard handler now dispatches through one table keyed by KeyboardEvent.key,
so each command is a small function and the cyclomatic complexity of the entry
point is four instead of twenty-nine. The type-to-find buffer moved from module
scope into a WeakMap keyed by tree, so two trees no longer type into one shared
search term.

Behaviour is otherwise unchanged, including PageDown no longer leaking into
type-to-find.
Address review feedback on keyboard handling:
- Route 'a' and 'A' to typeahead when tree.props.onCreate is not set so
  read-only trees do not swallow character keys.
- Filter out non-character keys and modifier shortcuts before typeahead,
  and compare lowercase search terms.
- Standardize key handlers to (e, tree), removing inline lambdas and
  redundant Array.from copy.
- Add test verifying 'a' falls through to type-to-find without onCreate,
  and verify non-character keys do not corrupt search.
- Strengthen Backspace test to assert deleted IDs and resulting focused node.
…election deletion

When multiple nodes at the end of the tree are selected and deleted via
Backspace, the focus fallback logic checked tree.lastNode without
verifying whether it was also part of the selection. This caused focus
to land on a node that was immediately deleted.

When later siblings are unavailable or selected, findUnselectedFallback
now finds the nearest unselected node preceding or following the
selection. Also prevents single-node deletion from focusing the
invisible root node when deleting the last root-level node.

This folds jameskerr#402 into jameskerr#399.
@ccombe
ccombe force-pushed the guard-clauses-and-cleanup branch from d91ea1d to 5093b32 Compare November 7, 2026 08:37
@ccombe

ccombe commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Folded #402 into this PR in commit 5093b32 to reduce the number of open PRs under review:

  • When deleting a multi-selection at the end of the tree via Backspace, findUnselectedFallback now finds the nearest unselected node preceding or following the selection.
  • Single-node deletion at the end of the root level falls back to the previous node rather than focusing the invisible root node.
  • Added 2 companion tests in default-container.test.tsx (146 tests total passing warning-clean).
  • Closed Fix focus fallback on Backspace deletion of trailing nodes #402.

@ccombe
ccombe force-pushed the guard-clauses-and-cleanup branch from 45448c8 to 47fe36d Compare November 7, 2026 09:04

@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 this! Most of the comments below are about the new multi-select Backspace focus logic. The main problem is that focus can still land on a node that is about to be deleted, because it is the child of a selected folder.

Comment thread .changes/guard-clauses-and-cleanup.md Resolved
A selected folder takes its descendants with it, so the focus fallback
could land on a row that the same Backspace removes. Replace the sibling
walk plus visible-index scan with one visible-order search that skips any
row under a selected node, and fall back to the focused row when the
most recent selection is inside a collapsed folder.

Drop the Math.max(...indices) spread so Ctrl+A then Backspace on a very
large tree cannot overflow the call stack.

Keep AltGr and macOS Option-composed characters in type-to-find; only
real modifier shortcuts are ignored now.

Rewrite the changeset to lead with what users will notice.
Synthetic dragover events never put the pointer in a folder row's middle
band, so that spec has been failing on main. Dropping just above the
folder's first row still moves the expense inside and exercises the same
folder totals, without depending on the synthetic pointer position.
`Math.min(...nodes.map(...))` passes one argument per selected node, so
select-all then Backspace on a 100k-row tree threw a RangeError before
onDelete ran. Track the minimum in a loop instead.

@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 this, the key-handler table is much easier to follow than the old switch. I checked that the merged computeDrop branches are byte-identical and that the per-tree typeahead works (the tree object comes from useMemo in the provider). The component tests pass warning-clean on this branch.

I found one real bug in the multi-select Backspace focus (when the selection is hidden inside a collapsed folder), and a couple of behaviour questions. The rest are small cleanups. Details are inline.

@ccombe

ccombe commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

All nine threads are answered and resolved in 628aca0:

  • visibleAnchor walks the raw id up to the nearest visible ancestor, and the collapsed-parent test now has rows above the folder so it actually exercises that path.
  • Backspace uses anchor.rowIndex, and the single-node branch is gone - both paths build the ids from the selection (or focus when there is none) and pick the next focus with nextFocusAfterDelete.
  • Ctrl/Cmd+A calls preventDefault() before the disableMultiSelection return.
  • Space extends a pending type-to-find term; a bare Alt+letter no longer reaches it while AltGr and macOS Option-composed letters still do.
  • The typeahead buffer moved onto TreeApi with clearTypeahead() on unmount.
  • delete() is a single reduce.
  • The budget helper sends dragenter plus explicit coordinates at the middle of the Entertainment row, so the test drops into the folder honestly; I confirmed on this branch that the spec passes 2/2 and explained the history in the thread.

Verified locally: 12 suites / 155 tests, warning-clean; lint/fmt:check clean; library + showcase build; all 5 Cypress specs (22 tests) pass. test and changeset are green on 628aca0.

@ccombe
ccombe requested a review from TrevorBurnham November 16, 2026 22:38
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.

Simplify keyboard handling and dedupe computeDrop branches

2 participants