Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ function BlockPopover( {

useShortcut(
'core/block-editor/focus-toolbar',
useCallback( () => setIsToolbarForced( true ), [] ),
useCallback( () => {
setIsToolbarForced( true );
}, [] ),
{
bindGlobal: true,
eventName: 'keydown',
Expand Down Expand Up @@ -180,7 +182,9 @@ function BlockPopover( {
__unstableBoundaryParent
// Observe movement for block animations (especially horizontal).
__unstableObserveElement={ node }
onBlur={ () => setIsToolbarForced( false ) }
onFocusOutside={ () => {
setIsToolbarForced( false );
} }
shouldAnchorIncludePadding
>
{ ( shouldShowContextualToolbar || isToolbarForced ) && (
Expand Down
309 changes: 161 additions & 148 deletions packages/block-editor/src/components/observe-typing/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* External dependencies
*/
import { over } from 'lodash';

/**
* WordPress dependencies
*/
Expand All @@ -19,14 +14,20 @@ import {
ESCAPE,
TAB,
} from '@wordpress/keycodes';
import { withSafeTimeout } from '@wordpress/compose';

/**
* Set of key codes upon which typing is to be initiated on a keydown event.
*
* @type {number[]}
* @type {Set<number>}
*/
const KEY_DOWN_ELIGIBLE_KEY_CODES = [ UP, RIGHT, DOWN, LEFT, ENTER, BACKSPACE ];
const KEY_DOWN_ELIGIBLE_KEY_CODES = new Set( [
UP,
RIGHT,
DOWN,
LEFT,
ENTER,
BACKSPACE,
] );

/**
* Returns true if a given keydown event can be inferred as intent to start
Expand All @@ -39,163 +40,175 @@ const KEY_DOWN_ELIGIBLE_KEY_CODES = [ UP, RIGHT, DOWN, LEFT, ENTER, BACKSPACE ];
*/
function isKeyDownEligibleForStartTyping( event ) {
const { keyCode, shiftKey } = event;
return ! shiftKey && KEY_DOWN_ELIGIBLE_KEY_CODES.includes( keyCode );
return ! shiftKey && KEY_DOWN_ELIGIBLE_KEY_CODES.has( keyCode );
}

function ObserveTyping( { children, setTimeout: setSafeTimeout } ) {
const typingContainer = useRef();
const lastMouseMove = useRef();
function useTypingObserver( ref ) {
const isTyping = useSelect( ( select ) =>
select( 'core/block-editor' ).isTyping()
);
const { startTyping, stopTyping } = useDispatch( 'core/block-editor' );

useEffect( () => {
toggleEventBindings( isTyping );
return () => toggleEventBindings( false );
}, [ isTyping ] );

/**
* Bind or unbind events to the document when typing has started or stopped
* respectively, or when component has become unmounted.
*
* @param {boolean} isBound Whether event bindings should be applied.
*/
function toggleEventBindings( isBound ) {
const bindFn = isBound ? 'addEventListener' : 'removeEventListener';
typingContainer.current.ownerDocument[ bindFn ](
'selectionchange',
stopTypingOnSelectionUncollapse
);
typingContainer.current.ownerDocument[ bindFn ](
'mousemove',
stopTypingOnMouseMove
);
document[ bindFn ]( 'mousemove', stopTypingOnMouseMove );
}

/**
* On mouse move, unset typing flag if user has moved cursor.
*
* @param {MouseEvent} event Mousemove event.
*/
function stopTypingOnMouseMove( event ) {
const { clientX, clientY } = event;

// We need to check that the mouse really moved because Safari triggers
// mousemove events when shift or ctrl are pressed.
if ( lastMouseMove.current ) {
const {
clientX: lastClientX,
clientY: lastClientY,
} = lastMouseMove.current;

if ( lastClientX !== clientX || lastClientY !== clientY ) {
stopTyping();
const element = ref.current;
const { ownerDocument } = element;
const { defaultView } = ownerDocument;

// Listeners to stop typing should only be added when typing.
// Listeners to start typing should only be added when not typing.
if ( isTyping ) {
let timerId;

/**
* Stops typing when focus transitions to a non-text field element.
*
* @param {FocusEvent} event Focus event.
*/
function stopTypingOnNonTextField( event ) {
const { target } = event;

// Since focus to a non-text field via arrow key will trigger
// before the keydown event, wait until after current stack
// before evaluating whether typing is to be stopped. Otherwise,
// typing will re-start.
timerId = defaultView.setTimeout( () => {
if ( ! isTextField( target ) ) {
stopTyping();
}
} );
}

/**
* Unsets typing flag if user presses Escape while typing flag is
* active.
*
* @param {KeyboardEvent} event Keypress or keydown event to
* interpret.
*/
function stopTypingOnEscapeKey( event ) {
const { keyCode } = event;

if ( keyCode === ESCAPE || keyCode === TAB ) {
stopTyping();
}
}
}

lastMouseMove.current = { clientX, clientY };
}
/**
* On selection change, unset typing flag if user has made an
* uncollapsed (shift) selection.
*/
function stopTypingOnSelectionUncollapse() {
const selection = defaultView.getSelection();
const isCollapsed =
selection.rangeCount > 0 &&
selection.getRangeAt( 0 ).collapsed;

if ( ! isCollapsed ) {
stopTyping();
}
}

/**
* On selection change, unset typing flag if user has made an uncollapsed
* (shift) selection.
*/
function stopTypingOnSelectionUncollapse( { target } ) {
const selection = target.defaultView.getSelection();
const isCollapsed =
selection.rangeCount > 0 && selection.getRangeAt( 0 ).collapsed;
let lastClientX;
let lastClientY;

/**
* On mouse move, unset typing flag if user has moved cursor.
*
* @param {MouseEvent} event Mousemove event.
*/
function stopTypingOnMouseMove( event ) {
const { clientX, clientY } = event;

// We need to check that the mouse really moved because Safari
// triggers mousemove events when shift or ctrl are pressed.
if (
lastClientX &&
lastClientY &&
( lastClientX !== clientX || lastClientY !== clientY )
) {
stopTyping();
}

lastClientX = clientX;
lastClientY = clientY;
}

if ( ! isCollapsed ) {
stopTyping();
}
}

/**
* Unsets typing flag if user presses Escape while typing flag is active.
*
* @param {KeyboardEvent} event Keypress or keydown event to interpret.
*/
function stopTypingOnEscapeKey( event ) {
if (
isTyping &&
( event.keyCode === ESCAPE || event.keyCode === TAB )
) {
stopTyping();
}
}

/**
* Handles a keypress or keydown event to infer intention to start typing.
*
* @param {KeyboardEvent} event Keypress or keydown event to interpret.
*/
function startTypingInTextField( event ) {
const { type, target } = event;

// Abort early if already typing, or key press is incurred outside a
// text field (e.g. arrow-ing through toolbar buttons).
// Ignore typing if outside the current DOM container
if (
isTyping ||
! isTextField( target ) ||
! typingContainer.current.contains( target )
) {
return;
element.addEventListener( 'focus', stopTypingOnNonTextField );
element.addEventListener( 'keydown', stopTypingOnEscapeKey );
ownerDocument.addEventListener(
'selectionchange',
stopTypingOnSelectionUncollapse
);
ownerDocument.addEventListener(
'mousemove',
stopTypingOnMouseMove
);

return () => {
defaultView.clearTimeout( timerId );
element.removeEventListener(
'focus',
stopTypingOnNonTextField
);
element.removeEventListener( 'keydown', stopTypingOnEscapeKey );
ownerDocument.removeEventListener(
'selectionchange',
stopTypingOnSelectionUncollapse
);
ownerDocument.removeEventListener(
'mousemove',
stopTypingOnMouseMove
);
};
}

// Special-case keydown because certain keys do not emit a keypress
// event. Conversely avoid keydown as the canonical event since there
// are many keydown which are explicitly not targeted for typing.
if (
type === 'keydown' &&
! isKeyDownEligibleForStartTyping( event )
) {
return;
}
/**
* Handles a keypress or keydown event to infer intention to start
* typing.
*
* @param {KeyboardEvent} event Keypress or keydown event to interpret.
*/
function startTypingInTextField( event ) {
const { type, target } = event;

// Abort early if already typing, or key press is incurred outside a
// text field (e.g. arrow-ing through toolbar buttons).
// Ignore typing if outside the current DOM container
if ( ! isTextField( target ) || ! element.contains( target ) ) {
return;
}

startTyping();
}

/**
* Stops typing when focus transitions to a non-text field element.
*
* @param {FocusEvent} event Focus event.
*/
function stopTypingOnNonTextField( event ) {
const { target } = event;

// Since focus to a non-text field via arrow key will trigger before
// the keydown event, wait until after current stack before evaluating
// whether typing is to be stopped. Otherwise, typing will re-start.
setSafeTimeout( () => {
if ( isTyping && ! isTextField( target ) ) {
stopTyping();
// Special-case keydown because certain keys do not emit a keypress
// event. Conversely avoid keydown as the canonical event since
// there are many keydown which are explicitly not targeted for
// typing.
if (
type === 'keydown' &&
! isKeyDownEligibleForStartTyping( event )
) {
return;
}
} );
}

// Disable reason: This component is responsible for capturing bubbled
// keyboard events which are interpreted as typing intent.

/* eslint-disable jsx-a11y/no-static-element-interactions */
return (
<div
ref={ typingContainer }
onFocus={ stopTypingOnNonTextField }
onKeyPress={ startTypingInTextField }
onKeyDown={ over( [
startTypingInTextField,
stopTypingOnEscapeKey,
] ) }
>
{ children }
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions */

startTyping();
}

element.addEventListener( 'keypress', startTypingInTextField );
element.addEventListener( 'keydown', startTypingInTextField );

return () => {
element.removeEventListener( 'keypress', startTypingInTextField );
element.removeEventListener( 'keydown', startTypingInTextField );
};
}, [ isTyping, startTyping, stopTyping ] );
}

function ObserveTyping( { children } ) {
const ref = useRef();
useTypingObserver( ref );
return <div ref={ ref }>{ children }</div>;
}

/**
* @see https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/observe-typing/README.md
*/
export default withSafeTimeout( ObserveTyping );
export default ObserveTyping;
1 change: 1 addition & 0 deletions packages/block-editor/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1649,6 +1649,7 @@ export function automaticChangeStatus( state, action ) {
return;
// Undoing an automatic change should still be possible after mouse
// move.
case 'START_TYPING':
case 'STOP_TYPING':
return state;
}
Expand Down
Loading