Skip to content

Commit

Permalink
Prevent scrolling when tabbing back to a focus capture div
Browse files Browse the repository at this point in the history
  • Loading branch information
gwwar committed Jun 25, 2021
1 parent b787346 commit 24a6ded
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/block-editor/src/components/writing-flow/use-tab-nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,43 @@ export default function useTabNav() {
lastFocus.current = event.target;
}

// When tabbing back to an element in block list, this event handler prevents scrolling if the
// focus capture divs (before/after) are outside of the viewport. (For example shift+tab back to a paragraph
// when focus is on a sidebar element. This prevents the scrollable writing area from jumping either to the
// top or bottom of the document.
//
// Note that it isn't possible to disable scrolling in the onFocus event. We need to intercept this
// earlier in the keypress handler, and call focus( { preventScroll: true } ) instead.
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus#parameters
function preventScrollOnTab( event ) {
if ( event.keyCode !== TAB ) {
return;
}
const isShift = event.shiftKey;
const direction = isShift ? 'findPrevious' : 'findNext';
const target = focus.tabbable[ direction ]( event.target );
// only do something when the next tabbable is a focus capture div (before/after)
if (
target === focusCaptureBeforeRef.current ||
target === focusCaptureAfterRef.current
) {
event.stopPropagation();
event.preventDefault();
target.focus( { preventScroll: true } );
}
}

node.ownerDocument.defaultView.addEventListener(
'keydown',
preventScrollOnTab
);
node.addEventListener( 'keydown', onKeyDown );
node.addEventListener( 'focusout', onFocusOut );
return () => {
node.ownerDocument.defaultView.removeEventListener(
'keydown',
preventScrollOnTab
);
node.removeEventListener( 'keydown', onKeyDown );
node.removeEventListener( 'focusout', onFocusOut );
};
Expand Down

0 comments on commit 24a6ded

Please sign in to comment.