Skip to content

Commit

Permalink
Rich text: pad multiple spaces through en/em replacement (#56341)
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix authored Nov 21, 2023
1 parent 7e61771 commit 53cae01
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
32 changes: 30 additions & 2 deletions packages/block-editor/src/components/rich-text/use-input-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
import { useRef } from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';
import { insert, toHTMLString } from '@wordpress/rich-text';
import { insert, isCollapsed, toHTMLString } from '@wordpress/rich-text';
import { getBlockTransforms, findTransform } from '@wordpress/blocks';
import { useDispatch } from '@wordpress/data';

Expand Down Expand Up @@ -42,6 +42,34 @@ function findSelection( blocks ) {
return [];
}

/**
* An input rule that replaces two spaces with an en space, and an en space
* followed by a space with an em space.
*
* @param {Object} value Value to replace spaces in.
*
* @return {Object} Value with spaces replaced.
*/
function replacePrecedingSpaces( value ) {
if ( ! isCollapsed( value ) ) {
return value;
}

const { text, start } = value;
const lastTwoCharacters = text.slice( start - 2, start );

// Replace two spaces with an em space.
if ( lastTwoCharacters === ' ' ) {
return insert( value, '\u2002', start - 2, start );
}
// Replace an en space followed by a space with an em space.
else if ( lastTwoCharacters === '\u2002 ' ) {
return insert( value, '\u2003', start - 2, start );
}

return value;
}

export function useInputRules( props ) {
const {
__unstableMarkLastChangeAsPersistent,
Expand Down Expand Up @@ -122,7 +150,7 @@ export function useInputRules( props ) {

return accumlator;
},
preventEventDiscovery( value )
preventEventDiscovery( replacePrecedingSpaces( value ) )
);

if ( transformed !== value ) {
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/specs/editor/blocks/links.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -940,8 +940,8 @@ test.describe( 'Links', () => {
pageUtils,
editor,
} ) => {
const textToSelect = ` spaces `;
const textWithWhitespace = `Text with leading and trailing${ textToSelect }`;
const textToSelect = `\u2003\u2003 spaces\u2003 `;
const textWithWhitespace = `Text with leading and trailing spaces `;

// Create a block with some text.
await editor.insertBlock( {
Expand Down

0 comments on commit 53cae01

Please sign in to comment.