Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refocus element after a diff #4244

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/component.js
Expand Up @@ -132,6 +132,7 @@ function renderComponent(component) {
newVNode._original = oldVNode._original + 1;
if (options.vnode) options.vnode(newVNode);

let focus = document.activeElement;
diff(
parentDom,
newVNode,
Expand All @@ -146,7 +147,7 @@ function renderComponent(component) {
);

newVNode._parent._children[newVNode._index] = newVNode;
commitRoot(commitQueue, newVNode, refQueue);
commitRoot(commitQueue, newVNode, refQueue, focus);

if (newVNode._dom != oldDom) {
updateParentDomPointers(newVNode);
Expand Down
9 changes: 8 additions & 1 deletion src/diff/index.js
Expand Up @@ -310,7 +310,7 @@ export function diff(
* which have callbacks to invoke in commitRoot
* @param {VNode} root
*/
export function commitRoot(commitQueue, root, refQueue) {
export function commitRoot(commitQueue, root, refQueue, focussedElement) {
root._nextDom = undefined;

for (let i = 0; i < refQueue.length; i++) {
Expand All @@ -332,6 +332,13 @@ export function commitRoot(commitQueue, root, refQueue) {
options._catchError(e, c._vnode);
}
});

if (
focussedElement !== document.activeElement &&
focussedElement.isConnected
) {
focussedElement.focus();
}
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/render.js
Expand Up @@ -34,6 +34,8 @@ export function render(vnode, parentDom, replaceNode) {
// List of effects that need to be called after diffing.
let commitQueue = [],
refQueue = [];
let focus = document.activeElement;

diff(
parentDom,
// Determine the new vnode tree and store it on the DOM element on
Expand All @@ -60,7 +62,7 @@ export function render(vnode, parentDom, replaceNode) {
);

// Flush all queued effects
commitRoot(commitQueue, vnode, refQueue);
commitRoot(commitQueue, vnode, refQueue, focus);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion test/browser/focus.test.js
Expand Up @@ -156,7 +156,7 @@ describe('focus', () => {
teardown(scratch);
});

it.skip('should maintain focus when swapping elements', () => {
it('should maintain focus when swapping elements', () => {
render(
<List>
<Input />
Expand Down