facebookarchive / draft-js

A React framework for building text editors.

Home Page:https://draftjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem with replaceText Modifier function

alessio-de-padova opened this issue · comments

Do you want to request a feature or report a bug?

I would like to understand the behavior of the Modifier's replaceText function.

What is the current behavior?

on editorState change I have a piece of code that is responsible for substituting a piece of text with an entity when some conditions are met.
The code is as follows:

`
const replaceString = (editorState, setEditorState) => {
const contentState = editorState.getCurrentContent();
const selectionState = editorState.getSelection();
const block = contentState.getBlockForKey(selectionState.getAnchorKey())
const blockAsArray = block.getText().split(' ');
const lastWord = blockAsArray.pop();

if (lastWord.startsWith('@*') || lastWord.startsWith('#*') || lastWord.startsWith('$*') || lastWord.endsWith('*')) {

    const entity = contentState.createEntity(
        "MENTION",
        "MUTABLE",
        {nature: 'remedy', lastWord}
    );
    
    const entityKey = entity.getLastCreatedEntityKey();
    
    const newContentState = Modifier.replaceText(
        contentState,
        selectionState.merge({
            anchorOffset: selectionState.getEndOffset() - lastWord.length,
            focusOffset: selectionState.getEndOffset()
        }),
        lastWord,
        [getInlineStyle(lastWord[0], editorState)],
        entityKey
    );
    
    editorState = EditorState.push(
        editorState,
        newContentState
    );
}

setEditorState(editorState)

}

const getInlineStyle = (type, editorState) => {
switch (type) {
case '@':
return "REMEDY";
case '#':
return "FAMILY";
default:
return editorState.getCurrentInlineStyle();
}
}

const defaultStyle = {
padding: "5px 10px",
color: "white",
fontWeight: "bold",
borderRadius: "10px",
textDecoration: "none"
}
export const styleMap = {
'REMEDY': {
...defaultStyle,
backgroundColor: "green"
},
'FAMILY': {
...defaultStyle,
backgroundColor: "blue"
},
};

`

What it says is that when an user types a word that meets the conditions in the if statement that word has to be replaced with an entity that has a specific style. It kinda works since the entity substitution is perfect but I have a problem with the styles affecting also words not meeting the above mentioned conditions as you can see in the attached files. Why does not the replaceText function affect only the selectionRange when it comes to style? As I said, it works perfectly with the text-entity substitution.
Cattura

https://pastebin.com/m4BV1Z0c

Here you can see the code way better