-
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.
Rich text: extract delete handler to hook
- Loading branch information
Showing
2 changed files
with
65 additions
and
43 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
59 changes: 59 additions & 0 deletions
59
packages/block-editor/src/components/rich-text/use-delete.js
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,59 @@ | ||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { useRef } from '@wordpress/element'; | ||
import { useRefEffect } from '@wordpress/compose'; | ||
import { DELETE, BACKSPACE } from '@wordpress/keycodes'; | ||
import { isCollapsed, isEmpty } from '@wordpress/rich-text'; | ||
|
||
export function useDelete( props ) { | ||
const propsRef = useRef( props ); | ||
propsRef.current = props; | ||
return useRefEffect( ( element ) => { | ||
function onKeyDown( event ) { | ||
const { keyCode } = event; | ||
|
||
if ( event.defaultPrevented ) { | ||
return; | ||
} | ||
|
||
const { value, onMerge, onRemove } = propsRef.current; | ||
|
||
if ( keyCode === DELETE || keyCode === BACKSPACE ) { | ||
const { start, end, text } = value; | ||
const isReverse = keyCode === BACKSPACE; | ||
const hasActiveFormats = | ||
value.activeFormats && !! value.activeFormats.length; | ||
|
||
// Only process delete if the key press occurs at an uncollapsed edge. | ||
if ( | ||
! isCollapsed( value ) || | ||
hasActiveFormats || | ||
( isReverse && start !== 0 ) || | ||
( ! isReverse && end !== text.length ) | ||
) { | ||
return; | ||
} | ||
|
||
if ( onMerge ) { | ||
onMerge( ! isReverse ); | ||
} | ||
|
||
// Only handle remove on Backspace. This serves dual-purpose of being | ||
// an intentional user interaction distinguishing between Backspace and | ||
// Delete to remove the empty field, but also to avoid merge & remove | ||
// causing destruction of two fields (merge, then removed merged). | ||
if ( onRemove && isEmpty( value ) && isReverse ) { | ||
onRemove( ! isReverse ); | ||
} | ||
|
||
event.preventDefault(); | ||
} | ||
} | ||
|
||
element.addEventListener( 'keydown', onKeyDown ); | ||
return () => { | ||
element.removeEventListener( 'keydown', onKeyDown ); | ||
}; | ||
}, [] ); | ||
} |