Keyed reorder moves the row that moved earlier, so a focused input in it loses focus (React keeps focus) #150
Version: @tanstack/redact 0.3.0
When a keyed list is reordered, Redact moves a different DOM node than React does. If the node it moves contains the focused element, the browser blurs it (moving a focused node with insertBefore drops focus in Chromium, Firefox and WebKit), so focus ends up on <body>. React keeps focus in the same case.
Repro (Vitest + jsdom + Testing Library)#
import { render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
test('a keyed reorder keeps focus in the row that moves earlier', () => {
const list = (order) => (
<div>{order.map((id) => <div key={id}><input aria-label={id} /></div>)}</div>
);
const { rerender } = render(list(['a', 'b']));
const b = screen.getByLabelText('b');
b.focus();
rerender(list(['b', 'a']));
expect(screen.getByLabelText('b')).toBe(b); // passes on both: the node is kept
expect(document.activeElement).toBe(b); // React: b. Redact: body
});
React 19.2.8 passes; Redact 0.3.0 fails the focus assertion.
Where it seems to come from#
For [a, b] -> [b, a], React leaves the rows whose relative order is unchanged in place and moves the ones that fall behind (it moves a). placeDomsInOrder in dist/dom/reconcile.js walks backwards and calls insertBefore on rows that move earlier (it moves b), which takes focus away from the row the user is working in. The same happens when an item is moved to the top of a list.
Matching React's placement (walk the new order forwards, track the highest current DOM index among rows left in place, and move only rows whose current index is below it) would keep focus. moveBefore could help where it exists, but jsdom and some browsers don't have it.
Real-world impact#
Keyboard users lose focus when the row they're in moves up: "move up" buttons, lists that re-sort, or lists that put the newest item first while a control in a row has focus. Scroll position and media inside the moved row can also reset.
Sign in to join this conversation.
Thanks for the clear repro, this is confirmed on current main. A local fix now keeps focus in rows that move earlier. It has not shipped yet.