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: pad multiple spaces through en/em replacement #56341

Merged
merged 3 commits into from
Nov 21, 2023
Merged
Changes from 2 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
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,26 @@ function findSelection( blocks ) {
return [];
}

function convertSpaces( value ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function could use some explanation, and possible a clearer name like replacePrecedingSpaces

just a single sentence explaining its purpose could help quite a bit.

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 +142,7 @@ export function useInputRules( props ) {

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

if ( transformed !== value ) {
Expand Down
Loading