Skip to content

Instantly share code, notes, and snippets.

@MattSegal
Created June 19, 2018 03:29
Show Gist options
  • Save MattSegal/ab943f5e08512320026a8e9e1a225516 to your computer and use it in GitHub Desktop.
Save MattSegal/ab943f5e08512320026a8e9e1a225516 to your computer and use it in GitHub Desktop.
Draftail Super and Subscript
# models.py
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
class MyModel(Page):
# ...
body = RichTextField(features=[
# ...
'subscript',
'superscript',
])
# wagtail_hooks.py
from wagtail.admin.rich_text.converters.html_to_contentstate import InlineStyleElementHandler
from wagtail.admin.rich_text.editors.draftail.features import InlineStyleFeature
@hooks.register('register_rich_text_features')
def register_embed_features(features):
"""Register custom richtext features with the Draftail editor"""
register_inline_feature(features, {
'name': 'superscript',
'type': INLINE_STYLES.SUPERSCRIPT,
'label': 'x²',
'tag': 'sup',
'description': 'Superscript',
})
register_inline_feature(features, {
'name': 'subscript',
'type': INLINE_STYLES.SUBSCRIPT,
'label': 'x₂',
'tag': 'sub',
'description': 'Subscript',
})
def register_inline_feature(feature_registry, config):
"""
Wrapper around Wagtail's feature registry API
Registers a new inline style feature with Draftail, like bold or italic
Params:
feature_registry: Wagtail's FeatureRegistry singleton
config: a dict of shape {
name: name of feature, used in RichTextField's features whitelist
type: type string, used to refer to the element in the frontend Draftail code
tag: tag used to wrap selected text, Eg, <strong> or <i>
description: tooltip hover description
label: tooltip icon text
style - inline element styles to be used in the Wagtail admin
class - class to be used on element in the frontend HTML
}
"""
feature_config = {
'type': config['type'],
'label': config['label'],
'description': config['description'],
}
if 'style' in config:
feature_config['style'] = config['style']
feature_registry.register_editor_plugin(
'draftail', config['name'], InlineStyleFeature(feature_config)
)
if 'class' in config:
selector = '{}[class]'.format(config['tag'])
element = {
'element': config['tag'],
'props': {'class': config['class']}
}
else:
selector = config['tag']
element = config['tag']
feature_registry.register_converter_rule('contentstate', config['name'], {
'from_database_format': {selector: InlineStyleElementHandler(config['type'])},
'to_database_format': {'style_map': {config['type']: element}},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment