Home Reference Source

application/components/common/rich-editor/drop-cap.js

import React from 'react';
import {EditorState, RichUtils, ContentState, Entity} from 'draft-js';

/**
 * Encapsulates entity finder for drop caps
 */
const findDropCapEntities = (contentBlock, callback, contentState) => {
    contentBlock.findEntityRanges(
        (character) => {
            const entityKey = character.getEntity();
            return (
                entityKey !== null &&
                contentState.getEntity(entityKey).getType() === 'DROPCAP'
            );
        },
        callback
    );
};

/**
 * Simple callback to inject drop cap state
 */
const toggleDropCapEntity = (editorState) => {
    const selection = editorState.getSelection();

    if (selection && selection.getStartKey()) {
        const block = editorState.getCurrentContent().getBlockForKey(selection.getFocusKey());
        const key = block.getEntityAt(selection.getAnchorOffset());
        console.log(key);
        if (key && editorState.getCurrentContent().getEntity(key).getData() && editorState.getCurrentContent().getEntity(key).getData().dropcap) {
            return RichUtils.toggleLink(editorState, selection, null);
        }
    }
    const newContentState = editorState.getCurrentContent().createEntity(
        'DROPCAP', 'MUTABLE', {'dropcap': true}
    );
    const entityKey = newContentState.getLastCreatedEntityKey();

    return RichUtils.toggleLink(
        editorState,
        editorState.getSelection(),
        entityKey
    );
}

/**
 * DropCap component styles... you know... drop caps
 */
class DropCap extends React.Component {
    constructor(props) {
        super(props);
    }


    render() {
        return (
            <span className='richEditor-dropcap'>
                {this.props.children}
            </span>
        );
    };
};

export {DropCap as default, findDropCapEntities, toggleDropCapEntity};