Вопрос о добавлении сносок к трясогузке - PullRequest
1 голос
/ 09 мая 2020

Я делаю проект на трясогузке и хочу добавить возможность добавлять сноски к тексту в редакторе Draft js. Я читал, что это возможно здесь , но потом я попытался повторить этот успех, у меня были только ошибки. Вот мой код wagtail_hooks.py :

@hooks.register('register_rich_text_features')
def register_footnote_feature(features):
    features.default_features.append('footnote')
    """
    Registering the `footnote` feature, which uses the `FOOTNOTE` Draft.js entity type,
    and is stored as HTML with a `<span data-footnote>` tag.
    """
    feature_name = 'footnote'
    type_ = 'FOOTNOTE'

    control = {
        'type': type_,
        'label': '$',
        'description': 'footnote',
    }

    features.register_editor_plugin(
        'draftail', feature_name, draftail_features.EntityFeature(
            control,
            js=['js/footnote.js'],
            css={'all': []}
        )
    )

    features.register_converter_rule('contentstate', feature_name, {
        # Note here that the conversion is more complicated than for blocks and inline styles.
        'from_database_format': {'span[data-footnote]': FootnoteEntityElementHandler(type_)},
        'to_database_format': {'entity_decorators': {type_: footnote_entity_decorator}},
    })

def footnote_entity_decorator(props):
    """
    Draft.js ContentState to database HTML.
    Converts the FOOTNOTE entities into a span tag.
    """
    return DOM.create_element('span', {
        'data-footnote': props['footnote'],
    }, props['children'])


class FootnoteEntityElementHandler(InlineEntityElementHandler):
    """
    Database HTML to Draft.js ContentState.
    Converts the span tag into a FOOTNOTE entity, with the right data.
    """
    mutability = 'MUTABLE'

    def get_attribute_data(self, attrs):
        """
        Take the ``footnote`` value from the ``data-footnote`` HTML attribute.
        """
        return {
            'footnote': attrs['data-footnote'],

Вот код сноски. js:

const React = window.React;
const Modifier = window.DraftJS.Modifier;
const EditorState = window.DraftJS.EditorState;

class FootnoteSource extends React.Component {

    componentDidMount() {
        const { editorState, entityType, onComplete } = this.props;
        const content = editorState.getCurrentContent();

        // // Uses the Draft.js API to create a new entity with the right data.
        const contentWithEntity = content.createEntity(entityType.type, 'MUTABLE', {});
        const entityKey = contentWithEntity.getLastCreatedEntityKey();

        const editorStateWithEntity = Modifier.applyEntity(
          editorState.getCurrentContent(),
          editorState.getSelection(),
          entityKey
        )
        const nextState = EditorState.push(editorState, editorStateWithEntity, 'apply-entity');

        onComplete(nextState);
    }

    render() {
        return null;
    }
}

//import PropTypes from 'prop-types';

const Footnote = (props) => {
    const { children, entityKey, contentState } = props;
    const data = contentState.getEntity(entityKey).getData();

    return (
      <span
        role="button"
        className="FootnoteEntity"
      >
        <span class="FootnoteEntity__label" aria-hidden="true">[Footnote]</span>
        {children}
      </span>
    );
};

Footnote.propTypes = {
    entityKey: PropTypes.string.isRequired,
    contentState: PropTypes.object.isRequired,
};

window.draftail.registerPlugin({
    type: 'FOOTNOTE',
    source: FootnoteSource,
    decorator: Footnote,
});

Я получил этот код от этого вопроса . К сожалению, мне не удалось найти ни одной документации или упоминания о системе JS объектов админки Wagtail. Так что теперь я просто не знаю, что делать, потому что мне не с чем работать. Теперь в редакторе richtext я просто получаю ошибку:

Invariant Violation: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. 

Invariant Violation: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. 
    at r (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:102534)
    at i (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:102803)
    at It (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:127629)
    at c (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:133308)
    at h (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:134676)
    at v (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:135240)
    at http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:137125
    at En (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:142062)
    at Dn (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:149997)
    at xr (http://localhost:8000/static/wagtailadmin/js/vendor.js?v=a92d317e:1:169294)

    in div
    in e
    in e

Может быть, кто-нибудь знает, как расширить Draftail в админ-панели Wagtail, и мог бы выбрать меня, где копать?

...