Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draft.js. How to get all entities data from the ContentState

From official docs I know about 2 methods: get entity by its key and get last created entity. In my case, I also need a method to access all entities from current ContentState. Is there any method that could perform this? If not, is there a one that can provide all entities keys?

like image 806
Pavel Poberezhnyi Avatar asked Sep 24 '17 23:09

Pavel Poberezhnyi


People also ask

What is entity Draftjs?

An entity is an object that represents metadata for a range of text within a Draft editor. It has three properties: type: A string that indicates what kind of entity it is, e.g. 'LINK' , 'MENTION' , 'PHOTO' .

How does draft work Javascript?

To be efficient, Draft. js organizes set of consecutive characters w/ same styles(or same set of styles) in a single object called inlineStyleRanges. To be clear, this is ONLY organized like this in the “convertToRaw” output (for brevity). In actual contentState it is stored the long way for each character.

Does Facebook use draft JS?

Draft. js is used in production on Facebook, including status and comment inputs, Notes, and messenger.com.


1 Answers

const getEntities = (editorState, entityType = null) => {
    const content = editorState.getCurrentContent();
    const entities = [];
    content.getBlocksAsArray().forEach((block) => {
        let selectedEntity = null;
        block.findEntityRanges(
            (character) => {
                if (character.getEntity() !== null) {
                    const entity = content.getEntity(character.getEntity());
                    if (!entityType || (entityType && entity.getType() === entityType)) {
                        selectedEntity = {
                            entityKey: character.getEntity(),
                            blockKey: block.getKey(),
                            entity: content.getEntity(character.getEntity()),
                        };
                        return true;
                    }
                }
                return false;
            },
            (start, end) => {
                entities.push({...selectedEntity, start, end});
            });
    });
    return entities;
};
like image 105
Farbod Avatar answered Sep 19 '22 04:09

Farbod