Home Reference Source

application/util/draft-utils.js

import {EditorState} from 'draft-js';

export const expandSelection = (editorState) => {
    const selection = editorState.getSelection();

    const anchor = selection.getAnchorKey();
    const focus = selection.getFocusKey();
    const currentContent = editorState.getCurrentContent();
    const currentBlock = currentContent.getBlockForKey(anchor);
    const max = currentBlock.getText().length;

    let start = selection.getStartOffset();
    let end = selection.getEndOffset();
    let text = currentBlock.getText().slice(start, end);

    // does the area around the cursor even have text?
    if (currentBlock.getText().slice((start-1), (end+1)).search(/([a-zA-Z0-9])/) === -1) {
        // ain't nothing here...
        throw 'No text to select'
    }

    // start expanding
    let go = false;
    do {
        go = false;
        start--;
        text = currentBlock.getText().slice(start, end);
        if (text.substr(0, 1).search(/([a-zA-Z0-9])/) !== -1) {
            go = true;
        } else {
            start++;
        }

        if (start < 0) {
            start = 0;
            go = false;
        }
    } while(go);

    do {
        go = false;
        end++;
        text = currentBlock.getText().slice(start, end);
        if (text.substr(-1, 1).search(/([a-zA-Z0-9])/) !== -1) {
            go = true;
        } else {
            end--;
        }
        if (end > max) {
            end--;
            go = false;
        }
    } while(go);

    const newSelectionState = selection.merge({
        focusOffset: end,
        anchorOffset: start
    });
    return EditorState.forceSelection(
        editorState,
        newSelectionState
    )
};