Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rich text: move key handlers to ref callbacks #31724

Closed
wants to merge 5 commits into from
Closed
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
118 changes: 17 additions & 101 deletions packages/block-editor/src/components/rich-text/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,17 @@ import { omit } from 'lodash';
*/
import { RawHTML, useRef, useCallback, forwardRef } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import {
children as childrenSource,
getBlockTransforms,
findTransform,
} from '@wordpress/blocks';
import { children as childrenSource } from '@wordpress/blocks';
import { useInstanceId, useMergeRefs } from '@wordpress/compose';
import {
__unstableUseRichText as useRichText,
__unstableCreateElement,
isEmpty,
__unstableIsEmptyLine as isEmptyLine,
insert,
__unstableInsertLineSeparator as insertLineSeparator,
split,
toHTMLString,
isCollapsed,
removeFormat,
} from '@wordpress/rich-text';
import deprecated from '@wordpress/deprecated';
import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes';

/**
* Internal dependencies
Expand All @@ -44,6 +35,7 @@ import { useMarkPersistent } from './use-mark-persistent';
import { usePasteHandler } from './use-paste-handler';
import { useInputRules } from './use-input-rules';
import { useFormatTypes } from './use-format-types';
import { useEnterDeleteHandler } from './use-enter-delete-handler';
import FormatEdit from './format-edit';
import { getMultilineTag, getAllowedFormats } from './utils';

Expand Down Expand Up @@ -312,93 +304,6 @@ function RichTextWrapper(
useCaretInFormat( hasActiveFormats );
useMarkPersistent( { hasActiveFormats, html: adjustedValue, value } );

function onKeyDown( event ) {
const { keyCode } = event;

if ( event.defaultPrevented ) {
return;
}

if ( event.keyCode === ENTER ) {
event.preventDefault();

const _value = { ...value };
_value.formats = removeEditorOnlyFormats( value );
const canSplit = onReplace && onSplit;

if ( onReplace ) {
const transforms = getBlockTransforms( 'from' ).filter(
( { type } ) => type === 'enter'
);
const transformation = findTransform( transforms, ( item ) => {
return item.regExp.test( _value.text );
} );

if ( transformation ) {
onReplace( [
transformation.transform( {
content: _value.text,
} ),
] );
__unstableMarkAutomaticChange();
}
}

if ( multiline ) {
if ( event.shiftKey ) {
if ( ! disableLineBreaks ) {
onChange( insert( _value, '\n' ) );
}
} else if ( canSplit && isEmptyLine( _value ) ) {
splitValue( _value );
} else {
onChange( insertLineSeparator( _value ) );
}
} else {
const { text, start, end } = _value;
const canSplitAtEnd =
onSplitAtEnd && start === end && end === text.length;

if ( event.shiftKey || ( ! canSplit && ! canSplitAtEnd ) ) {
if ( ! disableLineBreaks ) {
onChange( insert( _value, '\n' ) );
}
} else if ( ! canSplit && canSplitAtEnd ) {
onSplitAtEnd();
} else if ( canSplit ) {
splitValue( _value );
}
}
} else if ( keyCode === DELETE || keyCode === BACKSPACE ) {
const { start, end, text } = value;
const isReverse = keyCode === BACKSPACE;

// 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();
}
}

const TagName = tagName;
const content = (
<>
Expand Down Expand Up @@ -439,6 +344,21 @@ function RichTextWrapper(
onReplace,
} ),
useUndoAutomaticChange(),
useEnterDeleteHandler( {
removeEditorOnlyFormats,
value,
onReplace,
onSplit,
__unstableMarkAutomaticChange,
multiline,
onChange,
disableLineBreaks,
splitValue,
onSplitAtEnd,
hasActiveFormats,
onMerge,
onRemove,
} ),
usePasteHandler( {
isSelected,
disableFormats,
Expand Down Expand Up @@ -466,10 +386,6 @@ function RichTextWrapper(
'rich-text'
) }
onFocus={ unstableOnFocus }
onKeyDown={ ( event ) => {
autocompleteProps.onKeyDown( event );
onKeyDown( event );
} }
/>
</>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';
import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes';
import {
isCollapsed,
isEmpty,
insert,
__unstableIsEmptyLine as isEmptyLine,
__unstableInsertLineSeparator as insertLineSeparator,
} from '@wordpress/rich-text';
import { getBlockTransforms, findTransform } from '@wordpress/blocks';

export function useEnterDeleteHandler( props ) {
const propsRef = useRef( props );
propsRef.current = props;
return useRefEffect( ( element ) => {
function onKeyDown( event ) {
const { keyCode } = event;

if ( event.defaultPrevented ) {
return;
}

const {
removeEditorOnlyFormats,
value,
onReplace,
onSplit,
__unstableMarkAutomaticChange,
multiline,
onChange,
disableLineBreaks,
splitValue,
onSplitAtEnd,
hasActiveFormats,
onMerge,
onRemove,
} = propsRef.current;

if ( event.keyCode === ENTER ) {
event.preventDefault();

const _value = { ...value };
_value.formats = removeEditorOnlyFormats( value );
const canSplit = onReplace && onSplit;

if ( onReplace ) {
const transforms = getBlockTransforms( 'from' ).filter(
( { type } ) => type === 'enter'
);
const transformation = findTransform(
transforms,
( item ) => {
return item.regExp.test( _value.text );
}
);

if ( transformation ) {
onReplace( [
transformation.transform( {
content: _value.text,
} ),
] );
__unstableMarkAutomaticChange();
}
}

if ( multiline ) {
if ( event.shiftKey ) {
if ( ! disableLineBreaks ) {
onChange( insert( _value, '\n' ) );
}
} else if ( canSplit && isEmptyLine( _value ) ) {
splitValue( _value );
} else {
onChange( insertLineSeparator( _value ) );
}
} else {
const { text, start, end } = _value;
const canSplitAtEnd =
onSplitAtEnd && start === end && end === text.length;

if ( event.shiftKey || ( ! canSplit && ! canSplitAtEnd ) ) {
if ( ! disableLineBreaks ) {
onChange( insert( _value, '\n' ) );
}
} else if ( ! canSplit && canSplitAtEnd ) {
onSplitAtEnd();
} else if ( canSplit ) {
splitValue( _value );
}
}
} else if ( keyCode === DELETE || keyCode === BACKSPACE ) {
const { start, end, text } = value;
const isReverse = keyCode === BACKSPACE;

// 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 );
};
}, [] );
}
24 changes: 14 additions & 10 deletions packages/block-editor/src/store/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ export function* mergeBlocks( firstBlockClientId, secondBlockClientId ) {

// Only focus the previous block if it's not mergeable
if ( ! blockAType.merge ) {
yield selectBlock( blockA.clientId );
yield selectBlock( blockA.clientId, -1 );
return;
}

Expand Down Expand Up @@ -802,8 +802,10 @@ export function* mergeBlocks( firstBlockClientId, secondBlockClientId ) {
blocksWithTheSameType[ 0 ].attributes
);

let newAttributeKey, newOffset;

if ( canRestoreTextSelection ) {
const newAttributeKey = findKey(
newAttributeKey = findKey(
updatedAttributes,
( v ) =>
typeof v === 'string' &&
Expand All @@ -821,7 +823,7 @@ export function* mergeBlocks( firstBlockClientId, secondBlockClientId ) {
multilineWrapperTags,
preserveWhiteSpace,
} );
const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA );
newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA );
const newValue = remove( convertedValue, newOffset, newOffset + 1 );
const newHtml = toHTMLString( {
value: newValue,
Expand All @@ -830,13 +832,6 @@ export function* mergeBlocks( firstBlockClientId, secondBlockClientId ) {
} );

updatedAttributes[ newAttributeKey ] = newHtml;

yield selectionChange(
blockA.clientId,
newAttributeKey,
newOffset,
newOffset
);
}

yield* replaceBlocks(
Expand All @@ -852,6 +847,15 @@ export function* mergeBlocks( firstBlockClientId, secondBlockClientId ) {
...blocksWithTheSameType.slice( 1 ),
]
);

if ( canRestoreTextSelection ) {
yield selectionChange(
blockA.clientId,
newAttributeKey,
newOffset,
newOffset
);
}
}

/**
Expand Down
Loading