import wagtail.admin.rich_text.editors.draftail.features as draftail_features from django.utils.html import escape from wagtail import hooks from wagtail.admin.rich_text.converters.html_to_contentstate import ( InlineStyleElementHandler, ) from wagtail.rich_text import LinkHandler from donate.constants import font_colors class ExternalLinkHandler(LinkHandler): identifier = "external" @classmethod def expand_db_attributes(cls, attrs): href = attrs["href"] return '<a href="%s" target="_blank" rel="noopener nofollower">' % escape(href) @hooks.register("register_rich_text_features") def register_external_link(features): features.register_link_type(ExternalLinkHandler) @hooks.register("register_rich_text_features") def register_font_color_feature(features): for color_name, color_value in font_colors: feature_name = "font_color_" + color_value type_ = "FONT_COLOR_" + color_value tag = f"span{color_name.lower()}" # This must be a "custom" HTML element in order for wagtail to correctly save it :-) control = { "type": type_, "label": color_name, "description": color_name + " text color", "style": {"color": color_value}, } features.register_editor_plugin( "draftail", feature_name, draftail_features.InlineStyleFeature(control) ) db_conversion = { "from_database_format": {tag: InlineStyleElementHandler(type_)}, "to_database_format": { "style_map": { type_: {"element": tag, "props": {"style": "color: " + color_value}} } }, } features.register_converter_rule("contentstate", feature_name, db_conversion)