-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
RichText: fix Space key for button and summary elements
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | ||
}; | ||
}, [] ); | ||
} |