Skip to content

Commit

Permalink
add anchors to rich text headings
Browse files Browse the repository at this point in the history
  • Loading branch information
Patricija Brečko committed Aug 19, 2024
1 parent db6555e commit 64b5eea
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions djnd/home/wagtail_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
from wagtail.rich_text import LinkHandler
from wagtail.snippets.models import register_snippet
from wagtail.snippets.views.snippets import SnippetViewSet
from wagtail.admin.rich_text.converters.html_to_contentstate import BlockElementHandler
from draftjs_exporter.dom import DOM

from django.utils.html import escape
from django.utils.text import slugify

from .forms import (
ActivityAdminModelForm,
Expand Down Expand Up @@ -67,9 +70,47 @@ def expand_db_attributes(cls, attrs):
return '<a href="%s" target="_blank">' % escape(href)


def header_with_name(props):
type_ = props.get('block', {}).get('type', '')
text = props.get('block', {}).get('text', '')
tag = 'div'
if type_ == 'header-two':
tag = 'h2'
if type_ == 'header-three':
tag = 'h3'
if type_ == 'header-four':
tag = 'h4'
return DOM.create_element(tag, {}, DOM.create_element('a', {'id': slugify(text), 'class': 'anchor'}), props['children'])


@hooks.register("register_rich_text_features")
def more_rich_text_features(features):
features.default_features.append("blockquote")

features.register_link_type(NewTabExternalLinkHandler)

features.register_converter_rule('contentstate', 'h2', {
'from_database_format': {
'h2': BlockElementHandler('header-two'),
},
'to_database_format': {
'block_map': {'header-two': header_with_name}
}
})
features.register_converter_rule('contentstate', 'h3', {
'from_database_format': {
'h3': BlockElementHandler('header-three'),
},
'to_database_format': {
'block_map': {'header-three': header_with_name}
}
})
features.register_converter_rule('contentstate', 'h4', {
'from_database_format': {
'h4': BlockElementHandler('header-four'),
},
'to_database_format': {
'block_map': {'header-four': header_with_name}
}
})

0 comments on commit 64b5eea

Please sign in to comment.