I'm working on a custom draft.js plugin that inserts an Atomic Block with a GIF in it. I started by copying the Draft.js Image Plugin as it's almost identical. I've got my plugin working but there's one issue I'm not sure best how to solve.
To insert a GIF I'm following the example addImage Modifier in the Image Plugin. However, this always creates a new Atomic Block after the current selection. If the current block is empty, I want to place the GIF there instead.
Here's what my modifier function looks like:
const addGiphy = (editorState, giphyId) => {
const contentState = editorState.getCurrentContent();
// This creates the new Giphy entity
const contentStateWithEntity = contentState.createEntity("GIPHY", "IMMUTABLE", {
giphyId
});
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
// Work out where the selection is
const currentSelection = editorState.getSelection();
const currentKey = currentSelection.getStartKey();
const currentBlock = editorState.getCurrentContent().getBlockForKey(currentKey);
let newEditorState;
if (currentBlock.getType() === "unstyled" && currentBlock.getText() === "") {
// Current line is empty, we should convert to a gif atomic block
// <INSERT MAGIC HERE>
} else {
// There's stuff here, lets create a new block
newEditorState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, " ");
}
return EditorState.forceSelection(
newEditorState,
newEditorState.getCurrentContent().getSelectionAfter()
);
};
I'm not sure how to handle the condition of converting the current block to an Atomic Block. Is this Draft.js best practice? Alternatively, am I better to always insert a new block and then remove the empty block?
For clarity, this same issue also exists in the Image Plugin, it's not something I've introduced.