Skip to content

Commit

Permalink
RichText: fix Space key for button and summary elements
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Aug 12, 2021
1 parent baf9697 commit cfb6289
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/rich-text/src/component/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useSelectObject } from './use-select-object';
import { useIndentListItemOnSpace } from './use-indent-list-item-on-space';
import { useInputAndSelection } from './use-input-and-selection';
import { useDelete } from './use-delete';
import { useSpace } from './use-space';

export function useRichText( {
value = '',
Expand Down Expand Up @@ -198,6 +199,7 @@ export function useRichText( {
isSelected,
onSelectionChange,
} ),
useSpace(),
useRefEffect( () => {
applyFromProps();
didMount.current = true;
Expand Down
40 changes: 40 additions & 0 deletions packages/rich-text/src/component/use-space.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* WordPress dependencies
*/
import { useRefEffect } from '@wordpress/compose';
import { SPACE } from '@wordpress/keycodes';

/**
* For some elements like BUTTON and SUMMARY, the space key doesn't insert a
* space character in some browsers even though the element is editable. We have
* to manually insert a space and prevent default behaviour.
*
* DO NOT limit this behaviour to specific tag names! It would mean that this
* behaviour is not widely tested. If there's ever any problems, we should find
* a different solution entirely or remove it entirely.
*/
export function useSpace() {
return useRefEffect( ( element ) => {
function onKeyDown( event ) {
// Don't insert a space if default behaviour is prevented.
if ( event.defaultPrevented ) {
return;
}

const { keyCode, altKey, metaKey, ctrlKey } = event;

// Only consider the space key without modifiers pressed.
if ( keyCode !== SPACE || altKey || metaKey || ctrlKey ) {
return;
}

event.target.ownerDocument.execCommand( 'insertText', false, ' ' );
event.preventDefault();
}

element.addEventListener( 'keydown', onKeyDown );
return () => {
element.removeEventListener( 'keydown', onKeyDown );
};
}, [] );
}

0 comments on commit cfb6289

Please sign in to comment.