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: Replace named character entities. #55364

Open
wants to merge 4 commits into
base: trunk
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
import { insert, isCollapsed } from '@wordpress/rich-text';
import { insert, isCollapsed, remove } from '@wordpress/rich-text';
import { applyFilters } from '@wordpress/hooks';

/**
Expand All @@ -23,6 +23,47 @@ export default ( props ) => ( element ) => {
const { inputType, data } = event;
const { value, onChange, registry } = props.current;

const replaceNamedCharacterReference = () => {
const text = value.text;
if ( ';' === data ) {
const ampAt = text.lastIndexOf( '&', value.start );
if ( -1 === ampAt || ampAt >= value.start ) {
return false;
}

const reference = text.slice( ampAt, value.start ) + ';';
if ( ! /^&#?[a-zA-Z0-9]+;$/.test( reference ) ) {
return false;
}

const d = document.createElement( 'div' );
d.innerHTML = reference;
const replacement = d.innerText;

if ( replacement === reference ) {
return false;
}

let newValue = remove( value, ampAt, value.text.length );
newValue = insert( newValue, replacement, ampAt, ampAt );

const {
__unstableMarkLastChangeAsPersistent,
__unstableMarkAutomaticChange,
} = registry.dispatch( blockEditorStore );

__unstableMarkLastChangeAsPersistent();
onChange( newValue );
__unstableMarkAutomaticChange();

return true;
}
};

if ( true === replaceNamedCharacterReference() ) {
return;
}

// Only run the rules when inserting text.
if ( inputType !== 'insertText' ) {
return;
Expand Down
Loading