I am developing a rich text editor with Draft.js (which is great!). The following code, which allows the user to edit a link, works logically fine, but I am not happy with the user experience.
If the user selects a portion of a link and run this code, this code divides that link into multiple links, which is NOT what the user wants.
For example, if a phase "buy this book" is linked with URL-A, and the user selects "buy this ", and changes it to URL-B, that portion will be linked with URL-B, but "book" is still linked with URL-A.
Ideally, when the user selects a portion of a linked text, I'd like to automatically expand the selection to the entire link, then execute this code.
I, however, am not able to figure out how to do it (expand the selection to the entire link).
editLink = () => {
const { editorState } = this.state;
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
return;
}
let url = ''; // default
const content = editorState.getCurrentContent();
const startKey = selection.getStartKey();
const startOffset = selection.getStartOffset();
const blockWithLinkAtBeginning = content.getBlockForKey(startKey);
const linkKey = blockWithLinkAtBeginning.getEntityAt(startOffset);
if (linkKey) {
const linkInstance = content.getEntity(linkKey);
url = linkInstance.getData().url;
}
let link = window.prompt("Paste the link", url);
if (!link) {
console.log("removing link");
const newEditorState = RichUtils.toggleLink(editorState, selection, null);
this.setState({ editorState: newEditorState });
return;
}
console.log("adding a link", link);
const contentWithEntity = content.createEntity('LINK', 'MUTABLE', { url: link });
const entityKey = contentWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, { currentContent: contentWithEntity });
const yetNewEditorState = RichUtils.toggleLink(newEditorState, newEditorState.getSelection(), entityKey);
this.setState({ editorState: yetNewEditorState} );
}
I'd really appreciate any help or suggestions.