Home Reference Source

application/components/common/rich-editor2/plugins/smart-quotes.js

export default function(options = {}) {
    const myOptions = Object.assign({}, {
        'enabled': false,
        'inBlocks': []
    }, options);

    function isQuote(str) {
        if (str.substr(-1) == '"' || str.substr(-1) == "'") {
            return true;
        }

        return false;
    };

    return {
        onKeyDown(e, editor, next) {

            if (myOptions.enabled !== true) {
                return next();
            }

            const {value} = editor;
            const {start} = value.selection;
            const {document} = value;

            if (!value.startText) {
                return next();
            }

            const closest = document.getClosestBlock(start.key);
            let inBlock = false;

            if (myOptions.inBlocks.length && myOptions.inBlocks.indexOf(closest.get('type')) !== -1) {
                inBlock = true;
            }
            if (myOptions.inBlocks.length && inBlock == false) {
                return next();
            }

            const startOffset = value.selection.start.offset;
            const textBefore = value.startText.text.slice(0, startOffset)

            if (!isQuote(textBefore)) {
                return next();
            }

            const checkVal = textBefore.substr(-2);
            let quote = '';

            if (textBefore.substr(-1) == "'") {
                quote = '’';
                if (!checkVal || checkVal && !/(\b|[\.\!\?])/.test(checkVal)) {
                    quote = '‘';
                }
            } else {
                quote = '”';
                if (!checkVal || checkVal && !/(\b|[\.\!\?])/.test(checkVal)) {
                    quote = '“';
                }
            }

            editor.deleteBackward(1);
            editor
                .insertText(quote);
        }
    };
}